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 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 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 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}