Skip to main content

xs/nu/commands/
last_command.rs

1use nu_engine::CallExt;
2use nu_protocol::engine::{Call, Command, EngineState, Stack};
3use nu_protocol::{
4    Category, ListStream, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
5};
6
7use crate::nu::util;
8use crate::store::{FollowOption, ReadOptions, Store};
9
10#[derive(Clone)]
11pub struct LastCommand {
12    store: Store,
13}
14
15impl LastCommand {
16    pub fn new(store: Store) -> Self {
17        Self { store }
18    }
19}
20
21impl Command for LastCommand {
22    fn name(&self) -> &str {
23        ".last"
24    }
25
26    fn signature(&self) -> Signature {
27        Signature::build(".last")
28            .input_output_types(vec![(Type::Nothing, Type::Any)])
29            .optional(
30                "topic",
31                SyntaxShape::Any,
32                "topic pattern(s) to get most recent frames from: string (commas allowed) or list (default: all topics)",
33            )
34            .optional(
35                "count",
36                SyntaxShape::Int,
37                "number of frames to return (default: 1)",
38            )
39            .switch(
40                "follow",
41                "long poll for updates to most recent frame",
42                Some('f'),
43            )
44            .switch(
45                "with-timestamp",
46                "include timestamp extracted from frame ID",
47                None,
48            )
49            .category(Category::Experimental)
50    }
51
52    fn description(&self) -> &str {
53        "get the most recent frame(s) for a topic"
54    }
55
56    fn run(
57        &self,
58        engine_state: &EngineState,
59        stack: &mut Stack,
60        call: &Call,
61        _input: PipelineData,
62    ) -> Result<PipelineData, ShellError> {
63        let raw_topic: Option<Value> = call.opt(engine_state, stack, 0)?;
64        let raw_count: Option<i64> = call.opt(engine_state, stack, 1)?;
65        let follow = call.has_flag(engine_state, stack, "follow")?;
66        let with_timestamp = call.has_flag(engine_state, stack, "with-timestamp")?;
67        let span = call.head;
68
69        // Disambiguate: if topic is an integer (or parses as one) and count is
70        // absent, treat it as the count (topics cannot start with digits per
71        // ADR 0002)
72        let (topic, n) = match (raw_topic, raw_count) {
73            (Some(Value::Int { val, .. }), None) if val > 0 => (None, val as usize),
74            (Some(Value::String { val, .. }), None) if val.parse::<usize>().is_ok() => {
75                (None, val.parse::<usize>().unwrap())
76            }
77            (raw_topic, raw_count) => (
78                raw_topic.map(util::topic_value_to_string).transpose()?,
79                raw_count.map(|v| v as usize).unwrap_or(1),
80            ),
81        };
82
83        if follow {
84            // Follow mode: stream historical-then-new through the receiver. The
85            // consumer dropping the ListStream cancels the producer task (L1).
86            let options = ReadOptions::builder()
87                .last(n)
88                .maybe_topic(topic)
89                .follow(FollowOption::On)
90                .build();
91
92            let mut rx = self.store.read(options);
93            let rt = self.store.runtime();
94            let signals = engine_state.signals().clone();
95            let waiting = signals.clone();
96            let stream = ListStream::new(
97                std::iter::from_fn(move || {
98                    let item = util::follow_recv(&mut rx, rt.as_ref(), &waiting)?;
99                    Some(util::follow_value(&item, span, |f| {
100                        util::frame_to_value(f, span, with_timestamp)
101                    }))
102                }),
103                span,
104                signals,
105            );
106
107            return Ok(PipelineData::ListStream(stream, None));
108        }
109
110        // Historical-only mode. Collect from the read receiver here (not via a
111        // shared eager helper) so we can preserve the single-value semantics for
112        // count == 1: a bare `.last topic` returns one Value, not a one-element
113        // list. The producer closes the channel once replay completes, so this
114        // loop terminates. blocking_recv parks the caller thread; callers that
115        // reach `.last` during an actor's async setup run the config eval on a
116        // dedicated thread (see parse_config), so this never parks a runtime
117        // thread.
118        let options = ReadOptions::builder().last(n).maybe_topic(topic).build();
119
120        let mut rx = self.store.read(options);
121        let frames: Vec<Value> = std::iter::from_fn(move || {
122            // None when the producer finishes replay; a read that does not
123            // follow never ends with an error.
124            let frame = rx.blocking_recv()?.ok()?;
125            Some(util::frame_to_value(&frame, span, with_timestamp))
126        })
127        .collect();
128
129        if frames.is_empty() {
130            Ok(PipelineData::Empty)
131        } else if frames.len() == 1 {
132            Ok(PipelineData::Value(
133                frames.into_iter().next().unwrap(),
134                None,
135            ))
136        } else {
137            Ok(PipelineData::Value(Value::list(frames, span), None))
138        }
139    }
140}