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 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 "ignore-errors",
45 "ignore missing data (make all cell path members optional)",
46 Some('i'),
47 )
48 .switch(
49 "sensitive",
50 "get path in a case sensitive manner (deprecated)",
51 Some('s'),
52 )
53 .allow_variants_without_examples(true)
54 .category(Category::Filters)
55 }
56
57 fn examples(&self) -> Vec<Example> {
58 vec![
59 Example {
60 description: "Get an item from a list",
61 example: "[0 1 2] | get 1",
62 result: Some(Value::test_int(1)),
63 },
64 Example {
65 description: "Get a column from a table",
66 example: "[{A: A0}] | get A",
67 result: Some(Value::list(
68 vec![Value::test_string("A0")],
69 Span::test_data(),
70 )),
71 },
72 Example {
73 description: "Get a cell from a table",
74 example: "[{A: A0}] | get 0.A",
75 result: Some(Value::test_string("A0")),
76 },
77 Example {
78 description: "Extract the name of the 3rd record in a list (same as `ls | $in.name.2`)",
79 example: "ls | get name.2",
80 result: None,
81 },
82 Example {
83 description: "Extract the name of the 3rd record in a list",
84 example: "ls | get 2.name",
85 result: None,
86 },
87 Example {
88 description: "Getting Path/PATH in a case insensitive way",
89 example: "$env | get paTH!",
90 result: None,
91 },
92 Example {
93 description: "Getting Path in a case sensitive way, won't work for 'PATH'",
94 example: "$env | get Path",
95 result: None,
96 },
97 ]
98 }
99
100 fn is_const(&self) -> bool {
101 true
102 }
103
104 fn run_const(
105 &self,
106 working_set: &StateWorkingSet,
107 call: &Call,
108 input: PipelineData,
109 ) -> Result<PipelineData, ShellError> {
110 let cell_path: CellPath = call.req_const(working_set, 0)?;
111 let rest: Vec<CellPath> = call.rest_const(working_set, 1)?;
112 let ignore_errors = call.has_flag_const(working_set, "ignore-errors")?;
113 let metadata = input.metadata();
114 action(
115 input,
116 cell_path,
117 rest,
118 ignore_errors,
119 working_set.permanent().signals().clone(),
120 call.head,
121 )
122 .map(|x| x.set_metadata(metadata))
123 }
124
125 fn run(
126 &self,
127 engine_state: &EngineState,
128 stack: &mut Stack,
129 call: &Call,
130 input: PipelineData,
131 ) -> Result<PipelineData, ShellError> {
132 let cell_path: CellPath = call.req(engine_state, stack, 0)?;
133 let rest: Vec<CellPath> = call.rest(engine_state, stack, 1)?;
134 let ignore_errors = call.has_flag(engine_state, stack, "ignore-errors")?;
135 let metadata = input.metadata();
136 action(
137 input,
138 cell_path,
139 rest,
140 ignore_errors,
141 engine_state.signals().clone(),
142 call.head,
143 )
144 .map(|x| x.set_metadata(metadata))
145 }
146
147 fn deprecation_info(&self) -> Vec<DeprecationEntry> {
148 vec![
149 DeprecationEntry {
150 ty: DeprecationType::Flag("sensitive".into()),
151 report_mode: ReportMode::FirstUse,
152 since: Some("0.105.0".into()),
153 expected_removal: None,
154 help: Some("Cell-paths are now case-sensitive by default.\nTo access fields case-insensitively, add `!` after the relevant path member.".into())
155 }
156 ]
157 }
158}
159
160fn action(
161 input: PipelineData,
162 mut cell_path: CellPath,
163 mut rest: Vec<CellPath>,
164 ignore_errors: bool,
165 signals: Signals,
166 span: Span,
167) -> Result<PipelineData, ShellError> {
168 if ignore_errors {
169 cell_path.make_optional();
170 for path in &mut rest {
171 path.make_optional();
172 }
173 }
174
175 match input {
176 PipelineData::Empty => return Err(ShellError::PipelineEmpty { dst_span: span }),
177 PipelineData::Value(val @ Value::Nothing { .. }, ..) if !ignore_errors => {
179 return Err(ShellError::OnlySupportsThisInputType {
180 exp_input_type: "table or record".into(),
181 wrong_type: "nothing".into(),
182 dst_span: span,
183 src_span: val.span(),
184 });
185 }
186 _ => (),
187 }
188
189 if rest.is_empty() {
190 follow_cell_path_into_stream(input, signals, cell_path.members, span)
191 } else {
192 let mut output = vec![];
193
194 let paths = std::iter::once(cell_path).chain(rest);
195
196 let input = input.into_value(span)?;
197
198 for path in paths {
199 output.push(input.follow_cell_path(&path.members)?.into_owned());
200 }
201
202 Ok(output.into_iter().into_pipeline_data(span, signals))
203 }
204}
205
206pub fn follow_cell_path_into_stream(
214 data: PipelineData,
215 signals: Signals,
216 cell_path: Vec<PathMember>,
217 head: Span,
218) -> Result<PipelineData, ShellError> {
219 let has_int_member = cell_path
222 .iter()
223 .any(|it| matches!(it, PathMember::Int { .. }));
224 match data {
225 PipelineData::ListStream(stream, ..) if !has_int_member => {
226 let result = stream
227 .into_iter()
228 .map(move |value| {
229 let span = value.span();
230
231 value
232 .follow_cell_path(&cell_path)
233 .map(Cow::into_owned)
234 .unwrap_or_else(|error| Value::error(error, span))
235 })
236 .into_pipeline_data(head, signals);
237
238 Ok(result)
239 }
240
241 _ => data
242 .follow_cell_path(&cell_path, head)
243 .map(|x| x.into_pipeline_data()),
244 }
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 #[test]
252 fn test_examples() {
253 use crate::test_examples;
254
255 test_examples(Get)
256 }
257}