1use nu_engine::command_prelude::*;
2use nu_protocol::{Signals, shell_error::io::IoError};
3use std::io::Read;
4
5#[cfg(feature = "sqlite")]
6use crate::database::SQLiteQueryBuilder;
7
8#[derive(Clone)]
9pub struct First;
10
11impl Command for First {
12 fn name(&self) -> &str {
13 "first"
14 }
15
16 fn signature(&self) -> Signature {
17 Signature::build("first")
18 .input_output_types(vec![
19 (
20 Type::List(Box::new(Type::Any)),
23 Type::Any,
24 ),
25 (Type::Binary, Type::Binary),
26 (Type::Range, Type::Any),
27 ])
28 .optional(
29 "rows",
30 SyntaxShape::Int,
31 "Starting from the front, the number of rows to return.",
32 )
33 .switch("strict", "Throw an error if input is empty.", Some('s'))
34 .allow_variants_without_examples(true)
35 .category(Category::Filters)
36 }
37
38 fn search_terms(&self) -> Vec<&str> {
39 vec!["head"]
40 }
41
42 fn description(&self) -> &str {
43 "Return only the first several rows of the input. Counterpart of `last`. Opposite of `skip`."
44 }
45
46 fn run(
47 &self,
48 engine_state: &EngineState,
49 stack: &mut Stack,
50 call: &Call,
51 input: PipelineData,
52 ) -> Result<PipelineData, ShellError> {
53 first_helper(engine_state, stack, call, input)
54 }
55
56 fn examples(&self) -> Vec<Example<'_>> {
57 vec![
58 Example {
59 description: "Return the first item of a list/table.",
60 example: "[1 2 3] | first",
61 result: Some(Value::test_int(1)),
62 },
63 Example {
64 description: "Return the first 2 items of a list/table.",
65 example: "[1 2 3] | first 2",
66 result: Some(Value::list(
67 vec![Value::test_int(1), Value::test_int(2)],
68 Span::test_data(),
69 )),
70 },
71 Example {
72 description: "Return the first 2 bytes of a binary value.",
73 example: "0x[01 23 45] | first 2",
74 result: Some(Value::binary(vec![0x01, 0x23], Span::test_data())),
75 },
76 Example {
77 description: "Return the first item of a range.",
78 example: "1..3 | first",
79 result: Some(Value::test_int(1)),
80 },
81 ]
82 }
83}
84
85fn first_helper(
86 engine_state: &EngineState,
87 stack: &mut Stack,
88 call: &Call,
89 input: PipelineData,
90) -> Result<PipelineData, ShellError> {
91 let head = call.head;
92 let rows: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?;
93 let strict_mode = call.has_flag(engine_state, stack, "strict")?;
94
95 let return_single_element = rows.is_none();
100 let rows = if let Some(rows) = rows {
101 if rows.item < 0 {
102 return Err(ShellError::NeedsPositiveValue { span: rows.span });
103 } else {
104 rows.item as usize
105 }
106 } else {
107 1
108 };
109
110 let mut input = input;
111 let input_meta = input.take_metadata();
112
113 if rows == 0 {
120 return match input {
121 PipelineData::Value(val, _) if matches!(&val, Value::Binary { .. }) => Ok(
122 Value::binary(Vec::new(), val.span()).into_pipeline_data_with_metadata(
123 input_meta.map(|m| m.with_content_type(None)),
124 ),
125 ),
126 PipelineData::ByteStream(stream, _) => {
127 if stream.type_().is_binary_coercible() {
128 let span = stream.span();
129 Ok(
130 Value::binary(Vec::new(), span).into_pipeline_data_with_metadata(
131 input_meta.map(|m| m.with_content_type(None)),
132 ),
133 )
134 } else {
135 Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(input_meta))
136 }
137 }
138 _ => Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(input_meta)),
139 };
140 }
141
142 match input {
143 PipelineData::Value(val, _) => {
144 let span = val.span();
145 match val {
146 Value::List { mut vals, .. } => {
147 if return_single_element {
148 if let Some(val) = vals.first_mut() {
149 Ok(std::mem::take(val).into_pipeline_data_with_metadata(input_meta))
150 } else if strict_mode {
151 Err(ShellError::AccessEmptyContent { span: head })
152 } else {
153 Ok(Value::nothing(head).into_pipeline_data_with_metadata(input_meta))
156 }
157 } else {
158 vals.truncate(rows);
159 Ok(Value::list(vals, span).into_pipeline_data_with_metadata(input_meta))
160 }
161 }
162 Value::Binary { mut val, .. } => {
163 let binary_meta = input_meta.map(|m| m.with_content_type(None));
165 if return_single_element {
166 if let Some(&val) = val.first() {
167 Ok(Value::int(val.into(), span)
168 .into_pipeline_data_with_metadata(binary_meta))
169 } else if strict_mode {
170 Err(ShellError::AccessEmptyContent { span: head })
171 } else {
172 Ok(Value::nothing(head).into_pipeline_data_with_metadata(binary_meta))
175 }
176 } else {
177 val.truncate(rows);
178 Ok(Value::binary(val, span).into_pipeline_data_with_metadata(binary_meta))
179 }
180 }
181 Value::Range { val, .. } => {
182 let mut iter = val.into_range_iter(span, Signals::empty());
183 if return_single_element {
184 if let Some(v) = iter.next() {
185 Ok(v.into_pipeline_data_with_metadata(input_meta))
186 } else if strict_mode {
187 Err(ShellError::AccessEmptyContent { span: head })
188 } else {
189 Ok(Value::nothing(head).into_pipeline_data_with_metadata(input_meta))
192 }
193 } else {
194 Ok(iter.take(rows).into_pipeline_data_with_metadata(
195 span,
196 engine_state.signals().clone(),
197 input_meta,
198 ))
199 }
200 }
201 Value::Error { error, .. } => Err(*error),
203 #[cfg(feature = "sqlite")]
204 Value::Custom {
206 val: custom_val,
207 internal_span,
208 ..
209 } => {
210 if let Some(table) = custom_val.as_any().downcast_ref::<SQLiteQueryBuilder>() {
211 if return_single_element {
212 let new_table = table.clone().with_limit(1);
214 let result = new_table.execute(head)?;
215 let value = result.into_value(head)?;
216 if let Value::List { vals, .. } = value {
217 if let Some(val) = vals.into_iter().next() {
218 Ok(val.into_pipeline_data_with_metadata(input_meta))
219 } else if strict_mode {
220 Err(ShellError::AccessEmptyContent { span: head })
221 } else {
222 Ok(Value::nothing(head)
225 .into_pipeline_data_with_metadata(input_meta))
226 }
227 } else {
228 Err(ShellError::NushellFailed {
229 msg: "Expected list from SQLiteQueryBuilder".into(),
230 })
231 }
232 } else {
233 let new_table = table.clone().with_limit(rows as i64);
235 new_table
236 .execute(head)
237 .map(|data| data.set_metadata(input_meta))
238 }
239 } else {
240 Err(ShellError::OnlySupportsThisInputType {
241 exp_input_type: "list, binary or range".into(),
242 wrong_type: custom_val.type_name(),
243 dst_span: head,
244 src_span: internal_span,
245 })
246 }
247 }
248 other => Err(ShellError::OnlySupportsThisInputType {
249 exp_input_type: "list, binary or range".into(),
250 wrong_type: other.get_type().to_string(),
251 dst_span: head,
252 src_span: other.span(),
253 }),
254 }
255 }
256 PipelineData::ListStream(stream, _) => {
257 if return_single_element {
258 if let Some(v) = stream.into_iter().next() {
259 Ok(v.into_pipeline_data_with_metadata(input_meta))
260 } else if strict_mode {
261 Err(ShellError::AccessEmptyContent { span: head })
262 } else {
263 Ok(Value::nothing(head).into_pipeline_data_with_metadata(input_meta))
266 }
267 } else {
268 Ok(PipelineData::list_stream(
269 stream.modify(|iter| iter.take(rows)),
270 input_meta,
271 ))
272 }
273 }
274 PipelineData::ByteStream(stream, _) => {
275 if stream.type_().is_binary_coercible() {
276 let span = stream.span();
277 let metadata = input_meta.map(|m| m.with_content_type(None));
278 if let Some(mut reader) = stream.reader() {
279 if return_single_element {
280 let mut byte = [0u8];
282 if reader
283 .read(&mut byte)
284 .map_err(|err| IoError::new(err, span, None))?
285 > 0
286 {
287 Ok(Value::int(byte[0] as i64, head)
288 .into_pipeline_data_with_metadata(metadata))
289 } else {
290 Err(ShellError::AccessEmptyContent { span: head })
291 }
292 } else {
293 Ok(PipelineData::byte_stream(
295 ByteStream::read(
296 reader.take(rows as u64),
297 head,
298 Signals::empty(),
299 ByteStreamType::Binary,
300 ),
301 metadata,
302 ))
303 }
304 } else {
305 Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata))
306 }
307 } else {
308 Err(ShellError::OnlySupportsThisInputType {
309 exp_input_type: "list, binary or range".into(),
310 wrong_type: stream.type_().describe().into(),
311 dst_span: head,
312 src_span: stream.span(),
313 })
314 }
315 }
316 PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType {
317 exp_input_type: "list, binary or range".into(),
318 wrong_type: "null".into(),
319 dst_span: call.head,
320 src_span: call.head,
321 }),
322 }
323}
324#[cfg(test)]
325mod test {
326 use super::*;
327 #[test]
328 fn test_examples() -> nu_test_support::Result {
329 nu_test_support::test().examples(First)
330 }
331}