nu_command/filters/
get.rs

1use std::borrow::Cow;
2
3use nu_engine::command_prelude::*;
4use nu_protocol::{DeprecationEntry, DeprecationType, ReportMode, Signals, ast::PathMember};
5
6#[derive(Clone)]
7pub struct Get;
8
9impl Command for Get {
10    fn name(&self) -> &str {
11        "get"
12    }
13
14    fn description(&self) -> &str {
15        "Extract data using a cell path."
16    }
17
18    fn extra_description(&self) -> &str {
19        r#"This is equivalent to using the cell path access syntax: `$env.OS` is the same as `$env | get OS`.
20
21If multiple cell paths are given, this will produce a list of values."#
22    }
23
24    fn signature(&self) -> nu_protocol::Signature {
25        Signature::build("get")
26            .input_output_types(vec![
27                (
28                    // TODO: This is too permissive; if we could express this
29                    // using a type parameter it would be List<T> -> T.
30                    Type::List(Box::new(Type::Any)),
31                    Type::Any,
32                ),
33                (Type::table(), Type::Any),
34                (Type::record(), Type::Any),
35                (Type::Nothing, Type::Nothing),
36            ])
37            .required(
38                "cell_path",
39                SyntaxShape::CellPath,
40                "The cell path to the data.",
41            )
42            .rest("rest", SyntaxShape::CellPath, "Additional cell paths.")
43            .switch(
44                "optional",
45                "make all cell path members optional (returns `null` for missing values)",
46                Some('o'),
47            )
48            .switch(
49                "ignore-case",
50                "make all cell path members case insensitive",
51                None,
52            )
53            .switch(
54                "ignore-errors",
55                "ignore missing data (make all cell path members optional) (deprecated)",
56                Some('i'),
57            )
58            .switch(
59                "sensitive",
60                "get path in a case sensitive manner (deprecated)",
61                Some('s'),
62            )
63            .allow_variants_without_examples(true)
64            .category(Category::Filters)
65    }
66
67    fn examples(&self) -> Vec<Example<'_>> {
68        vec![
69            Example {
70                description: "Get an item from a list",
71                example: "[0 1 2] | get 1",
72                result: Some(Value::test_int(1)),
73            },
74            Example {
75                description: "Get a column from a table",
76                example: "[{A: A0}] | get A",
77                result: Some(Value::list(
78                    vec![Value::test_string("A0")],
79                    Span::test_data(),
80                )),
81            },
82            Example {
83                description: "Get a column from a table where some rows don't have that column, using optional cell-path syntax",
84                example: "[{A: A0, B: B0}, {B: B1}, {A: A2, B: B2}] | get A?",
85                result: Some(Value::list(
86                    vec![
87                        Value::test_string("A0"),
88                        Value::test_nothing(),
89                        Value::test_string("A2"),
90                    ],
91                    Span::test_data(),
92                )),
93            },
94            Example {
95                description: "Get a column from a table where some rows don't have that column, using the optional flag",
96                example: "[{A: A0, B: B0}, {B: B1}, {A: A2, B: B2}] | get -o A",
97                result: Some(Value::list(
98                    vec![
99                        Value::test_string("A0"),
100                        Value::test_nothing(),
101                        Value::test_string("A2"),
102                    ],
103                    Span::test_data(),
104                )),
105            },
106            Example {
107                description: "Get a cell from a table",
108                example: "[{A: A0}] | get 0.A",
109                result: Some(Value::test_string("A0")),
110            },
111            Example {
112                description: "Extract the name of the 3rd record in a list (same as `ls | $in.name.2`)",
113                example: "ls | get name.2",
114                result: None,
115            },
116            Example {
117                description: "Extract the name of the 3rd record in a list",
118                example: "ls | get 2.name",
119                result: None,
120            },
121            Example {
122                description: "Getting environment variables in a case insensitive way, using case insensitive cell-path syntax",
123                example: "$env | get home! path!",
124                result: None,
125            },
126            Example {
127                description: "Getting environment variables in a case insensitive way, using the '--ignore-case' flag",
128                example: "$env | get --ignore-case home path",
129                result: None,
130            },
131            Example {
132                description: "Getting Path in a case sensitive way, won't work for 'PATH'",
133                example: "$env | get Path",
134                result: None,
135            },
136        ]
137    }
138
139    fn is_const(&self) -> bool {
140        true
141    }
142
143    fn run_const(
144        &self,
145        working_set: &StateWorkingSet,
146        call: &Call,
147        input: PipelineData,
148    ) -> Result<PipelineData, ShellError> {
149        let cell_path: CellPath = call.req_const(working_set, 0)?;
150        let rest: Vec<CellPath> = call.rest_const(working_set, 1)?;
151        let optional = call.has_flag_const(working_set, "optional")?
152            || call.has_flag_const(working_set, "ignore-errors")?;
153        let ignore_case = call.has_flag_const(working_set, "ignore-case")?;
154        let metadata = input.metadata();
155        action(
156            input,
157            cell_path,
158            rest,
159            optional,
160            ignore_case,
161            working_set.permanent().signals().clone(),
162            call.head,
163        )
164        .map(|x| x.set_metadata(metadata))
165    }
166
167    fn run(
168        &self,
169        engine_state: &EngineState,
170        stack: &mut Stack,
171        call: &Call,
172        input: PipelineData,
173    ) -> Result<PipelineData, ShellError> {
174        let cell_path: CellPath = call.req(engine_state, stack, 0)?;
175        let rest: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
176        let optional = call.has_flag(engine_state, stack, "optional")?
177            || call.has_flag(engine_state, stack, "ignore-errors")?;
178        let ignore_case = call.has_flag(engine_state, stack, "ignore-case")?;
179        let metadata = input.metadata();
180        action(
181            input,
182            cell_path,
183            rest,
184            optional,
185            ignore_case,
186            engine_state.signals().clone(),
187            call.head,
188        )
189        .map(|x| x.set_metadata(metadata))
190    }
191
192    fn deprecation_info(&self) -> Vec<DeprecationEntry> {
193        vec![
194            DeprecationEntry {
195                ty: DeprecationType::Flag("sensitive".into()),
196                report_mode: ReportMode::FirstUse,
197                since: Some("0.105.0".into()),
198                expected_removal: None,
199                help: Some("Cell-paths are now case-sensitive by default.\nTo access fields case-insensitively, add `!` after the relevant path member.".into())
200            },
201            DeprecationEntry {
202                ty: DeprecationType::Flag("ignore-errors".into()),
203                report_mode: ReportMode::FirstUse,
204                since: Some("0.106.0".into()),
205                expected_removal: None,
206                help: Some("This flag has been renamed to `--optional (-o)` to better reflect its behavior.".into())
207            }
208        ]
209    }
210}
211
212fn action(
213    input: PipelineData,
214    mut cell_path: CellPath,
215    mut rest: Vec<CellPath>,
216    optional: bool,
217    ignore_case: bool,
218    signals: Signals,
219    span: Span,
220) -> Result<PipelineData, ShellError> {
221    if optional {
222        cell_path.make_optional();
223        for path in &mut rest {
224            path.make_optional();
225        }
226    }
227
228    if ignore_case {
229        cell_path.make_insensitive();
230        for path in &mut rest {
231            path.make_insensitive();
232        }
233    }
234
235    if let PipelineData::Empty = input {
236        return Err(ShellError::PipelineEmpty { dst_span: span });
237    }
238
239    if rest.is_empty() {
240        follow_cell_path_into_stream(input, signals, cell_path.members, span)
241    } else {
242        let mut output = vec![];
243
244        let paths = std::iter::once(cell_path).chain(rest);
245
246        let input = input.into_value(span)?;
247
248        for path in paths {
249            output.push(input.follow_cell_path(&path.members)?.into_owned());
250        }
251
252        Ok(output.into_iter().into_pipeline_data(span, signals))
253    }
254}
255
256// the PipelineData.follow_cell_path function, when given a
257// stream, collects it into a vec before doing its job
258//
259// this is fine, since it returns a Result<Value ShellError>,
260// but if we want to follow a PipelineData into a cell path and
261// return another PipelineData, then we have to take care to
262// make sure it streams
263pub fn follow_cell_path_into_stream(
264    data: PipelineData,
265    signals: Signals,
266    cell_path: Vec<PathMember>,
267    head: Span,
268) -> Result<PipelineData, ShellError> {
269    // when given an integer/indexing, we fallback to
270    // the default nushell indexing behaviour
271    let has_int_member = cell_path
272        .iter()
273        .any(|it| matches!(it, PathMember::Int { .. }));
274    match data {
275        PipelineData::ListStream(stream, ..) if !has_int_member => {
276            let result = stream
277                .into_iter()
278                .map(move |value| {
279                    let span = value.span();
280
281                    value
282                        .follow_cell_path(&cell_path)
283                        .map(Cow::into_owned)
284                        .unwrap_or_else(|error| Value::error(error, span))
285                })
286                .into_pipeline_data(head, signals);
287
288            Ok(result)
289        }
290
291        _ => data
292            .follow_cell_path(&cell_path, head)
293            .map(|x| x.into_pipeline_data()),
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn test_examples() {
303        use crate::test_examples;
304
305        test_examples(Get)
306    }
307}