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 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 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().map(|m| m.with_content_type(None));
103
104 if rows == 0 {
106 return Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(metadata));
107 }
108
109 match input {
110 PipelineData::Value(val, _) => {
111 let span = val.span();
112 match val {
113 Value::List { mut vals, .. } => {
114 if return_single_element {
115 if let Some(val) = vals.first_mut() {
116 Ok(std::mem::take(val).into_pipeline_data())
117 } else {
118 Err(ShellError::AccessEmptyContent { span: head })
119 }
120 } else {
121 vals.truncate(rows);
122 Ok(Value::list(vals, span).into_pipeline_data_with_metadata(metadata))
123 }
124 }
125 Value::Binary { mut val, .. } => {
126 if return_single_element {
127 if let Some(&val) = val.first() {
128 Ok(Value::int(val.into(), span).into_pipeline_data())
129 } else {
130 Err(ShellError::AccessEmptyContent { span: head })
131 }
132 } else {
133 val.truncate(rows);
134 Ok(Value::binary(val, span).into_pipeline_data_with_metadata(metadata))
135 }
136 }
137 Value::Range { val, .. } => {
138 let mut iter = val.into_range_iter(span, Signals::empty());
139 if return_single_element {
140 if let Some(v) = iter.next() {
141 Ok(v.into_pipeline_data())
142 } else {
143 Err(ShellError::AccessEmptyContent { span: head })
144 }
145 } else {
146 Ok(iter.take(rows).into_pipeline_data_with_metadata(
147 span,
148 engine_state.signals().clone(),
149 metadata,
150 ))
151 }
152 }
153 Value::Error { error, .. } => Err(*error),
155 other => Err(ShellError::OnlySupportsThisInputType {
156 exp_input_type: "list, binary or range".into(),
157 wrong_type: other.get_type().to_string(),
158 dst_span: head,
159 src_span: other.span(),
160 }),
161 }
162 }
163 PipelineData::ListStream(stream, metadata) => {
164 if return_single_element {
165 if let Some(v) = stream.into_iter().next() {
166 Ok(v.into_pipeline_data())
167 } else {
168 Err(ShellError::AccessEmptyContent { span: head })
169 }
170 } else {
171 Ok(PipelineData::list_stream(
172 stream.modify(|iter| iter.take(rows)),
173 metadata,
174 ))
175 }
176 }
177 PipelineData::ByteStream(stream, metadata) => {
178 if stream.type_().is_binary_coercible() {
179 let span = stream.span();
180 let metadata = metadata.map(|m| m.with_content_type(None));
181 if let Some(mut reader) = stream.reader() {
182 if return_single_element {
183 let mut byte = [0u8];
185 if reader
186 .read(&mut byte)
187 .map_err(|err| IoError::new(err, span, None))?
188 > 0
189 {
190 Ok(Value::int(byte[0] as i64, head).into_pipeline_data())
191 } else {
192 Err(ShellError::AccessEmptyContent { span: head })
193 }
194 } else {
195 Ok(PipelineData::byte_stream(
197 ByteStream::read(
198 reader.take(rows as u64),
199 head,
200 Signals::empty(),
201 ByteStreamType::Binary,
202 ),
203 metadata,
204 ))
205 }
206 } else {
207 Ok(PipelineData::empty())
208 }
209 } else {
210 Err(ShellError::OnlySupportsThisInputType {
211 exp_input_type: "list, binary or range".into(),
212 wrong_type: stream.type_().describe().into(),
213 dst_span: head,
214 src_span: stream.span(),
215 })
216 }
217 }
218 PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType {
219 exp_input_type: "list, binary or range".into(),
220 wrong_type: "null".into(),
221 dst_span: call.head,
222 src_span: call.head,
223 }),
224 }
225}
226#[cfg(test)]
227mod test {
228 use super::*;
229 #[test]
230 fn test_examples() {
231 use crate::test_examples;
232
233 test_examples(First {})
234 }
235}