xs/nu/commands/
last_command.rs1use 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 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 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 frame = util::follow_recv(&mut rx, rt.as_ref(), &waiting)?;
99 Some(util::frame_to_value(&frame, span, with_timestamp))
100 }),
101 span,
102 signals,
103 );
104
105 return Ok(PipelineData::ListStream(stream, None));
106 }
107
108 let options = ReadOptions::builder().last(n).maybe_topic(topic).build();
117
118 let mut rx = self.store.read(options);
119 let frames: Vec<Value> = std::iter::from_fn(move || {
120 let frame = rx.blocking_recv()?; Some(util::frame_to_value(&frame, span, with_timestamp))
122 })
123 .collect();
124
125 if frames.is_empty() {
126 Ok(PipelineData::Empty)
127 } else if frames.len() == 1 {
128 Ok(PipelineData::Value(
129 frames.into_iter().next().unwrap(),
130 None,
131 ))
132 } else {
133 Ok(PipelineData::Value(Value::list(frames, span), None))
134 }
135 }
136}