nu_cmd_lang/core_commands/
collect.rs1use nu_engine::command_prelude::*;
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct Collect;
6
7impl Command for Collect {
8 fn name(&self) -> &str {
9 "collect"
10 }
11
12 fn signature(&self) -> Signature {
13 Signature::build("collect")
14 .input_output_types(vec![(Type::Any, Type::Any)])
15 .optional(
16 "closure",
17 SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
18 "The closure to run once the stream is collected.",
19 )
20 .switch(
21 "keep-env",
22 "Let the closure affect environment variables.",
23 None,
24 )
25 .category(Category::Core)
26 }
27
28 fn description(&self) -> &str {
29 "Collect a stream into a value."
30 }
31
32 fn extra_description(&self) -> &str {
33 r#"If provided, run a closure with the collected value as input.
34
35The entire stream will be collected into one value in memory, so if the stream
36is particularly large, this can cause high memory usage."#
37 }
38
39 fn command_type(&self) -> CommandType {
40 CommandType::Keyword
41 }
42
43 fn run(
44 &self,
45 _engine_state: &EngineState,
46 _stack: &mut Stack,
47 _call: &Call,
48 _input: PipelineData,
49 ) -> Result<PipelineData, ShellError> {
50 eprintln!(
53 "Tried to execute 'run' for the 'collect' command: this code path should never be reached in IR mode"
54 );
55 unreachable!();
56 }
57
58 fn examples(&self) -> Vec<Example<'_>> {
59 vec![
60 Example {
61 description: "Use the second value in the stream.",
62 example: "[1 2 3] | collect { |x| $x.1 }",
63 result: Some(Value::test_int(2)),
64 },
65 Example {
66 description: "Read and write to the same file.",
67 example: "open file.txt | collect | save -f file.txt",
68 result: None,
69 },
70 ]
71 }
72}
73
74#[cfg(test)]
75mod test {
76 use super::*;
77 use crate::Do;
78
79 #[test]
80 fn test_examples() {
81 use crate::test_examples_with_commands;
82
83 test_examples_with_commands(Collect {}, &[&Do {}])
84 }
85}