nu_command/filters/
first.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::{Signals, shell_error::io::IoError};
3use std::io::Read;
4
5#[derive(Clone)]
6pub struct First;
7
8impl Command for First {
9    fn name(&self) -> &str {
10        "first"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("first")
15            .input_output_types(vec![
16                (
17                    // TODO: This is too permissive; if we could express this
18                    // using a type parameter it would be List<T> -> T.
19                    Type::List(Box::new(Type::Any)),
20                    Type::Any,
21                ),
22                (Type::Binary, Type::Binary),
23                (Type::Range, Type::Any),
24            ])
25            .optional(
26                "rows",
27                SyntaxShape::Int,
28                "Starting from the front, the number of rows to return.",
29            )
30            .allow_variants_without_examples(true)
31            .category(Category::Filters)
32    }
33
34    fn description(&self) -> &str {
35        "Return only the first several rows of the input. Counterpart of `last`. Opposite of `skip`."
36    }
37
38    fn run(
39        &self,
40        engine_state: &EngineState,
41        stack: &mut Stack,
42        call: &Call,
43        input: PipelineData,
44    ) -> Result<PipelineData, ShellError> {
45        first_helper(engine_state, stack, call, input)
46    }
47
48    fn examples(&self) -> Vec<Example> {
49        vec![
50            Example {
51                description: "Return the first item of a list/table",
52                example: "[1 2 3] | first",
53                result: Some(Value::test_int(1)),
54            },
55            Example {
56                description: "Return the first 2 items of a list/table",
57                example: "[1 2 3] | first 2",
58                result: Some(Value::list(
59                    vec![Value::test_int(1), Value::test_int(2)],
60                    Span::test_data(),
61                )),
62            },
63            Example {
64                description: "Return the first 2 bytes of a binary value",
65                example: "0x[01 23 45] | first 2",
66                result: Some(Value::binary(vec![0x01, 0x23], Span::test_data())),
67            },
68            Example {
69                description: "Return the first item of a range",
70                example: "1..3 | first",
71                result: Some(Value::test_int(1)),
72            },
73        ]
74    }
75}
76
77fn first_helper(
78    engine_state: &EngineState,
79    stack: &mut Stack,
80    call: &Call,
81    input: PipelineData,
82) -> Result<PipelineData, ShellError> {
83    let head = call.head;
84    let rows: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?;
85
86    // FIXME: for backwards compatibility reasons, if `rows` is not specified we
87    // return a single element and otherwise we return a single list. We should probably
88    // remove `rows` so that `first` always returns a single element; getting a list of
89    // the first N elements is covered by `take`
90    let return_single_element = rows.is_none();
91    let rows = if let Some(rows) = rows {
92        if rows.item < 0 {
93            return Err(ShellError::NeedsPositiveValue { span: rows.span });
94        } else {
95            rows.item as usize
96        }
97    } else {
98        1
99    };
100
101    let metadata = input.metadata();
102
103    // early exit for `first 0`
104    if rows == 0 {
105        return Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(metadata));
106    }
107
108    match input {
109        PipelineData::Value(val, _) => {
110            let span = val.span();
111            match val {
112                Value::List { mut vals, .. } => {
113                    if return_single_element {
114                        if let Some(val) = vals.first_mut() {
115                            Ok(std::mem::take(val).into_pipeline_data())
116                        } else {
117                            Err(ShellError::AccessEmptyContent { span: head })
118                        }
119                    } else {
120                        vals.truncate(rows);
121                        Ok(Value::list(vals, span).into_pipeline_data_with_metadata(metadata))
122                    }
123                }
124                Value::Binary { mut val, .. } => {
125                    if return_single_element {
126                        if let Some(&val) = val.first() {
127                            Ok(Value::int(val.into(), span).into_pipeline_data())
128                        } else {
129                            Err(ShellError::AccessEmptyContent { span: head })
130                        }
131                    } else {
132                        val.truncate(rows);
133                        Ok(Value::binary(val, span).into_pipeline_data_with_metadata(metadata))
134                    }
135                }
136                Value::Range { val, .. } => {
137                    let mut iter = val.into_range_iter(span, Signals::empty());
138                    if return_single_element {
139                        if let Some(v) = iter.next() {
140                            Ok(v.into_pipeline_data())
141                        } else {
142                            Err(ShellError::AccessEmptyContent { span: head })
143                        }
144                    } else {
145                        Ok(iter.take(rows).into_pipeline_data_with_metadata(
146                            span,
147                            engine_state.signals().clone(),
148                            metadata,
149                        ))
150                    }
151                }
152                // Propagate errors by explicitly matching them before the final case.
153                Value::Error { error, .. } => Err(*error),
154                other => Err(ShellError::OnlySupportsThisInputType {
155                    exp_input_type: "list, binary or range".into(),
156                    wrong_type: other.get_type().to_string(),
157                    dst_span: head,
158                    src_span: other.span(),
159                }),
160            }
161        }
162        PipelineData::ListStream(stream, metadata) => {
163            if return_single_element {
164                if let Some(v) = stream.into_iter().next() {
165                    Ok(v.into_pipeline_data())
166                } else {
167                    Err(ShellError::AccessEmptyContent { span: head })
168                }
169            } else {
170                Ok(PipelineData::ListStream(
171                    stream.modify(|iter| iter.take(rows)),
172                    metadata,
173                ))
174            }
175        }
176        PipelineData::ByteStream(stream, metadata) => {
177            if stream.type_().is_binary_coercible() {
178                let span = stream.span();
179                if let Some(mut reader) = stream.reader() {
180                    if return_single_element {
181                        // Take a single byte
182                        let mut byte = [0u8];
183                        if reader
184                            .read(&mut byte)
185                            .map_err(|err| IoError::new(err, span, None))?
186                            > 0
187                        {
188                            Ok(Value::int(byte[0] as i64, head).into_pipeline_data())
189                        } else {
190                            Err(ShellError::AccessEmptyContent { span: head })
191                        }
192                    } else {
193                        // Just take 'rows' bytes off the stream, mimicking the binary behavior
194                        Ok(PipelineData::ByteStream(
195                            ByteStream::read(
196                                reader.take(rows as u64),
197                                head,
198                                Signals::empty(),
199                                ByteStreamType::Binary,
200                            ),
201                            metadata,
202                        ))
203                    }
204                } else {
205                    Ok(PipelineData::Empty)
206                }
207            } else {
208                Err(ShellError::OnlySupportsThisInputType {
209                    exp_input_type: "list, binary or range".into(),
210                    wrong_type: stream.type_().describe().into(),
211                    dst_span: head,
212                    src_span: stream.span(),
213                })
214            }
215        }
216        PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType {
217            exp_input_type: "list, binary or range".into(),
218            wrong_type: "null".into(),
219            dst_span: call.head,
220            src_span: call.head,
221        }),
222    }
223}
224#[cfg(test)]
225mod test {
226    use super::*;
227    #[test]
228    fn test_examples() {
229        use crate::test_examples;
230
231        test_examples(First {})
232    }
233}