repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/to/yaml.rs
crates/nu-command/src/formats/to/yaml.rs
use nu_engine::command_prelude::*; use nu_protocol::ast::PathMember; #[derive(Clone)] pub struct ToYaml; impl Command for ToYaml { fn name(&self) -> &str { "to yaml" } fn signature(&self) -> Signature { Signature::build("to yaml") .input_output_types(vec![(Type::Any, Type::String)]) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Convert table into .yaml/.yml text." } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Outputs a YAML string representing the contents of this table", example: r#"[[foo bar]; ["1" "2"]] | to yaml"#, result: Some(Value::test_string("- foo: '1'\n bar: '2'\n")), }] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; let input = input.try_expand_range()?; to_yaml(engine_state, input, head, serialize_types) } } #[derive(Clone)] pub struct ToYml; impl Command for ToYml { fn name(&self) -> &str { "to yml" } fn signature(&self) -> Signature { Signature::build("to yml") .input_output_types(vec![(Type::Any, Type::String)]) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Convert table into .yaml/.yml text." } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Outputs a YAML string representing the contents of this table", example: r#"[[foo bar]; ["1" "2"]] | to yml"#, result: Some(Value::test_string("- foo: '1'\n bar: '2'\n")), }] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; let input = input.try_expand_range()?; to_yaml(engine_state, input, head, serialize_types) } } pub fn value_to_yaml_value( engine_state: &EngineState, v: &Value, serialize_types: bool, ) -> Result<serde_yaml::Value, ShellError> { Ok(match &v { Value::Bool { val, .. } => serde_yaml::Value::Bool(*val), Value::Int { val, .. } => serde_yaml::Value::Number(serde_yaml::Number::from(*val)), Value::Filesize { val, .. } => { serde_yaml::Value::Number(serde_yaml::Number::from(val.get())) } Value::Duration { val, .. } => serde_yaml::Value::String(val.to_string()), Value::Date { val, .. } => serde_yaml::Value::String(val.to_string()), Value::Range { .. } => serde_yaml::Value::Null, Value::Float { val, .. } => serde_yaml::Value::Number(serde_yaml::Number::from(*val)), Value::String { val, .. } | Value::Glob { val, .. } => { serde_yaml::Value::String(val.clone()) } Value::Record { val, .. } => { let mut m = serde_yaml::Mapping::new(); for (k, v) in &**val { m.insert( serde_yaml::Value::String(k.clone()), value_to_yaml_value(engine_state, v, serialize_types)?, ); } serde_yaml::Value::Mapping(m) } Value::List { vals, .. } => { let mut out = vec![]; for value in vals { out.push(value_to_yaml_value(engine_state, value, serialize_types)?); } serde_yaml::Value::Sequence(out) } Value::Closure { val, .. } => { if serialize_types { let block = engine_state.get_block(val.block_id); if let Some(span) = block.span { let contents_bytes = engine_state.get_span_contents(span); let contents_string = String::from_utf8_lossy(contents_bytes); serde_yaml::Value::String(contents_string.to_string()) } else { serde_yaml::Value::String(format!( "unable to retrieve block contents for yaml block_id {}", val.block_id.get() )) } } else { serde_yaml::Value::Null } } Value::Nothing { .. } => serde_yaml::Value::Null, Value::Error { error, .. } => return Err(*error.clone()), Value::Binary { val, .. } => serde_yaml::Value::Sequence( val.iter() .map(|x| serde_yaml::Value::Number(serde_yaml::Number::from(*x))) .collect(), ), Value::CellPath { val, .. } => serde_yaml::Value::Sequence( val.members .iter() .map(|x| match &x { PathMember::String { val, .. } => Ok(serde_yaml::Value::String(val.clone())), PathMember::Int { val, .. } => { Ok(serde_yaml::Value::Number(serde_yaml::Number::from(*val))) } }) .collect::<Result<Vec<serde_yaml::Value>, ShellError>>()?, ), Value::Custom { .. } => serde_yaml::Value::Null, }) } fn to_yaml( engine_state: &EngineState, input: PipelineData, head: Span, serialize_types: bool, ) -> Result<PipelineData, ShellError> { let metadata = input .metadata() .unwrap_or_default() // Per RFC-9512, application/yaml should be used .with_content_type(Some("application/yaml".into())); let value = input.into_value(head)?; let yaml_value = value_to_yaml_value(engine_state, &value, serialize_types)?; match serde_yaml::to_string(&yaml_value) { Ok(serde_yaml_string) => { Ok(Value::string(serde_yaml_string, head) .into_pipeline_data_with_metadata(Some(metadata))) } _ => Ok(Value::error( ShellError::CantConvert { to_type: "YAML".into(), from_type: value.get_type().to_string(), span: head, help: None, }, head, ) .into_pipeline_data_with_metadata(Some(metadata))), } } #[cfg(test)] mod test { use super::*; use crate::{Get, Metadata}; use nu_cmd_lang::eval_pipeline_without_terminal_expression; #[test] fn test_examples() { use crate::test_examples; test_examples(ToYaml {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { // Base functions that are needed for testing // Try to keep this working set small to keep tests running as fast as possible let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(ToYaml {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(Get {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = "{a: 1 b: 2} | to yaml | metadata | get content_type | $in"; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_string("application/yaml"), result.expect("There should be a result") ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/to/csv.rs
crates/nu-command/src/formats/to/csv.rs
use std::sync::Arc; use crate::formats::to::delimited::to_delimited_data; use nu_engine::command_prelude::*; use nu_protocol::Config; use super::delimited::ToDelimitedDataArgs; #[derive(Clone)] pub struct ToCsv; impl Command for ToCsv { fn name(&self) -> &str { "to csv" } fn signature(&self) -> Signature { Signature::build("to csv") .input_output_types(vec![ (Type::record(), Type::String), (Type::table(), Type::String), ]) .named( "separator", SyntaxShape::String, "a character to separate columns, defaults to ','", Some('s'), ) .switch( "noheaders", "do not output the columns names as the first row", Some('n'), ) .named( "columns", SyntaxShape::List(SyntaxShape::String.into()), "the names (in order) of the columns to use", None, ) .category(Category::Formats) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs a CSV string representing the contents of this table", example: "[[foo bar]; [1 2]] | to csv", result: Some(Value::test_string("foo,bar\n1,2\n")), }, Example { description: "Outputs a CSV string representing the contents of this table", example: "[[foo bar]; [1 2]] | to csv --separator ';' ", result: Some(Value::test_string("foo;bar\n1;2\n")), }, Example { description: "Outputs a CSV string representing the contents of this record", example: "{a: 1 b: 2} | to csv", result: Some(Value::test_string("a,b\n1,2\n")), }, Example { description: "Outputs a CSV stream with column names pre-determined", example: "[[foo bar baz]; [1 2 3]] | to csv --columns [baz foo]", result: Some(Value::test_string("baz,foo\n3,1\n")), }, ] } fn description(&self) -> &str { "Convert table into .csv text ." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let noheaders = call.has_flag(engine_state, stack, "noheaders")?; let separator: Option<Spanned<String>> = call.get_flag(engine_state, stack, "separator")?; let columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?; let config = engine_state.config.clone(); to_csv(input, noheaders, separator, columns, head, config) } } fn to_csv( input: PipelineData, noheaders: bool, separator: Option<Spanned<String>>, columns: Option<Vec<String>>, head: Span, config: Arc<Config>, ) -> Result<PipelineData, ShellError> { let sep = match separator { Some(Spanned { item: s, span, .. }) => { if s == r"\t" { Spanned { item: '\t', span } } else { let vec_s: Vec<char> = s.chars().collect(); if vec_s.len() != 1 { return Err(ShellError::TypeMismatch { err_message: "Expected a single separator char from --separator" .to_string(), span, }); }; Spanned { item: vec_s[0], span: head, } } } _ => Spanned { item: ',', span: head, }, }; to_delimited_data( ToDelimitedDataArgs { noheaders, separator: sep, columns, format_name: "CSV", input, head, content_type: Some(mime::TEXT_CSV.to_string()), }, config, ) } #[cfg(test)] mod test { use nu_cmd_lang::eval_pipeline_without_terminal_expression; use crate::{Get, Metadata}; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ToCsv {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { // Base functions that are needed for testing // Try to keep this working set small to keep tests running as fast as possible let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(ToCsv {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(Get {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = "{a: 1 b: 2} | to csv | metadata | get content_type | $in"; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_string("text/csv"), result.expect("There should be a result") ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/to/delimited.rs
crates/nu-command/src/formats/to/delimited.rs
use csv::WriterBuilder; use nu_cmd_base::formats::to::delimited::merge_descriptors; use nu_protocol::{ ByteStream, ByteStreamType, Config, PipelineData, ShellError, Signals, Span, Spanned, Value, shell_error::io::IoError, }; use std::{iter, sync::Arc}; fn make_csv_error(error: csv::Error, format_name: &str, head: Span) -> ShellError { if let csv::ErrorKind::Io(error) = error.kind() { IoError::new(error, head, None).into() } else { ShellError::GenericError { error: format!("Failed to generate {format_name} data"), msg: error.to_string(), span: Some(head), help: None, inner: vec![], } } } fn to_string_tagged_value( v: &Value, config: &Config, format_name: &'static str, ) -> Result<String, ShellError> { match &v { Value::String { .. } | Value::Bool { .. } | Value::Int { .. } | Value::Duration { .. } | Value::Binary { .. } | Value::Custom { .. } | Value::Filesize { .. } | Value::CellPath { .. } | Value::Float { .. } => Ok(v.clone().to_abbreviated_string(config)), Value::Date { val, .. } => Ok(val.to_string()), Value::Nothing { .. } => Ok(String::new()), // Propagate existing errors Value::Error { error, .. } => Err(*error.clone()), _ => Err(make_cant_convert_error(v, format_name)), } } fn make_unsupported_input_error( r#type: impl std::fmt::Display, head: Span, span: Span, ) -> ShellError { ShellError::UnsupportedInput { msg: "expected table or record".to_string(), input: format!("input type: {type}"), msg_span: head, input_span: span, } } fn make_cant_convert_error(value: &Value, format_name: &'static str) -> ShellError { ShellError::CantConvert { to_type: "string".into(), from_type: value.get_type().to_string(), span: value.span(), help: Some(format!( "only simple values are supported for {format_name} output" )), } } pub struct ToDelimitedDataArgs { pub noheaders: bool, pub separator: Spanned<char>, pub columns: Option<Vec<String>>, pub format_name: &'static str, pub input: PipelineData, pub head: Span, pub content_type: Option<String>, } pub fn to_delimited_data( ToDelimitedDataArgs { noheaders, separator, columns, format_name, input, head, content_type, }: ToDelimitedDataArgs, config: Arc<Config>, ) -> Result<PipelineData, ShellError> { let mut input = input; let span = input.span().unwrap_or(head); let metadata = Some( input .metadata() .unwrap_or_default() .with_content_type(content_type), ); let separator = u8::try_from(separator.item).map_err(|_| ShellError::IncorrectValue { msg: "separator must be an ASCII character".into(), val_span: separator.span, call_span: head, })?; // Check to ensure the input is likely one of our supported types first. We can't check a stream // without consuming it though match input { PipelineData::Value(Value::List { .. } | Value::Record { .. }, _) => (), PipelineData::Value(Value::Error { error, .. }, _) => return Err(*error), PipelineData::Value(other, _) => { return Err(make_unsupported_input_error(other.get_type(), head, span)); } PipelineData::ByteStream(..) => { return Err(make_unsupported_input_error("byte stream", head, span)); } PipelineData::ListStream(..) => (), PipelineData::Empty => (), } // Determine the columns we'll use. This is necessary even if we don't write the header row, // because we need to write consistent columns. let columns = match columns { Some(columns) => columns, None => { // The columns were not provided. We need to detect them, and in order to do so, we have // to convert the input into a value first, so that we can find all of them let value = input.into_value(span)?; let columns = match &value { Value::List { vals, .. } => merge_descriptors(vals), Value::Record { val, .. } => val.columns().cloned().collect(), _ => return Err(make_unsupported_input_error(value.get_type(), head, span)), }; input = PipelineData::value(value, metadata.clone()); columns } }; // Generate a byte stream of all of the values in the pipeline iterator, with a non-strict // iterator so we can still accept plain records. let mut iter = input.into_iter(); // If we're configured to generate a header, we generate it first, then set this false let mut is_header = !noheaders; let stream = ByteStream::from_fn( head, Signals::empty(), ByteStreamType::String, move |buffer| { let mut wtr = WriterBuilder::new() .delimiter(separator) .from_writer(buffer); if is_header { // Unless we are configured not to write a header, we write the header row now, once, // before everything else. wtr.write_record(&columns) .map_err(|err| make_csv_error(err, format_name, head))?; is_header = false; Ok(true) } else if let Some(row) = iter.next() { // Write each column of a normal row, in order let record = row.into_record()?; for column in &columns { let field = record .get(column) .map(|v| to_string_tagged_value(v, &config, format_name)) .unwrap_or(Ok(String::new()))?; wtr.write_field(field) .map_err(|err| make_csv_error(err, format_name, head))?; } // End the row wtr.write_record(iter::empty::<String>()) .map_err(|err| make_csv_error(err, format_name, head))?; Ok(true) } else { Ok(false) } }, ); Ok(PipelineData::byte_stream(stream, metadata)) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/to/toml.rs
crates/nu-command/src/formats/to/toml.rs
use chrono::{DateTime, Datelike, FixedOffset, Timelike}; use nu_engine::command_prelude::*; use nu_protocol::{PipelineMetadata, ast::PathMember}; #[derive(Clone)] pub struct ToToml; impl Command for ToToml { fn name(&self) -> &str { "to toml" } fn signature(&self) -> Signature { Signature::build("to toml") .input_output_types(vec![(Type::record(), Type::String)]) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Convert record into .toml text." } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Outputs an TOML string representing the contents of this record", example: r#"{foo: 1 bar: 'qwe'} | to toml"#, result: Some(Value::test_string("foo = 1\nbar = \"qwe\"\n")), }] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; to_toml(engine_state, input, head, serialize_types) } } // Helper method to recursively convert nu_protocol::Value -> toml::Value // This shouldn't be called at the top-level fn helper( engine_state: &EngineState, v: &Value, serialize_types: bool, ) -> Result<toml::Value, ShellError> { Ok(match &v { Value::Bool { val, .. } => toml::Value::Boolean(*val), Value::Int { val, .. } => toml::Value::Integer(*val), Value::Filesize { val, .. } => toml::Value::Integer(val.get()), Value::Duration { val, .. } => toml::Value::String(val.to_string()), Value::Date { val, .. } => toml::Value::Datetime(to_toml_datetime(val)), Value::Range { .. } => toml::Value::String("<Range>".to_string()), Value::Float { val, .. } => toml::Value::Float(*val), Value::String { val, .. } | Value::Glob { val, .. } => toml::Value::String(val.clone()), Value::Record { val, .. } => { let mut m = toml::map::Map::new(); for (k, v) in &**val { m.insert(k.clone(), helper(engine_state, v, serialize_types)?); } toml::Value::Table(m) } Value::List { vals, .. } => { toml::Value::Array(toml_list(engine_state, vals, serialize_types)?) } Value::Closure { val, .. } => { if serialize_types { let block = engine_state.get_block(val.block_id); if let Some(span) = block.span { let contents_bytes = engine_state.get_span_contents(span); let contents_string = String::from_utf8_lossy(contents_bytes); toml::Value::String(contents_string.to_string()) } else { toml::Value::String(format!( "unable to retrieve block contents for toml block_id {}", val.block_id.get() )) } } else { toml::Value::String(format!("closure_{}", val.block_id.get())) } } Value::Nothing { .. } => toml::Value::String("<Nothing>".to_string()), Value::Error { error, .. } => return Err(*error.clone()), Value::Binary { val, .. } => toml::Value::Array( val.iter() .map(|x| toml::Value::Integer(*x as i64)) .collect(), ), Value::CellPath { val, .. } => toml::Value::Array( val.members .iter() .map(|x| match &x { PathMember::String { val, .. } => Ok(toml::Value::String(val.clone())), PathMember::Int { val, .. } => Ok(toml::Value::Integer(*val as i64)), }) .collect::<Result<Vec<toml::Value>, ShellError>>()?, ), Value::Custom { .. } => toml::Value::String("<Custom Value>".to_string()), }) } fn toml_list( engine_state: &EngineState, input: &[Value], serialize_types: bool, ) -> Result<Vec<toml::Value>, ShellError> { let mut out = vec![]; for value in input { out.push(helper(engine_state, value, serialize_types)?); } Ok(out) } fn toml_into_pipeline_data( toml_value: &toml::Value, value_type: Type, span: Span, metadata: Option<PipelineMetadata>, ) -> Result<PipelineData, ShellError> { let new_md = Some( metadata .unwrap_or_default() .with_content_type(Some("text/x-toml".into())), ); match toml::to_string_pretty(&toml_value) { Ok(serde_toml_string) => { Ok(Value::string(serde_toml_string, span).into_pipeline_data_with_metadata(new_md)) } _ => Ok(Value::error( ShellError::CantConvert { to_type: "TOML".into(), from_type: value_type.to_string(), span, help: None, }, span, ) .into_pipeline_data_with_metadata(new_md)), } } fn value_to_toml_value( engine_state: &EngineState, v: &Value, head: Span, serialize_types: bool, ) -> Result<toml::Value, ShellError> { match v { Value::Record { .. } | Value::Closure { .. } => helper(engine_state, v, serialize_types), // Propagate existing errors Value::Error { error, .. } => Err(*error.clone()), _ => Err(ShellError::UnsupportedInput { msg: format!("{:?} is not valid top-level TOML", v.get_type()), input: "value originates from here".into(), msg_span: head, input_span: v.span(), }), } } fn to_toml( engine_state: &EngineState, input: PipelineData, span: Span, serialize_types: bool, ) -> Result<PipelineData, ShellError> { let metadata = input.metadata(); let value = input.into_value(span)?; let toml_value = value_to_toml_value(engine_state, &value, span, serialize_types)?; match toml_value { toml::Value::Array(ref vec) => match vec[..] { [toml::Value::Table(_)] => toml_into_pipeline_data( vec.iter().next().expect("this should never trigger"), value.get_type(), span, metadata, ), _ => toml_into_pipeline_data(&toml_value, value.get_type(), span, metadata), }, _ => toml_into_pipeline_data(&toml_value, value.get_type(), span, metadata), } } /// Convert chrono datetime into a toml::Value datetime. The latter uses its /// own ad-hoc datetime types, which makes this somewhat convoluted. fn to_toml_datetime(datetime: &DateTime<FixedOffset>) -> toml::value::Datetime { let date = toml::value::Date { // TODO: figure out what to do with BC dates, because the toml // crate doesn't support them. Same for large years, which // don't fit in u16. year: datetime.year_ce().1 as u16, // Panic: this is safe, because chrono guarantees that the month // value will be between 1 and 12 and the day will be between 1 // and 31 month: datetime.month() as u8, day: datetime.day() as u8, }; let time = toml::value::Time { // Panic: same as before, chorono guarantees that all of the following 3 // methods return values less than 65'000 hour: datetime.hour() as u8, minute: datetime.minute() as u8, second: datetime.second() as u8, nanosecond: datetime.nanosecond(), }; let offset = toml::value::Offset::Custom { // Panic: minute timezone offset fits into i16 (that's more than // 1000 hours) minutes: (-datetime.timezone().utc_minus_local() / 60) as i16, }; toml::value::Datetime { date: Some(date), time: Some(time), offset: Some(offset), } } #[cfg(test)] mod tests { use super::*; use chrono::TimeZone; #[test] fn test_examples() { use crate::test_examples; test_examples(ToToml {}) } #[test] fn to_toml_creates_correct_date() { let engine_state = EngineState::new(); let serialize_types = false; let test_date = Value::date( chrono::FixedOffset::east_opt(60 * 120) .unwrap() .with_ymd_and_hms(1980, 10, 12, 10, 12, 44) .unwrap(), Span::test_data(), ); let reference_date = toml::Value::Datetime(toml::value::Datetime { date: Some(toml::value::Date { year: 1980, month: 10, day: 12, }), time: Some(toml::value::Time { hour: 10, minute: 12, second: 44, nanosecond: 0, }), offset: Some(toml::value::Offset::Custom { minutes: 120 }), }); let result = helper(&engine_state, &test_date, serialize_types); assert!(result.is_ok_and(|res| res == reference_date)); } #[test] fn test_value_to_toml_value() { // // Positive Tests // let engine_state = EngineState::new(); let serialize_types = false; let mut m = indexmap::IndexMap::new(); m.insert("rust".to_owned(), Value::test_string("editor")); m.insert("is".to_owned(), Value::nothing(Span::test_data())); m.insert( "features".to_owned(), Value::list( vec![Value::test_string("hello"), Value::test_string("array")], Span::test_data(), ), ); let tv = value_to_toml_value( &engine_state, &Value::record(m.into_iter().collect(), Span::test_data()), Span::test_data(), serialize_types, ) .expect("Expected Ok from valid TOML dictionary"); assert_eq!( tv.get("features"), Some(&toml::Value::Array(vec![ toml::Value::String("hello".to_owned()), toml::Value::String("array".to_owned()) ])) ); // // Negative Tests // value_to_toml_value( &engine_state, &Value::test_string("not_valid"), Span::test_data(), serialize_types, ) .expect_err("Expected non-valid toml (String) to cause error!"); value_to_toml_value( &engine_state, &Value::list(vec![Value::test_string("1")], Span::test_data()), Span::test_data(), serialize_types, ) .expect_err("Expected non-valid toml (Table) to cause error!"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/par_each.rs
crates/nu-command/src/filters/par_each.rs
use super::utils::chain_error_with_input; use nu_engine::{ClosureEvalOnce, command_prelude::*}; use nu_protocol::{Signals, engine::Closure}; use rayon::prelude::*; #[derive(Clone)] pub struct ParEach; impl Command for ParEach { fn name(&self) -> &str { "par-each" } fn description(&self) -> &str { "Run a closure on each row of the input list in parallel, creating a new list with the results." } fn signature(&self) -> nu_protocol::Signature { Signature::build("par-each") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::table(), Type::List(Box::new(Type::Any))), (Type::Any, Type::Any), ]) .named( "threads", SyntaxShape::Int, "the number of threads to use", Some('t'), ) .switch( "keep-order", "keep sequence of output same as the order of input", Some('k'), ) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[1 2 3] | par-each {|e| $e * 2 }", description: "Multiplies each number. Note that the list will become arbitrarily disordered.", result: None, }, Example { example: r#"[1 2 3] | par-each --keep-order {|e| $e * 2 }"#, description: "Multiplies each number, keeping an original order", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(4), Value::test_int(6), ])), }, Example { example: r#"1..3 | enumerate | par-each {|p| update item ($p.item * 2)} | sort-by item | get item"#, description: "Enumerate and sort-by can be used to reconstruct the original order", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(4), Value::test_int(6), ])), }, Example { example: r#"[foo bar baz] | par-each {|e| $e + '!' } | sort"#, description: "Output can still be sorted afterward", result: Some(Value::test_list(vec![ Value::test_string("bar!"), Value::test_string("baz!"), Value::test_string("foo!"), ])), }, Example { example: r#"[1 2 3] | enumerate | par-each { |e| if $e.item == 2 { $"found 2 at ($e.index)!"} }"#, description: "Iterate over each element, producing a list showing indexes of any 2s", result: Some(Value::test_list(vec![Value::test_string("found 2 at 1!")])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { fn create_pool(num_threads: usize) -> Result<rayon::ThreadPool, ShellError> { match rayon::ThreadPoolBuilder::new() .num_threads(num_threads) .build() { Err(e) => Err(e).map_err(|e| ShellError::GenericError { error: "Error creating thread pool".into(), msg: e.to_string(), span: Some(Span::unknown()), help: None, inner: vec![], }), Ok(pool) => Ok(pool), } } let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let threads: Option<usize> = call.get_flag(engine_state, stack, "threads")?; let max_threads = threads.unwrap_or(0); let keep_order = call.has_flag(engine_state, stack, "keep-order")?; let metadata = input.metadata(); // A helper function sorts the output if needed let apply_order = |mut vec: Vec<(usize, Value)>| { if keep_order { // It runs inside the rayon's thread pool so parallel sorting can be used. // There are no identical indexes, so unstable sorting can be used. vec.par_sort_unstable_by_key(|(index, _)| *index); } vec.into_iter().map(|(_, val)| val) }; match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(value, ..) => { let span = value.span(); match value { Value::List { vals, .. } => Ok(create_pool(max_threads)?.install(|| { let vec = vals .into_par_iter() .enumerate() .map(move |(index, value)| { let span = value.span(); let is_error = value.is_error(); let value = ClosureEvalOnce::new(engine_state, stack, closure.clone()) .run_with_value(value) .and_then(|data| data.into_value(span)) .unwrap_or_else(|err| { Value::error( chain_error_with_input(err, is_error, span), span, ) }); (index, value) }) .collect::<Vec<_>>(); apply_order(vec).into_pipeline_data(span, engine_state.signals().clone()) })), Value::Range { val, .. } => Ok(create_pool(max_threads)?.install(|| { let vec = val .into_range_iter(span, Signals::empty()) .enumerate() .par_bridge() .map(move |(index, value)| { let span = value.span(); let is_error = value.is_error(); let value = ClosureEvalOnce::new(engine_state, stack, closure.clone()) .run_with_value(value) .and_then(|data| data.into_value(span)) .unwrap_or_else(|err| { Value::error( chain_error_with_input(err, is_error, span), span, ) }); (index, value) }) .collect::<Vec<_>>(); apply_order(vec).into_pipeline_data(span, engine_state.signals().clone()) })), // This match allows non-iterables to be accepted, // which is currently considered undesirable (Nov 2022). value => { ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value) } } } PipelineData::ListStream(stream, ..) => Ok(create_pool(max_threads)?.install(|| { let vec = stream .into_iter() .enumerate() .par_bridge() .map(move |(index, value)| { let span = value.span(); let is_error = value.is_error(); let value = ClosureEvalOnce::new(engine_state, stack, closure.clone()) .run_with_value(value) .and_then(|data| data.into_value(head)) .unwrap_or_else(|err| { Value::error(chain_error_with_input(err, is_error, span), span) }); (index, value) }) .collect::<Vec<_>>(); apply_order(vec).into_pipeline_data(head, engine_state.signals().clone()) })), PipelineData::ByteStream(stream, ..) => { if let Some(chunks) = stream.chunks() { Ok(create_pool(max_threads)?.install(|| { let vec = chunks .enumerate() .par_bridge() .map(move |(index, value)| { let value = match value { Ok(value) => value, Err(err) => return (index, Value::error(err, head)), }; let value = ClosureEvalOnce::new(engine_state, stack, closure.clone()) .run_with_value(value) .and_then(|data| data.into_value(head)) .unwrap_or_else(|err| Value::error(err, head)); (index, value) }) .collect::<Vec<_>>(); apply_order(vec).into_pipeline_data(head, engine_state.signals().clone()) })) } else { Ok(PipelineData::empty()) } } } .and_then(|x| x.filter(|v| !v.is_nothing(), engine_state.signals())) .map(|data| data.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ParEach {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/tee.rs
crates/nu-command/src/filters/tee.rs
use nu_engine::{command_prelude::*, get_eval_block_with_early_return}; #[cfg(feature = "os")] use nu_protocol::process::ChildPipe; #[cfg(test)] use nu_protocol::shell_error; use nu_protocol::{ ByteStream, ByteStreamSource, OutDest, PipelineMetadata, Signals, byte_stream::copy_with_signals, engine::Closure, report_shell_error, shell_error::io::IoError, }; use std::{ io::{self, Read, Write}, sync::{ Arc, mpsc::{self, Sender}, }, thread::{self, JoinHandle}, }; #[derive(Clone)] pub struct Tee; impl Command for Tee { fn name(&self) -> &str { "tee" } fn description(&self) -> &str { "Copy a stream to another command in parallel." } fn extra_description(&self) -> &str { r#"This is useful for doing something else with a stream while still continuing to use it in your pipeline."# } fn signature(&self) -> Signature { Signature::build("tee") .input_output_type(Type::Any, Type::Any) .switch( "stderr", "For external commands: copy the standard error stream instead.", Some('e'), ) .required( "closure", SyntaxShape::Closure(None), "The other command to send the stream to.", ) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "http get http://example.org/ | tee { save example.html }", description: "Save a webpage to a file while also printing it", result: None, }, Example { example: "nu -c 'print -e error; print ok' | tee --stderr { save error.log } | complete", description: "Save error messages from an external command to a file without \ redirecting them", result: None, }, Example { example: "1..100 | tee { each { print } } | math sum | wrap sum", description: "Print numbers and their sum", result: None, }, Example { example: "10000 | tee { 1..$in | print } | $in * 5", description: "Do something with a value on another thread, while also passing through the value", result: Some(Value::test_int(50000)), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let from_io_error = IoError::factory(head, None); let use_stderr = call.has_flag(engine_state, stack, "stderr")?; let closure: Spanned<Closure> = call.req(engine_state, stack, 0)?; let closure_span = closure.span; let closure = closure.item; let engine_state_arc = Arc::new(engine_state.clone()); let mut eval_block = { let closure_engine_state = engine_state_arc.clone(); let mut closure_stack = stack .captures_to_stack_preserve_out_dest(closure.captures) .reset_pipes(); let eval_block_with_early_return = get_eval_block_with_early_return(engine_state); move |input| { let result = eval_block_with_early_return( &closure_engine_state, &mut closure_stack, closure_engine_state.get_block(closure.block_id), input, ) .map(|p| p.body); // Make sure to drain any iterator produced to avoid unexpected behavior result.and_then(|data| data.drain().map(|_| ())) } }; // Convert values that can be represented as streams into streams. Streams can pass errors // through later, so if we treat string/binary/list as a stream instead, it's likely that // we can get the error back to the original thread. let span = input.span().unwrap_or(head); let input = input .try_into_stream(engine_state) .unwrap_or_else(|original_input| original_input); if let PipelineData::ByteStream(stream, metadata) = input { let type_ = stream.type_(); let info = StreamInfo { span, signals: engine_state.signals().clone(), type_, metadata: metadata.clone(), }; match stream.into_source() { ByteStreamSource::Read(read) => { if use_stderr { return stderr_misuse(span, head); } let tee_thread = spawn_tee(info, eval_block)?; let tee = IoTee::new(read, tee_thread); Ok(PipelineData::byte_stream( ByteStream::read(tee, span, engine_state.signals().clone(), type_), metadata, )) } ByteStreamSource::File(file) => { if use_stderr { return stderr_misuse(span, head); } let tee_thread = spawn_tee(info, eval_block)?; let tee = IoTee::new(file, tee_thread); Ok(PipelineData::byte_stream( ByteStream::read(tee, span, engine_state.signals().clone(), type_), metadata, )) } #[cfg(feature = "os")] ByteStreamSource::Child(mut child) => { let stderr_thread = if use_stderr { let stderr_thread = if let Some(stderr) = child.stderr.take() { let tee_thread = spawn_tee(info.clone(), eval_block)?; let tee = IoTee::new(stderr, tee_thread); match stack.stderr() { OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => { child.stderr = Some(ChildPipe::Tee(Box::new(tee))); Ok(None) } OutDest::Null => copy_on_thread(tee, io::sink(), &info).map(Some), OutDest::Print | OutDest::Inherit => { copy_on_thread(tee, io::stderr(), &info).map(Some) } OutDest::File(file) => { copy_on_thread(tee, file.clone(), &info).map(Some) } }? } else { None }; if let Some(stdout) = child.stdout.take() { match stack.stdout() { OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => { child.stdout = Some(stdout); Ok(()) } OutDest::Null => copy_pipe(stdout, io::sink(), &info), OutDest::Print | OutDest::Inherit => { copy_pipe(stdout, io::stdout(), &info) } OutDest::File(file) => copy_pipe(stdout, file.as_ref(), &info), }?; } stderr_thread } else { let stderr_thread = if let Some(stderr) = child.stderr.take() { let info = info.clone(); match stack.stderr() { OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => { child.stderr = Some(stderr); Ok(None) } OutDest::Null => { copy_pipe_on_thread(stderr, io::sink(), &info).map(Some) } OutDest::Print | OutDest::Inherit => { copy_pipe_on_thread(stderr, io::stderr(), &info).map(Some) } OutDest::File(file) => { copy_pipe_on_thread(stderr, file.clone(), &info).map(Some) } }? } else { None }; if let Some(stdout) = child.stdout.take() { let tee_thread = spawn_tee(info.clone(), eval_block)?; let tee = IoTee::new(stdout, tee_thread); match stack.stdout() { OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => { child.stdout = Some(ChildPipe::Tee(Box::new(tee))); Ok(()) } OutDest::Null => copy(tee, io::sink(), &info), OutDest::Print | OutDest::Inherit => copy(tee, io::stdout(), &info), OutDest::File(file) => copy(tee, file.as_ref(), &info), }?; } stderr_thread }; if child.stdout.is_some() || child.stderr.is_some() { Ok(PipelineData::byte_stream( ByteStream::child(*child, span), metadata, )) } else { if let Some(thread) = stderr_thread { thread.join().unwrap_or_else(|_| Err(panic_error()))?; } child.wait()?; Ok(PipelineData::empty()) } } } } else { if use_stderr { return stderr_misuse(input.span().unwrap_or(head), head); } let metadata = input.metadata(); let metadata_clone = metadata.clone(); if let PipelineData::ListStream(..) = input { // Only use the iterator implementation on lists / list streams. We want to be able // to preserve errors as much as possible, and only the stream implementations can // really do that let signals = engine_state.signals().clone(); Ok(tee(input.into_iter(), move |rx| { let input = rx.into_pipeline_data_with_metadata(span, signals, metadata_clone); eval_block(input) }) .map_err(&from_io_error)? .map(move |result| result.unwrap_or_else(|err| Value::error(err, closure_span))) .into_pipeline_data_with_metadata( span, engine_state.signals().clone(), metadata, )) } else { // Otherwise, we can spawn a thread with the input value, but we have nowhere to // send an error to other than just trying to print it to stderr. let value = input.into_value(span)?; let value_clone = value.clone(); tee_once(stack.clone(), engine_state_arc, move || { eval_block(value_clone.into_pipeline_data_with_metadata(metadata_clone)) }) .map_err(&from_io_error)?; Ok(value.into_pipeline_data_with_metadata(metadata)) } } } fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) { (Some(OutDest::PipeSeparate), Some(OutDest::PipeSeparate)) } } fn panic_error() -> ShellError { ShellError::NushellFailed { msg: "A panic occurred on a thread spawned by `tee`".into(), } } /// Copies the iterator to a channel on another thread. If an error is produced on that thread, /// it is embedded in the resulting iterator as an `Err` as soon as possible. When the iterator /// finishes, it waits for the other thread to finish, also handling any error produced at that /// point. fn tee<T>( input: impl Iterator<Item = T>, with_cloned_stream: impl FnOnce(mpsc::Receiver<T>) -> Result<(), ShellError> + Send + 'static, ) -> Result<impl Iterator<Item = Result<T, ShellError>>, std::io::Error> where T: Clone + Send + 'static, { // For sending the values to the other thread let (tx, rx) = mpsc::channel(); let mut thread = Some( thread::Builder::new() .name("tee".into()) .spawn(move || with_cloned_stream(rx))?, ); let mut iter = input.into_iter(); let mut tx = Some(tx); Ok(std::iter::from_fn(move || { if thread.as_ref().is_some_and(|t| t.is_finished()) { // Check for an error from the other thread let result = thread .take() .expect("thread was taken early") .join() .unwrap_or_else(|_| Err(panic_error())); if let Err(err) = result { // Embed the error early return Some(Err(err)); } } // Get a value from the iterator if let Some(value) = iter.next() { // Send a copy, ignoring any error if the channel is closed let _ = tx.as_ref().map(|tx| tx.send(value.clone())); Some(Ok(value)) } else { // Close the channel so the stream ends for the other thread drop(tx.take()); // Wait for the other thread, and embed any error produced thread.take().and_then(|t| { t.join() .unwrap_or_else(|_| Err(panic_error())) .err() .map(Err) }) } })) } /// "tee" for a single value. No stream handling, just spawns a thread, printing any resulting error fn tee_once( stack: Stack, engine_state: Arc<EngineState>, on_thread: impl FnOnce() -> Result<(), ShellError> + Send + 'static, ) -> Result<JoinHandle<()>, std::io::Error> { thread::Builder::new().name("tee".into()).spawn(move || { if let Err(err) = on_thread() { report_shell_error(Some(&stack), &engine_state, &err); } }) } fn stderr_misuse<T>(span: Span, head: Span) -> Result<T, ShellError> { Err(ShellError::UnsupportedInput { msg: "--stderr can only be used on external commands".into(), input: "the input to `tee` is not an external command".into(), msg_span: head, input_span: span, }) } struct IoTee<R: Read> { reader: R, sender: Option<Sender<Vec<u8>>>, thread: Option<JoinHandle<Result<(), ShellError>>>, } impl<R: Read> IoTee<R> { fn new(reader: R, tee: TeeThread) -> Self { Self { reader, sender: Some(tee.sender), thread: Some(tee.thread), } } } impl<R: Read> Read for IoTee<R> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if let Some(thread) = self.thread.take() { if thread.is_finished() { if let Err(err) = thread.join().unwrap_or_else(|_| Err(panic_error())) { return Err(io::Error::other(err)); } } else { self.thread = Some(thread) } } let len = self.reader.read(buf)?; if len == 0 { self.sender = None; if let Some(thread) = self.thread.take() && let Err(err) = thread.join().unwrap_or_else(|_| Err(panic_error())) { return Err(io::Error::other(err)); } } else if let Some(sender) = self.sender.as_mut() && sender.send(buf[..len].to_vec()).is_err() { self.sender = None; } Ok(len) } } struct TeeThread { sender: Sender<Vec<u8>>, thread: JoinHandle<Result<(), ShellError>>, } fn spawn_tee( info: StreamInfo, mut eval_block: impl FnMut(PipelineData) -> Result<(), ShellError> + Send + 'static, ) -> Result<TeeThread, ShellError> { let (sender, receiver) = mpsc::channel(); let thread = thread::Builder::new() .name("tee".into()) .spawn(move || { // We use Signals::empty() here because we assume there already is a Signals on the other side let stream = ByteStream::from_iter( receiver.into_iter(), info.span, Signals::empty(), info.type_, ); eval_block(PipelineData::byte_stream(stream, info.metadata)) }) .map_err(|err| { IoError::new_with_additional_context(err, info.span, None, "Could not spawn tee") })?; Ok(TeeThread { sender, thread }) } #[derive(Clone)] struct StreamInfo { span: Span, signals: Signals, type_: ByteStreamType, metadata: Option<PipelineMetadata>, } fn copy(src: impl Read, dest: impl Write, info: &StreamInfo) -> Result<(), ShellError> { copy_with_signals(src, dest, info.span, &info.signals)?; Ok(()) } #[cfg(feature = "os")] fn copy_pipe(pipe: ChildPipe, dest: impl Write, info: &StreamInfo) -> Result<(), ShellError> { match pipe { ChildPipe::Pipe(pipe) => copy(pipe, dest, info), ChildPipe::Tee(tee) => copy(tee, dest, info), } } fn copy_on_thread( src: impl Read + Send + 'static, dest: impl Write + Send + 'static, info: &StreamInfo, ) -> Result<JoinHandle<Result<(), ShellError>>, ShellError> { let span = info.span; let signals = info.signals.clone(); thread::Builder::new() .name("stderr copier".into()) .spawn(move || { copy_with_signals(src, dest, span, &signals)?; Ok(()) }) .map_err(|err| { IoError::new_with_additional_context(err, span, None, "Could not spawn stderr copier") .into() }) } #[cfg(feature = "os")] fn copy_pipe_on_thread( pipe: ChildPipe, dest: impl Write + Send + 'static, info: &StreamInfo, ) -> Result<JoinHandle<Result<(), ShellError>>, ShellError> { match pipe { ChildPipe::Pipe(pipe) => copy_on_thread(pipe, dest, info), ChildPipe::Tee(tee) => copy_on_thread(tee, dest, info), } } #[test] fn tee_copies_values_to_other_thread_and_passes_them_through() { let (tx, rx) = mpsc::channel(); let expected_values = vec![1, 2, 3, 4]; let my_result = tee(expected_values.clone().into_iter(), move |rx| { for val in rx { let _ = tx.send(val); } Ok(()) }) .expect("io error") .collect::<Result<Vec<i32>, ShellError>>() .expect("should not produce error"); assert_eq!(expected_values, my_result); let other_threads_result = rx.into_iter().collect::<Vec<_>>(); assert_eq!(expected_values, other_threads_result); } #[test] fn tee_forwards_errors_back_immediately() { use std::time::Duration; let slow_input = (0..100).inspect(|_| std::thread::sleep(Duration::from_millis(1))); let iter = tee(slow_input, |_| { Err(ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other), Span::test_data(), None, "test", ))) }) .expect("io error"); for result in iter { if let Ok(val) = result { // should not make it to the end assert!(val < 99, "the error did not come early enough"); } else { // got the error return; } } panic!("never received the error"); } #[test] fn tee_waits_for_the_other_thread() { use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, }; use std::time::Duration; let waited = Arc::new(AtomicBool::new(false)); let waited_clone = waited.clone(); let iter = tee(0..100, move |_| { std::thread::sleep(Duration::from_millis(10)); waited_clone.store(true, Ordering::Relaxed); Err(ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other), Span::test_data(), None, "test", ))) }) .expect("io error"); let last = iter.last(); assert!(waited.load(Ordering::Relaxed), "failed to wait"); assert!( last.is_some_and(|res| res.is_err()), "failed to return error from wait" ); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/slice.rs
crates/nu-command/src/filters/slice.rs
use nu_engine::command_prelude::*; use nu_protocol::IntRange; use std::ops::Bound; #[derive(Clone)] pub struct Slice; impl Command for Slice { fn name(&self) -> &str { "slice" } fn signature(&self) -> Signature { Signature::build("slice") .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .required("rows", SyntaxShape::Range, "Range of rows to return.") .category(Category::Filters) } fn description(&self) -> &str { "Return only the selected rows." } fn search_terms(&self) -> Vec<&str> { vec!["filter", "head", "tail", "range"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[0,1,2,3,4,5] | slice 4..5", description: "Get the last 2 items", result: Some(Value::list( vec![Value::test_int(4), Value::test_int(5)], Span::test_data(), )), }, Example { example: "[0,1,2,3,4,5] | slice (-2)..", description: "Get the last 2 items", result: Some(Value::list( vec![Value::test_int(4), Value::test_int(5)], Span::test_data(), )), }, Example { example: "[0,1,2,3,4,5] | slice (-3)..-2", description: "Get the next to last 2 items", result: Some(Value::list( vec![Value::test_int(3), Value::test_int(4)], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let metadata = input.metadata(); let range: IntRange = call.req(engine_state, stack, 0)?; // only collect the input if we have any negative indices if range.is_relative() { let v: Vec<_> = input.into_iter().collect(); let (from, to) = range.absolute_bounds(v.len()); let count = match to { Bound::Excluded(to) => to.saturating_sub(from), Bound::Included(to) => to.saturating_sub(from) + 1, Bound::Unbounded => usize::MAX, }; if count == 0 { Ok(PipelineData::value(Value::list(vec![], head), None)) } else { let iter = v.into_iter().skip(from).take(count); Ok(iter.into_pipeline_data(head, engine_state.signals().clone())) } } else { let from = range.start() as usize; let count = match range.end() { Bound::Excluded(to) | Bound::Included(to) if range.start() > to => 0, Bound::Excluded(to) => (to as usize).saturating_sub(from), Bound::Included(to) => (to as usize).saturating_sub(from) + 1, Bound::Unbounded => { if range.step() < 0 { 0 } else { usize::MAX } } }; if count == 0 { Ok(PipelineData::value(Value::list(vec![], head), None)) } else { let iter = input.into_iter().skip(from).take(count); Ok(iter.into_pipeline_data(head, engine_state.signals().clone())) } } .map(|x| x.set_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Slice {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/is_not_empty.rs
crates/nu-command/src/filters/is_not_empty.rs
use crate::filters::empty::empty; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct IsNotEmpty; impl Command for IsNotEmpty { fn name(&self) -> &str { "is-not-empty" } fn signature(&self) -> Signature { Signature::build("is-not-empty") .input_output_types(vec![(Type::Any, Type::Bool)]) .rest( "rest", SyntaxShape::CellPath, "The names of the columns to check emptiness.", ) .category(Category::Filters) } fn description(&self) -> &str { "Check for non-empty values." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { // Call the same `empty` function but negate the result empty(engine_state, stack, call, input, true) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Check if a string is empty", example: "'' | is-not-empty", result: Some(Value::test_bool(false)), }, Example { description: "Check if a list is empty", example: "[] | is-not-empty", result: Some(Value::test_bool(false)), }, Example { // TODO: revisit empty cell path semantics for a record. description: "Check if more than one column are empty", example: "[[meal size]; [arepa small] [taco '']] | is-not-empty meal size", result: Some(Value::test_bool(true)), }, ] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(IsNotEmpty {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/first.rs
crates/nu-command/src/filters/first.rs
use nu_engine::command_prelude::*; use nu_protocol::{Signals, shell_error::io::IoError}; use std::io::Read; #[derive(Clone)] pub struct First; impl Command for First { fn name(&self) -> &str { "first" } fn signature(&self) -> Signature { Signature::build("first") .input_output_types(vec![ ( // TODO: This is too permissive; if we could express this // using a type parameter it would be List<T> -> T. Type::List(Box::new(Type::Any)), Type::Any, ), (Type::Binary, Type::Binary), (Type::Range, Type::Any), ]) .optional( "rows", SyntaxShape::Int, "Starting from the front, the number of rows to return.", ) .switch("strict", "Throw an error if input is empty", Some('s')) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Return only the first several rows of the input. Counterpart of `last`. Opposite of `skip`." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { first_helper(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return the first item of a list/table", example: "[1 2 3] | first", result: Some(Value::test_int(1)), }, Example { description: "Return the first 2 items of a list/table", example: "[1 2 3] | first 2", result: Some(Value::list( vec![Value::test_int(1), Value::test_int(2)], Span::test_data(), )), }, Example { description: "Return the first 2 bytes of a binary value", example: "0x[01 23 45] | first 2", result: Some(Value::binary(vec![0x01, 0x23], Span::test_data())), }, Example { description: "Return the first item of a range", example: "1..3 | first", result: Some(Value::test_int(1)), }, ] } } fn first_helper( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let rows: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?; let strict_mode = call.has_flag(engine_state, stack, "strict")?; // FIXME: for backwards compatibility reasons, if `rows` is not specified we // return a single element and otherwise we return a single list. We should probably // remove `rows` so that `first` always returns a single element; getting a list of // the first N elements is covered by `take` let return_single_element = rows.is_none(); let rows = if let Some(rows) = rows { if rows.item < 0 { return Err(ShellError::NeedsPositiveValue { span: rows.span }); } else { rows.item as usize } } else { 1 }; // first 5 bytes of an image/png are not image/png themselves let metadata = input.metadata().map(|m| m.with_content_type(None)); // early exit for `first 0` if rows == 0 { return Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(metadata)); } match input { PipelineData::Value(val, _) => { let span = val.span(); match val { Value::List { mut vals, .. } => { if return_single_element { if let Some(val) = vals.first_mut() { Ok(std::mem::take(val).into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { vals.truncate(rows); Ok(Value::list(vals, span).into_pipeline_data_with_metadata(metadata)) } } Value::Binary { mut val, .. } => { if return_single_element { if let Some(&val) = val.first() { Ok(Value::int(val.into(), span).into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { val.truncate(rows); Ok(Value::binary(val, span).into_pipeline_data_with_metadata(metadata)) } } Value::Range { val, .. } => { let mut iter = val.into_range_iter(span, Signals::empty()); if return_single_element { if let Some(v) = iter.next() { Ok(v.into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { Ok(iter.take(rows).into_pipeline_data_with_metadata( span, engine_state.signals().clone(), metadata, )) } } // Propagate errors by explicitly matching them before the final case. Value::Error { error, .. } => Err(*error), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }), } } PipelineData::ListStream(stream, metadata) => { if return_single_element { if let Some(v) = stream.into_iter().next() { Ok(v.into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { Ok(PipelineData::list_stream( stream.modify(|iter| iter.take(rows)), metadata, )) } } PipelineData::ByteStream(stream, metadata) => { if stream.type_().is_binary_coercible() { let span = stream.span(); let metadata = metadata.map(|m| m.with_content_type(None)); if let Some(mut reader) = stream.reader() { if return_single_element { // Take a single byte let mut byte = [0u8]; if reader .read(&mut byte) .map_err(|err| IoError::new(err, span, None))? > 0 { Ok(Value::int(byte[0] as i64, head).into_pipeline_data()) } else { Err(ShellError::AccessEmptyContent { span: head }) } } else { // Just take 'rows' bytes off the stream, mimicking the binary behavior Ok(PipelineData::byte_stream( ByteStream::read( reader.take(rows as u64), head, Signals::empty(), ByteStreamType::Binary, ), metadata, )) } } else { Ok(PipelineData::empty()) } } else { Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: stream.type_().describe().into(), dst_span: head, src_span: stream.span(), }) } } PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: "null".into(), dst_span: call.head, src_span: call.head, }), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(First {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/where_.rs
crates/nu-command/src/filters/where_.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::{Closure, CommandType}; #[derive(Clone)] pub struct Where; impl Command for Where { fn name(&self) -> &str { "where" } fn description(&self) -> &str { "Filter values of an input list based on a condition." } fn extra_description(&self) -> &str { r#"A condition is evaluated for each element of the input, and only elements which meet the condition are included in the output. A condition can be either a "row condition" or a closure. A row condition is a special short-hand syntax to makes accessing fields easier. Each element of the input can be accessed through the `$it` variable. On the left hand side of a row condition, any field name is automatically expanded to use `$it`. For example, `where type == dir` is equivalent to `where $it.type == dir`. This expansion does not happen when passing a subexpression or closure to `where`. When using a closure, the element is passed as an argument and as pipeline input (`$in`) to the closure. Unlike row conditions, the `$it` variable isn't available inside closures. Row conditions cannot be stored in a variable. To pass a condition with a variable, use a closure instead."# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn signature(&self) -> nu_protocol::Signature { Signature::build("where") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::table(), Type::table()), (Type::Range, Type::Any), ]) .required( "condition", SyntaxShape::RowCondition, "Filter row condition or closure.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn search_terms(&self) -> Vec<&str> { vec!["filter", "find", "search", "condition"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let mut closure = ClosureEval::new(engine_state, stack, closure); let metadata = input.metadata(); Ok(input .into_iter_strict(head)? .filter_map(move |value| { match closure .run_with_value(value.clone()) .and_then(|data| data.into_value(head)) { Ok(cond) => cond.is_true().then_some(value), Err(err) => Some(Value::error(err, head)), } }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Filter rows of a table according to a condition", example: "[{a: 1} {a: 2}] | where a > 1", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(2), })])), }, Example { description: "List only the files in the current directory", example: "ls | where type == file", result: None, }, Example { description: "List all files in the current directory with sizes greater than 2kb", example: "ls | where size > 2kb", result: None, }, Example { description: r#"List all files with names that contain "Car""#, example: r#"ls | where name =~ "Car""#, result: None, }, Example { description: "List all files that were modified in the last two weeks", example: "ls | where modified >= (date now) - 2wk", result: None, }, Example { description: "Filter items of a list with a row condition", example: "[1 2 3 4 5] | where $it > 2", result: Some(Value::test_list(vec![ Value::test_int(3), Value::test_int(4), Value::test_int(5), ])), }, Example { description: "Filter items of a list with a closure", example: "[1 2 3 4 5] | where {|x| $x > 2 }", result: Some(Value::test_list(vec![ Value::test_int(3), Value::test_int(4), Value::test_int(5), ])), }, Example { description: "Find files whose filenames don't begin with the correct sequential number", example: "ls | where type == file | sort-by name --natural | enumerate | where {|e| $e.item.name !~ $'^($e.index + 1)' } | get item", result: None, }, Example { description: r#"Find case-insensitively files called "readme", with a subexpression inside the row condition"#, example: "ls | where ($it.name | str downcase) =~ readme", result: None, }, Example { description: r#"Find case-insensitively files called "readme", with regex only"#, example: "ls | where name =~ '(?i)readme'", result: None, }, Example { description: "Filter rows of a table according to a stored condition", example: "let cond = {|x| $x.a > 1}; [{a: 1} {a: 2}] | where $cond", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(2), })])), }, Example { description: "List all numbers above 3, using an existing closure condition", example: "let a = {$in > 3}; [1, 2, 5, 6] | where $a", result: Some(Value::test_list(vec![ Value::test_int(5), Value::test_int(6), ])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Where {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/move_.rs
crates/nu-command/src/filters/move_.rs
use std::ops::Not; use nu_engine::command_prelude::*; #[derive(Clone, Debug)] enum Location { Before(Spanned<String>), After(Spanned<String>), Last, First, } #[derive(Clone)] pub struct Move; impl Command for Move { fn name(&self) -> &str { "move" } fn description(&self) -> &str { "Moves columns relative to other columns or make them the first/last columns. Flags are mutually exclusive." } fn signature(&self) -> nu_protocol::Signature { Signature::build("move") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ]) .rest("columns", SyntaxShape::String, "The columns to move.") .named( "after", SyntaxShape::String, "the column that will precede the columns moved", None, ) .named( "before", SyntaxShape::String, "the column that will be the next after the columns moved", None, ) .switch("first", "makes the columns be the first ones", None) .switch("last", "makes the columns be the last ones", None) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[[name value index]; [foo a 1] [bar b 2] [baz c 3]] | move index --before name", description: "Move a column before the first column", result: Some(Value::test_list(vec![ Value::test_record(record! { "index" => Value::test_int(1), "name" => Value::test_string("foo"), "value" => Value::test_string("a"), }), Value::test_record(record! { "index" => Value::test_int(2), "name" => Value::test_string("bar"), "value" => Value::test_string("b"), }), Value::test_record(record! { "index" => Value::test_int(3), "name" => Value::test_string("baz"), "value" => Value::test_string("c"), }), ])), }, Example { example: "[[name value index]; [foo a 1] [bar b 2] [baz c 3]] | move value name --after index", description: "Move multiple columns after the last column and reorder them", result: Some(Value::test_list(vec![ Value::test_record(record! { "index" => Value::test_int(1), "value" => Value::test_string("a"), "name" => Value::test_string("foo"), }), Value::test_record(record! { "index" => Value::test_int(2), "value" => Value::test_string("b"), "name" => Value::test_string("bar"), }), Value::test_record(record! { "index" => Value::test_int(3), "value" => Value::test_string("c"), "name" => Value::test_string("baz"), }), ])), }, Example { example: "{ name: foo, value: a, index: 1 } | move name --before index", description: "Move columns of a record", result: Some(Value::test_record(record! { "value" => Value::test_string("a"), "name" => Value::test_string("foo"), "index" => Value::test_int(1), })), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let columns: Vec<Value> = call.rest(engine_state, stack, 0)?; let after: Option<Value> = call.get_flag(engine_state, stack, "after")?; let before: Option<Value> = call.get_flag(engine_state, stack, "before")?; let first = call.has_flag(engine_state, stack, "first")?; let last = call.has_flag(engine_state, stack, "last")?; let location = match (after, before, first, last) { (Some(v), None, false, false) => Location::After(Spanned { span: v.span(), item: v.coerce_into_string()?, }), (None, Some(v), false, false) => Location::Before(Spanned { span: v.span(), item: v.coerce_into_string()?, }), (None, None, true, false) => Location::First, (None, None, false, true) => Location::Last, (None, None, false, false) => { return Err(ShellError::GenericError { error: "Cannot move columns".into(), msg: "Missing required location flag".into(), span: Some(head), help: None, inner: vec![], }); } _ => { return Err(ShellError::GenericError { error: "Cannot move columns".into(), msg: "Use only a single flag".into(), span: Some(head), help: None, inner: vec![], }); } }; let metadata = input.metadata(); match input { PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream { .. } => { let res = input.into_iter().map(move |x| match x.as_record() { Ok(record) => match move_record_columns(record, &columns, &location, head) { Ok(val) => val, Err(error) => Value::error(error, head), }, Err(error) => Value::error(error, head), }); Ok(res.into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )) } PipelineData::Value(Value::Record { val, .. }, ..) => { Ok(move_record_columns(&val, &columns, &location, head)?.into_pipeline_data()) } other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or table".to_string(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: Span::new(head.start, head.start), }), } } } // Move columns within a record fn move_record_columns( record: &Record, columns: &[Value], location: &Location, span: Span, ) -> Result<Value, ShellError> { let mut column_idx: Vec<usize> = Vec::with_capacity(columns.len()); // Find indices of columns to be moved for column in columns.iter() { if let Some(idx) = record.index_of(column.coerce_string()?) { column_idx.push(idx); } else { return Err(ShellError::GenericError { error: "Cannot move columns".into(), msg: "column does not exist".into(), span: Some(column.span()), help: None, inner: vec![], }); } } let mut out = Record::with_capacity(record.len()); match &location { Location::Before(pivot) | Location::After(pivot) => { // Check if pivot exists if !record.contains(&pivot.item) { return Err(ShellError::GenericError { error: "Cannot move columns".into(), msg: "column does not exist".into(), span: Some(pivot.span), help: None, inner: vec![], }); } for (i, (inp_col, inp_val)) in record.iter().enumerate() { if inp_col == &pivot.item { // Check if this pivot is also a column we are supposed to move if column_idx.contains(&i) { return Err(ShellError::IncompatibleParameters { left_message: "Column cannot be moved".to_string(), left_span: inp_val.span(), right_message: "relative to itself".to_string(), right_span: pivot.span, }); } if let Location::After(..) = location { out.push(inp_col.clone(), inp_val.clone()); } insert_moved(record, span, &column_idx, &mut out)?; if let Location::Before(..) = location { out.push(inp_col.clone(), inp_val.clone()); } } else if !column_idx.contains(&i) { out.push(inp_col.clone(), inp_val.clone()); } } } Location::First => { insert_moved(record, span, &column_idx, &mut out)?; out.extend(where_unmoved(record, &column_idx)); } Location::Last => { out.extend(where_unmoved(record, &column_idx)); insert_moved(record, span, &column_idx, &mut out)?; } }; Ok(Value::record(out, span)) } fn where_unmoved<'a>( record: &'a Record, column_idx: &'a [usize], ) -> impl Iterator<Item = (String, Value)> + use<'a> { record .iter() .enumerate() .filter(|(i, _)| column_idx.contains(i).not()) .map(|(_, (c, v))| (c.clone(), v.clone())) } fn insert_moved( record: &Record, span: Span, column_idx: &[usize], out: &mut Record, ) -> Result<(), ShellError> { for idx in column_idx.iter() { if let Some((col, val)) = record.get_index(*idx) { out.push(col.clone(), val.clone()); } else { return Err(ShellError::NushellFailedSpanned { msg: "Error indexing input columns".to_string(), label: "originates from here".to_string(), span, }); } } Ok(()) } #[cfg(test)] mod test { use super::*; // helper fn get_test_record(columns: Vec<&str>, values: Vec<i64>) -> Record { let test_span = Span::test_data(); Record::from_raw_cols_vals( columns.iter().map(|col| col.to_string()).collect(), values.iter().map(|val| Value::test_int(*val)).collect(), test_span, test_span, ) .unwrap() } #[test] fn test_examples() { use crate::test_examples; test_examples(Move {}) } #[test] fn move_after_with_single_column() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d"], vec![1, 2, 3, 4]); let after: Location = Location::After(Spanned { item: "c".to_string(), span: test_span, }); let columns = ["a"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4} | move a --after c let result = move_record_columns(&test_record, &columns, &after, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["b", "c", "a", "d"]); } #[test] fn move_after_with_multiple_columns() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d", "e"], vec![1, 2, 3, 4, 5]); let after: Location = Location::After(Spanned { item: "c".to_string(), span: test_span, }); let columns = ["b", "e"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4, e: 5} | move b e --after c let result = move_record_columns(&test_record, &columns, &after, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["a", "c", "b", "e", "d"]); } #[test] fn move_before_with_single_column() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d"], vec![1, 2, 3, 4]); let before: Location = Location::Before(Spanned { item: "b".to_string(), span: test_span, }); let columns = ["d"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4} | move d --before b let result = move_record_columns(&test_record, &columns, &before, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["a", "d", "b", "c"]); } #[test] fn move_before_with_multiple_columns() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d", "e"], vec![1, 2, 3, 4, 5]); let before: Location = Location::Before(Spanned { item: "b".to_string(), span: test_span, }); let columns = ["c", "e"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4, e: 5} | move c e --before b let result = move_record_columns(&test_record, &columns, &before, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["a", "c", "e", "b", "d"]); } #[test] fn move_first_with_single_column() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d"], vec![1, 2, 3, 4]); let columns = ["c"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4} | move c --first let result = move_record_columns(&test_record, &columns, &Location::First, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["c", "a", "b", "d"]); } #[test] fn move_first_with_multiple_columns() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d", "e"], vec![1, 2, 3, 4, 5]); let columns = ["c", "e"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4, e: 5} | move c e --first let result = move_record_columns(&test_record, &columns, &Location::First, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["c", "e", "a", "b", "d"]); } #[test] fn move_last_with_single_column() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d"], vec![1, 2, 3, 4]); let columns = ["b"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4} | move b --last let result = move_record_columns(&test_record, &columns, &Location::Last, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["a", "c", "d", "b"]); } #[test] fn move_last_with_multiple_columns() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d", "e"], vec![1, 2, 3, 4, 5]); let columns = ["c", "d"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4, e: 5} | move c d --last let result = move_record_columns(&test_record, &columns, &Location::Last, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["a", "b", "e", "c", "d"]); } #[test] fn move_with_multiple_columns_reorders_columns() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d", "e"], vec![1, 2, 3, 4, 5]); let after: Location = Location::After(Spanned { item: "e".to_string(), span: test_span, }); let columns = ["d", "c", "a"].map(Value::test_string); // corresponds to: {a: 1, b: 2, c: 3, d: 4, e: 5} | move d c a --after e let result = move_record_columns(&test_record, &columns, &after, test_span); assert!(result.is_ok()); let result_record = result.unwrap().into_record().unwrap(); let result_columns = result_record.into_columns().collect::<Vec<String>>(); assert_eq!(result_columns, ["b", "e", "d", "c", "a"]); } #[test] fn move_fails_when_pivot_not_present() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b"], vec![1, 2]); let before: Location = Location::Before(Spanned { item: "non-existent".to_string(), span: test_span, }); let columns = ["a"].map(Value::test_string); let result = move_record_columns(&test_record, &columns, &before, test_span); assert!(result.is_err()); } #[test] fn move_fails_when_column_not_present() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b"], vec![1, 2]); let before: Location = Location::Before(Spanned { item: "b".to_string(), span: test_span, }); let columns = ["a", "non-existent"].map(Value::test_string); let result = move_record_columns(&test_record, &columns, &before, test_span); assert!(result.is_err()); } #[test] fn move_fails_when_column_is_also_pivot() { let test_span = Span::test_data(); let test_record = get_test_record(vec!["a", "b", "c", "d"], vec![1, 2, 3, 4]); let after: Location = Location::After(Spanned { item: "b".to_string(), span: test_span, }); let columns = ["b", "d"].map(Value::test_string); let result = move_record_columns(&test_record, &columns, &after, test_span); assert!(result.is_err()); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/reverse.rs
crates/nu-command/src/filters/reverse.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Reverse; impl Command for Reverse { fn name(&self) -> &str { "reverse" } fn signature(&self) -> nu_protocol::Signature { Signature::build("reverse") .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .category(Category::Filters) } fn description(&self) -> &str { "Reverses the input list or table." } fn search_terms(&self) -> Vec<&str> { vec!["convert, inverse, flip"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[0,1,2,3] | reverse", description: "Reverse a list", result: Some(Value::test_list(vec![ Value::test_int(3), Value::test_int(2), Value::test_int(1), Value::test_int(0), ])), }, Example { example: "[{a: 1} {a: 2}] | reverse", description: "Reverse a table", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_int(1), }), ])), }, ] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let metadata = input.metadata(); let values = input.into_iter_strict(head)?.collect::<Vec<_>>(); let iter = values.into_iter().rev(); Ok(iter.into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Reverse {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/headers.rs
crates/nu-command/src/filters/headers.rs
use nu_engine::command_prelude::*; use nu_protocol::Config; #[derive(Clone)] pub struct Headers; impl Command for Headers { fn name(&self) -> &str { "headers" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::table(), Type::table())]) .category(Category::Filters) } fn description(&self) -> &str { "Use the first row of the table as column names." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Sets the column names for a table created by `split column`", example: r#""a b c|1 2 3" | split row "|" | split column " " | headers"#, result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_string("1"), "b" => Value::test_string("2"), "c" => Value::test_string("3"), })])), }, Example { description: "Columns which don't have data in their first row are removed", example: r#""a b c|1 2 3|1 2 3 4" | split row "|" | split column " " | headers"#, result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_string("1"), "b" => Value::test_string("2"), "c" => Value::test_string("3"), }), Value::test_record(record! { "a" => Value::test_string("1"), "b" => Value::test_string("2"), "c" => Value::test_string("3"), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let config = &stack.get_config(engine_state); let metadata = input.metadata(); let span = input.span().unwrap_or(call.head); let value = input.into_value(span)?; let Value::List { vals: table, .. } = value else { return Err(ShellError::TypeMismatch { err_message: "not a table".to_string(), span, }); }; let (old_headers, new_headers) = extract_headers(&table, span, config)?; let value = replace_headers(table, span, &old_headers, &new_headers)?; Ok(value.into_pipeline_data_with_metadata(metadata)) } } fn extract_headers( table: &[Value], span: Span, config: &Config, ) -> Result<(Vec<String>, Vec<String>), ShellError> { table .first() .ok_or_else(|| ShellError::GenericError { error: "Found empty list".into(), msg: "unable to extract headers".into(), span: Some(span), help: None, inner: vec![], }) .and_then(Value::as_record) .and_then(|record| { for v in record.values() { if !is_valid_header(v) { return Err(ShellError::TypeMismatch { err_message: "needs compatible type: Null, String, Bool, Float, Int" .to_string(), span: v.span(), }); } } let old_headers = record.columns().cloned().collect(); let new_headers = record .values() .enumerate() .map(|(idx, value)| { let col = value.to_expanded_string("", config); if col.is_empty() { format!("column{idx}") } else { col } }) .collect(); Ok((old_headers, new_headers)) }) } fn is_valid_header(value: &Value) -> bool { matches!( value, Value::Nothing { .. } | Value::String { val: _, .. } | Value::Bool { val: _, .. } | Value::Float { val: _, .. } | Value::Int { val: _, .. } ) } fn replace_headers( rows: Vec<Value>, span: Span, old_headers: &[String], new_headers: &[String], ) -> Result<Value, ShellError> { rows.into_iter() .skip(1) .map(|value| { let span = value.span(); if let Value::Record { val: record, .. } = value { Ok(Value::record( record .into_owned() .into_iter() .filter_map(|(col, val)| { old_headers .iter() .position(|c| c == &col) .map(|i| (new_headers[i].clone(), val)) }) .collect(), span, )) } else { Err(ShellError::CantConvert { to_type: "record".into(), from_type: value.get_type().to_string(), span, help: None, }) } }) .collect::<Result<_, _>>() .map(|rows| Value::list(rows, span)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Headers {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/select.rs
crates/nu-command/src/filters/select.rs
use nu_engine::command_prelude::*; use nu_protocol::{ DeprecationEntry, DeprecationType, PipelineIterator, ReportMode, ast::PathMember, casing::Casing, }; use std::collections::BTreeSet; #[derive(Clone)] pub struct Select; impl Command for Select { fn name(&self) -> &str { "select" } // FIXME: also add support for --skip fn signature(&self) -> Signature { Signature::build("select") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), (Type::List(Box::new(Type::Any)), Type::Any), ]) .switch( "optional", "make all cell path members optional (returns `null` for missing values)", Some('o'), ) .switch( "ignore-case", "make all cell path members case insensitive", None, ) .switch( "ignore-errors", "ignore missing data (make all cell path members optional) (deprecated)", Some('i'), ) .rest( "rest", SyntaxShape::CellPath, "The columns to select from the table.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Select only these columns or rows from the input. Opposite of `reject`." } fn extra_description(&self) -> &str { r#"This differs from `get` in that, rather than accessing the given value in the data structure, it removes all non-selected values from the structure. Hence, using `select` on a table will produce a table, a list will produce a list, and a record will produce a record."# } fn search_terms(&self) -> Vec<&str> { vec!["pick", "choose", "get"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Vec<Value> = call.rest(engine_state, stack, 0)?; let mut new_columns: Vec<CellPath> = vec![]; for col_val in columns { let col_span = col_val.span(); match col_val { Value::CellPath { val, .. } => { new_columns.push(val); } Value::String { val, .. } => { let cv = CellPath { members: vec![PathMember::String { val, span: col_span, optional: false, casing: Casing::Sensitive, }], }; new_columns.push(cv); } Value::Int { val, .. } => { if val < 0 { return Err(ShellError::CantConvert { to_type: "cell path".into(), from_type: "negative number".into(), span: col_span, help: None, }); } let cv = CellPath { members: vec![PathMember::Int { val: val as usize, span: col_span, optional: false, }], }; new_columns.push(cv); } x => { return Err(ShellError::CantConvert { to_type: "cell path".into(), from_type: x.get_type().to_string(), span: x.span(), help: None, }); } } } let optional = call.has_flag(engine_state, stack, "optional")? || call.has_flag(engine_state, stack, "ignore-errors")?; let ignore_case = call.has_flag(engine_state, stack, "ignore-case")?; let span = call.head; if optional { for cell_path in &mut new_columns { cell_path.make_optional(); } } if ignore_case { for cell_path in &mut new_columns { cell_path.make_insensitive(); } } select(engine_state, span, new_columns, input) } fn deprecation_info(&self) -> Vec<DeprecationEntry> { vec![DeprecationEntry { ty: DeprecationType::Flag("ignore-errors".into()), report_mode: ReportMode::FirstUse, since: Some("0.106.0".into()), expected_removal: None, help: Some( "This flag has been renamed to `--optional (-o)` to better reflect its behavior." .into(), ), }] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Select a column in a table", example: "[{a: a b: b}] | select a", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_string("a") })])), }, Example { description: "Select a column even if some rows are missing that column", example: "[{a: a0 b: b0} {b: b1}] | select -o a", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_string("a0") }), Value::test_record(record! { "a" => Value::test_nothing() }), ])), }, Example { description: "Select a field in a record", example: "{a: a b: b} | select a", result: Some(Value::test_record(record! { "a" => Value::test_string("a") })), }, Example { description: "Select just the `name` column", example: "ls | select name", result: None, }, Example { description: "Select the first four rows (this is the same as `first 4`)", example: "ls | select 0 1 2 3", result: None, }, Example { description: "Select multiple columns", example: "[[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb]] | select name type", result: Some(Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("Cargo.toml"), "type" => Value::test_string("toml"), }), Value::test_record(record! { "name" => Value::test_string("Cargo.lock"), "type" => Value::test_string("toml") }), ])), }, Example { description: "Select multiple columns by spreading a list", example: r#"let cols = [name type]; [[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb]] | select ...$cols"#, result: Some(Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("Cargo.toml"), "type" => Value::test_string("toml") }), Value::test_record(record! { "name" => Value::test_string("Cargo.lock"), "type" => Value::test_string("toml") }), ])), }, ] } } fn select( engine_state: &EngineState, call_span: Span, columns: Vec<CellPath>, input: PipelineData, ) -> Result<PipelineData, ShellError> { let mut unique_rows: BTreeSet<usize> = BTreeSet::new(); let mut new_columns = vec![]; for column in columns { let CellPath { ref members } = column; match members.first() { Some(PathMember::Int { val, span, .. }) => { if members.len() > 1 { return Err(ShellError::GenericError { error: "Select only allows row numbers for rows".into(), msg: "extra after row number".into(), span: Some(*span), help: None, inner: vec![], }); } unique_rows.insert(*val); } _ => { if !new_columns.contains(&column) { new_columns.push(column) } } }; } let columns = new_columns; let input = if !unique_rows.is_empty() { let metadata = input.metadata(); let pipeline_iter: PipelineIterator = input.into_iter(); NthIterator { input: pipeline_iter, rows: unique_rows.into_iter().peekable(), current: 0, } .into_pipeline_data_with_metadata( call_span, engine_state.signals().clone(), metadata, ) } else { input }; match input { PipelineData::Value(v, metadata, ..) => { let span = v.span(); match v { Value::List { vals: input_vals, .. } => Ok(input_vals .into_iter() .map(move |input_val| { if !columns.is_empty() { let mut record = Record::new(); for path in &columns { match input_val.follow_cell_path(&path.members) { Ok(fetcher) => { record.push(path.to_column_name(), fetcher.into_owned()); } Err(e) => return Value::error(e, call_span), } } Value::record(record, span) } else { input_val.clone() } }) .into_pipeline_data_with_metadata( call_span, engine_state.signals().clone(), metadata, )), _ => { if !columns.is_empty() { let mut record = Record::new(); for cell_path in columns { let result = v.follow_cell_path(&cell_path.members)?; record.push(cell_path.to_column_name(), result.into_owned()); } Ok(Value::record(record, call_span) .into_pipeline_data_with_metadata(metadata)) } else { Ok(v.into_pipeline_data_with_metadata(metadata)) } } } } PipelineData::ListStream(stream, metadata, ..) => Ok(stream .map(move |x| { if !columns.is_empty() { let mut record = Record::new(); for path in &columns { match x.follow_cell_path(&path.members) { Ok(value) => { record.push(path.to_column_name(), value.into_owned()); } Err(e) => return Value::error(e, call_span), } } Value::record(record, call_span) } else { x } }) .into_pipeline_data_with_metadata(call_span, engine_state.signals().clone(), metadata)), _ => Ok(PipelineData::empty()), } } struct NthIterator { input: PipelineIterator, rows: std::iter::Peekable<std::collections::btree_set::IntoIter<usize>>, current: usize, } impl Iterator for NthIterator { type Item = Value; fn next(&mut self) -> Option<Self::Item> { loop { if let Some(row) = self.rows.peek() { if self.current == *row { self.rows.next(); self.current += 1; return self.input.next(); } else { self.current += 1; let _ = self.input.next()?; continue; } } else { return None; } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Select) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/upsert.rs
crates/nu-command/src/filters/upsert.rs
use std::borrow::Cow; use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*}; use nu_protocol::ast::PathMember; #[derive(Clone)] pub struct Upsert; impl Command for Upsert { fn name(&self) -> &str { "upsert" } fn signature(&self) -> Signature { Signature::build("upsert") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .required( "field", SyntaxShape::CellPath, "The name of the column to update or insert.", ) .required( "replacement value", SyntaxShape::Any, "The new value to give the cell(s), or a closure to create the value.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Update an existing column to have a new value, or insert a new column." } fn extra_description(&self) -> &str { "When updating or inserting a column, the closure will be run for each row, and the current row will be passed as the first argument. \ Referencing `$in` inside the closure will provide the value at the column for the current row or null if the column does not exist. When updating a specific index, the closure will instead be run once. The first argument to the closure and the `$in` value will both be the current value at the index. \ If the command is inserting at the end of a list or table, then both of these values will be null." } fn search_terms(&self) -> Vec<&str> { vec!["add"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { upsert(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Update a record's value", example: "{'name': 'nu', 'stars': 5} | upsert name 'Nushell'", result: Some(Value::test_record(record! { "name" => Value::test_string("Nushell"), "stars" => Value::test_int(5), })), }, Example { description: "Insert a new entry into a record", example: "{'name': 'nu', 'stars': 5} | upsert language 'Rust'", result: Some(Value::test_record(record! { "name" => Value::test_string("nu"), "stars" => Value::test_int(5), "language" => Value::test_string("Rust"), })), }, Example { description: "Update each row of a table", example: "[[name lang]; [Nushell ''] [Reedline '']] | upsert lang 'Rust'", result: Some(Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("Nushell"), "lang" => Value::test_string("Rust"), }), Value::test_record(record! { "name" => Value::test_string("Reedline"), "lang" => Value::test_string("Rust"), }), ])), }, Example { description: "Insert a new column with values computed based off the other columns", example: "[[foo]; [7] [8] [9]] | upsert bar {|row| $row.foo * 2 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_int(7), "bar" => Value::test_int(14), }), Value::test_record(record! { "foo" => Value::test_int(8), "bar" => Value::test_int(16), }), Value::test_record(record! { "foo" => Value::test_int(9), "bar" => Value::test_int(18), }), ])), }, Example { description: "Update null values in a column to a default value", example: "[[foo]; [2] [null] [4]] | upsert foo { default 0 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_int(2), }), Value::test_record(record! { "foo" => Value::test_int(0), }), Value::test_record(record! { "foo" => Value::test_int(4), }), ])), }, Example { description: "Upsert into a list, updating an existing value at an index", example: "[1 2 3] | upsert 0 2", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(2), Value::test_int(3), ])), }, Example { description: "Upsert into a list, inserting a new value at the end", example: "[1 2 3] | upsert 3 4", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { description: "Upsert into a nested path, creating new values as needed", example: "[{} {a: [{}]}] | upsert a.0.b \"value\"", result: Some(Value::test_list(vec![ Value::test_record(record!( "a" => Value::test_list(vec![Value::test_record(record!( "b" => Value::test_string("value"), ))]), )), Value::test_record(record!( "a" => Value::test_list(vec![Value::test_record(record!( "b" => Value::test_string("value"), ))]), )), ])), }, ] } } fn upsert( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let cell_path: CellPath = call.req(engine_state, stack, 0)?; let replacement: Value = call.req(engine_state, stack, 1)?; match input { PipelineData::Value(mut value, metadata) => { if let Value::Closure { val, .. } = replacement { match (cell_path.members.first(), &mut value) { (Some(PathMember::String { .. }), Value::List { vals, .. }) => { let mut closure = ClosureEval::new(engine_state, stack, *val); for val in vals { upsert_value_by_closure( val, &mut closure, head, &cell_path.members, false, )?; } } (first, _) => { upsert_single_value_by_closure( &mut value, ClosureEvalOnce::new(engine_state, stack, *val), head, &cell_path.members, matches!(first, Some(PathMember::Int { .. })), )?; } } } else { value.upsert_data_at_cell_path(&cell_path.members, replacement)?; } Ok(value.into_pipeline_data_with_metadata(metadata)) } PipelineData::ListStream(stream, metadata) => { if let Some(( &PathMember::Int { val, span: path_span, .. }, path, )) = cell_path.members.split_first() { let mut stream = stream.into_iter(); let mut pre_elems = vec![]; for idx in 0..val { if let Some(v) = stream.next() { pre_elems.push(v); } else { return Err(ShellError::InsertAfterNextFreeIndex { available_idx: idx, span: path_span, }); } } let value = if path.is_empty() { let value = stream.next().unwrap_or(Value::nothing(head)); if let Value::Closure { val, .. } = replacement { ClosureEvalOnce::new(engine_state, stack, *val) .run_with_value(value)? .into_value(head)? } else { replacement } } else if let Some(mut value) = stream.next() { if let Value::Closure { val, .. } = replacement { upsert_single_value_by_closure( &mut value, ClosureEvalOnce::new(engine_state, stack, *val), head, path, true, )?; } else { value.upsert_data_at_cell_path(path, replacement)?; } value } else { return Err(ShellError::AccessBeyondEnd { max_idx: pre_elems.len() - 1, span: path_span, }); }; pre_elems.push(value); Ok(pre_elems .into_iter() .chain(stream) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )) } else if let Value::Closure { val, .. } = replacement { let mut closure = ClosureEval::new(engine_state, stack, *val); let stream = stream.map(move |mut value| { let err = upsert_value_by_closure( &mut value, &mut closure, head, &cell_path.members, false, ); if let Err(e) = err { Value::error(e, head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } else { let stream = stream.map(move |mut value| { if let Err(e) = value.upsert_data_at_cell_path(&cell_path.members, replacement.clone()) { Value::error(e, head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } } PipelineData::Empty => Err(ShellError::IncompatiblePathAccess { type_name: "empty pipeline".to_string(), span: head, }), PipelineData::ByteStream(stream, ..) => Err(ShellError::IncompatiblePathAccess { type_name: stream.type_().describe().into(), span: head, }), } } fn upsert_value_by_closure( value: &mut Value, closure: &mut ClosureEval, span: Span, cell_path: &[PathMember], first_path_member_int: bool, ) -> Result<(), ShellError> { let value_at_path = value.follow_cell_path(cell_path); let arg = if first_path_member_int { value_at_path .as_deref() .cloned() .unwrap_or(Value::nothing(span)) } else { value.clone() }; let input = value_at_path .map(Cow::into_owned) .map(IntoPipelineData::into_pipeline_data) .unwrap_or(PipelineData::empty()); let new_value = closure .add_arg(arg) .run_with_input(input)? .into_value(span)?; value.upsert_data_at_cell_path(cell_path, new_value) } fn upsert_single_value_by_closure( value: &mut Value, closure: ClosureEvalOnce, span: Span, cell_path: &[PathMember], first_path_member_int: bool, ) -> Result<(), ShellError> { let value_at_path = value.follow_cell_path(cell_path); let arg = if first_path_member_int { value_at_path .as_deref() .cloned() .unwrap_or(Value::nothing(span)) } else { value.clone() }; let input = value_at_path .map(Cow::into_owned) .map(IntoPipelineData::into_pipeline_data) .unwrap_or(PipelineData::empty()); let new_value = closure .add_arg(arg) .run_with_input(input)? .into_value(span)?; value.upsert_data_at_cell_path(cell_path, new_value) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Upsert {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/items.rs
crates/nu-command/src/filters/items.rs
use super::utils::chain_error_with_input; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct Items; impl Command for Items { fn name(&self) -> &str { "items" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::record(), Type::Any)]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])), "The closure to run.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Given a record, iterate on each pair of column name and associated value." } fn extra_description(&self) -> &str { "This is a fusion of `columns`, `values` and `each`." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(value, ..) => { let span = value.span(); match value { Value::Record { val, .. } => { let mut closure = ClosureEval::new(engine_state, stack, closure); Ok(val .into_owned() .into_iter() .map_while(move |(col, val)| { let result = closure .add_arg(Value::string(col, span)) .add_arg(val) .run_with_input(PipelineData::empty()) .and_then(|data| data.into_value(head)); match result { Ok(value) => Some(value), Err(err) => { let err = chain_error_with_input(err, false, span); Some(Value::error(err, head)) } } }) .into_pipeline_data(head, engine_state.signals().clone())) } Value::Error { error, .. } => Err(*error), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }), } } PipelineData::ListStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record".into(), wrong_type: "stream".into(), dst_span: call.head, src_span: stream.span(), }), PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record".into(), wrong_type: stream.type_().describe().into(), dst_span: call.head, src_span: stream.span(), }), } .map(|data| data.set_metadata(metadata)) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "{ new: york, san: francisco } | items {|key, value| echo $'($key) ($value)' }", description: "Iterate over each key-value pair of a record", result: Some(Value::list( vec![ Value::test_string("new york"), Value::test_string("san francisco"), ], Span::test_data(), )), }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Items {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/insert.rs
crates/nu-command/src/filters/insert.rs
use std::borrow::Cow; use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*}; use nu_protocol::ast::PathMember; #[derive(Clone)] pub struct Insert; impl Command for Insert { fn name(&self) -> &str { "insert" } fn signature(&self) -> Signature { Signature::build("insert") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .required( "field", SyntaxShape::CellPath, "The name of the column to insert.", ) .required( "new value", SyntaxShape::Any, "The new value to give the cell(s).", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Insert a new column, using an expression or closure to create each row's values." } fn extra_description(&self) -> &str { "When inserting a column, the closure will be run for each row, and the current row will be passed as the first argument. When inserting into a specific index, the closure will instead get the current value at the index or null if inserting at the end of a list/table." } fn search_terms(&self) -> Vec<&str> { vec!["add"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { insert(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Insert a new entry into a single record", example: "{'name': 'nu', 'stars': 5} | insert alias 'Nushell'", result: Some(Value::test_record(record! { "name" => Value::test_string("nu"), "stars" => Value::test_int(5), "alias" => Value::test_string("Nushell"), })), }, Example { description: "Insert a new column into a table, populating all rows", example: "[[project, lang]; ['Nushell', 'Rust']] | insert type 'shell'", result: Some(Value::test_list(vec![Value::test_record(record! { "project" => Value::test_string("Nushell"), "lang" => Value::test_string("Rust"), "type" => Value::test_string("shell"), })])), }, Example { description: "Insert a new column with values computed based off the other columns", example: "[[foo]; [7] [8] [9]] | insert bar {|row| $row.foo * 2 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_int(7), "bar" => Value::test_int(14), }), Value::test_record(record! { "foo" => Value::test_int(8), "bar" => Value::test_int(16), }), Value::test_record(record! { "foo" => Value::test_int(9), "bar" => Value::test_int(18), }), ])), }, Example { description: "Insert a new value into a list at an index", example: "[1 2 4] | insert 2 3", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { description: "Insert a new value at the end of a list", example: "[1 2 3] | insert 3 4", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { description: "Insert into a nested path, creating new values as needed", example: "[{} {a: [{}]}] | insert a.0.b \"value\"", result: Some(Value::test_list(vec![ Value::test_record(record!( "a" => Value::test_list(vec![Value::test_record(record!( "b" => Value::test_string("value"), ))]), )), Value::test_record(record!( "a" => Value::test_list(vec![Value::test_record(record!( "b" => Value::test_string("value"), ))]), )), ])), }, ] } } fn insert( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let cell_path: CellPath = call.req(engine_state, stack, 0)?; let replacement: Value = call.req(engine_state, stack, 1)?; match input { // Propagate errors in the pipeline PipelineData::Value(Value::Error { error, .. }, ..) => Err(*error), PipelineData::Value(mut value, metadata) => { if let Value::Closure { val, .. } = replacement { match (cell_path.members.first(), &mut value) { (Some(PathMember::String { .. }), Value::List { vals, .. }) => { let mut closure = ClosureEval::new(engine_state, stack, *val); for val in vals { insert_value_by_closure( val, &mut closure, head, &cell_path.members, false, )?; } } (first, _) => { insert_single_value_by_closure( &mut value, ClosureEvalOnce::new(engine_state, stack, *val), head, &cell_path.members, matches!(first, Some(PathMember::Int { .. })), )?; } } } else { value.insert_data_at_cell_path(&cell_path.members, replacement, head)?; } Ok(value.into_pipeline_data_with_metadata(metadata)) } PipelineData::ListStream(stream, metadata) => { if let Some(( &PathMember::Int { val, span: path_span, .. }, path, )) = cell_path.members.split_first() { let mut stream = stream.into_iter(); let mut pre_elems = vec![]; for idx in 0..val { if let Some(v) = stream.next() { pre_elems.push(v); } else { return Err(ShellError::InsertAfterNextFreeIndex { available_idx: idx, span: path_span, }); } } if path.is_empty() { if let Value::Closure { val, .. } = replacement { let value = stream.next(); let end_of_stream = value.is_none(); let value = value.unwrap_or(Value::nothing(head)); let new_value = ClosureEvalOnce::new(engine_state, stack, *val) .run_with_value(value.clone())? .into_value(head)?; pre_elems.push(new_value); if !end_of_stream { pre_elems.push(value); } } else { pre_elems.push(replacement); } } else if let Some(mut value) = stream.next() { if let Value::Closure { val, .. } = replacement { insert_single_value_by_closure( &mut value, ClosureEvalOnce::new(engine_state, stack, *val), head, path, true, )?; } else { value.insert_data_at_cell_path(path, replacement, head)?; } pre_elems.push(value) } else { return Err(ShellError::AccessBeyondEnd { max_idx: pre_elems.len() - 1, span: path_span, }); } Ok(pre_elems .into_iter() .chain(stream) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )) } else if let Value::Closure { val, .. } = replacement { let mut closure = ClosureEval::new(engine_state, stack, *val); let stream = stream.map(move |mut value| { let err = insert_value_by_closure( &mut value, &mut closure, head, &cell_path.members, false, ); if let Err(e) = err { Value::error(e, head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } else { let stream = stream.map(move |mut value| { if let Err(e) = value.insert_data_at_cell_path( &cell_path.members, replacement.clone(), head, ) { Value::error(e, head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } } PipelineData::Empty => Err(ShellError::IncompatiblePathAccess { type_name: "empty pipeline".to_string(), span: head, }), PipelineData::ByteStream(stream, ..) => Err(ShellError::IncompatiblePathAccess { type_name: stream.type_().describe().into(), span: head, }), } } fn insert_value_by_closure( value: &mut Value, closure: &mut ClosureEval, span: Span, cell_path: &[PathMember], first_path_member_int: bool, ) -> Result<(), ShellError> { let value_at_path = if first_path_member_int { value .follow_cell_path(cell_path) .map(Cow::into_owned) .unwrap_or(Value::nothing(span)) } else { value.clone() }; let new_value = closure.run_with_value(value_at_path)?.into_value(span)?; value.insert_data_at_cell_path(cell_path, new_value, span) } fn insert_single_value_by_closure( value: &mut Value, closure: ClosureEvalOnce, span: Span, cell_path: &[PathMember], first_path_member_int: bool, ) -> Result<(), ShellError> { let value_at_path = if first_path_member_int { value .follow_cell_path(cell_path) .map(Cow::into_owned) .unwrap_or(Value::nothing(span)) } else { value.clone() }; let new_value = closure.run_with_value(value_at_path)?.into_value(span)?; value.insert_data_at_cell_path(cell_path, new_value, span) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Insert {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/update.rs
crates/nu-command/src/filters/update.rs
use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*}; use nu_protocol::ast::PathMember; #[derive(Clone)] pub struct Update; impl Command for Update { fn name(&self) -> &str { "update" } fn signature(&self) -> Signature { Signature::build("update") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .required( "field", SyntaxShape::CellPath, "The name of the column to update.", ) .required( "replacement value", SyntaxShape::Any, "The new value to give the cell(s), or a closure to create the value.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Update an existing column to have a new value." } fn extra_description(&self) -> &str { "When updating a column, the closure will be run for each row, and the current row will be passed as the first argument. \ Referencing `$in` inside the closure will provide the value at the column for the current row. When updating a specific index, the closure will instead be run once. The first argument to the closure and the `$in` value will both be the current value at the index." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { update(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Update a column value", example: "{'name': 'nu', 'stars': 5} | update name 'Nushell'", result: Some(Value::test_record(record! { "name" => Value::test_string("Nushell"), "stars" => Value::test_int(5), })), }, Example { description: "Use a closure to alter each value in the 'authors' column to a single string", example: "[[project, authors]; ['nu', ['Andrés', 'JT', 'Yehuda']]] | update authors {|row| $row.authors | str join ',' }", result: Some(Value::test_list(vec![Value::test_record(record! { "project" => Value::test_string("nu"), "authors" => Value::test_string("Andrés,JT,Yehuda"), })])), }, Example { description: "Implicitly use the `$in` value in a closure to update 'authors'", example: "[[project, authors]; ['nu', ['Andrés', 'JT', 'Yehuda']]] | update authors { str join ',' }", result: Some(Value::test_list(vec![Value::test_record(record! { "project" => Value::test_string("nu"), "authors" => Value::test_string("Andrés,JT,Yehuda"), })])), }, Example { description: "Update a value at an index in a list", example: "[1 2 3] | update 1 4", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(4), Value::test_int(3), ])), }, Example { description: "Use a closure to compute a new value at an index", example: "[1 2 3] | update 1 {|i| $i + 2 }", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(4), Value::test_int(3), ])), }, ] } } fn update( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let cell_path: CellPath = call.req(engine_state, stack, 0)?; let replacement: Value = call.req(engine_state, stack, 1)?; match input { PipelineData::Value(mut value, metadata) => { if let Value::Closure { val, .. } = replacement { match (cell_path.members.first(), &mut value) { (Some(PathMember::String { .. }), Value::List { vals, .. }) => { let mut closure = ClosureEval::new(engine_state, stack, *val); for val in vals { update_value_by_closure( val, &mut closure, head, &cell_path.members, false, )?; } } (first, _) => { update_single_value_by_closure( &mut value, ClosureEvalOnce::new(engine_state, stack, *val), head, &cell_path.members, matches!(first, Some(PathMember::Int { .. })), )?; } } } else { value.update_data_at_cell_path(&cell_path.members, replacement)?; } Ok(value.into_pipeline_data_with_metadata(metadata)) } PipelineData::ListStream(stream, metadata) => { if let Some(( &PathMember::Int { val, span: path_span, .. }, path, )) = cell_path.members.split_first() { let mut stream = stream.into_iter(); let mut pre_elems = vec![]; for idx in 0..=val { if let Some(v) = stream.next() { pre_elems.push(v); } else if idx == 0 { return Err(ShellError::AccessEmptyContent { span: path_span }); } else { return Err(ShellError::AccessBeyondEnd { max_idx: idx - 1, span: path_span, }); } } // cannot fail since loop above does at least one iteration or returns an error let value = pre_elems.last_mut().expect("one element"); if let Value::Closure { val, .. } = replacement { update_single_value_by_closure( value, ClosureEvalOnce::new(engine_state, stack, *val), head, path, true, )?; } else { value.update_data_at_cell_path(path, replacement)?; } Ok(pre_elems .into_iter() .chain(stream) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )) } else if let Value::Closure { val, .. } = replacement { let mut closure = ClosureEval::new(engine_state, stack, *val); let stream = stream.map(move |mut value| { let err = update_value_by_closure( &mut value, &mut closure, head, &cell_path.members, false, ); if let Err(e) = err { Value::error(e, head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } else { let stream = stream.map(move |mut value| { if let Err(e) = value.update_data_at_cell_path(&cell_path.members, replacement.clone()) { Value::error(e, head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } } PipelineData::Empty => Err(ShellError::IncompatiblePathAccess { type_name: "empty pipeline".to_string(), span: head, }), PipelineData::ByteStream(stream, ..) => Err(ShellError::IncompatiblePathAccess { type_name: stream.type_().describe().into(), span: head, }), } } fn update_value_by_closure( value: &mut Value, closure: &mut ClosureEval, span: Span, cell_path: &[PathMember], first_path_member_int: bool, ) -> Result<(), ShellError> { let value_at_path = value.follow_cell_path(cell_path)?; // Don't run the closure for optional paths that don't exist let is_optional = cell_path.iter().any(|member| match member { PathMember::String { optional, .. } => *optional, PathMember::Int { optional, .. } => *optional, }); if is_optional && matches!(value_at_path.as_ref(), Value::Nothing { .. }) { return Ok(()); } let arg = if first_path_member_int { value_at_path.as_ref() } else { &*value }; let new_value = closure .add_arg(arg.clone()) .run_with_input(value_at_path.into_owned().into_pipeline_data())? .into_value(span)?; value.update_data_at_cell_path(cell_path, new_value) } fn update_single_value_by_closure( value: &mut Value, closure: ClosureEvalOnce, span: Span, cell_path: &[PathMember], first_path_member_int: bool, ) -> Result<(), ShellError> { let value_at_path = value.follow_cell_path(cell_path)?; // Don't run the closure for optional paths that don't exist let is_optional = cell_path.iter().any(|member| match member { PathMember::String { optional, .. } => *optional, PathMember::Int { optional, .. } => *optional, }); if is_optional && matches!(value_at_path.as_ref(), Value::Nothing { .. }) { return Ok(()); } let arg = if first_path_member_int { value_at_path.as_ref() } else { &*value }; let new_value = closure .add_arg(arg.clone()) .run_with_input(value_at_path.into_owned().into_pipeline_data())? .into_value(span)?; value.update_data_at_cell_path(cell_path, new_value) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Update {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/all.rs
crates/nu-command/src/filters/all.rs
use super::utils; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct All; impl Command for All { fn name(&self) -> &str { "all" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::Bool)]) .required( "predicate", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "A closure that must evaluate to a boolean.", ) .category(Category::Filters) } fn description(&self) -> &str { "Test if every element of the input fulfills a predicate expression." } fn search_terms(&self) -> Vec<&str> { vec!["every", "and"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Check if a list contains only true values", example: "[false true true false] | all {}", result: Some(Value::test_bool(false)), }, Example { description: "Check if each row's status is the string 'UP'", example: "[[status]; [UP] [UP]] | all {|el| $el.status == UP }", result: Some(Value::test_bool(true)), }, Example { description: "Check that each item is a string", example: "[foo bar 2 baz] | all {|| ($in | describe) == 'string' }", result: Some(Value::test_bool(false)), }, Example { description: "Check that all values are equal to twice their index", example: "[0 2 4 6] | enumerate | all {|i| $i.item == $i.index * 2 }", result: Some(Value::test_bool(true)), }, Example { description: "Check that all of the values are even, using a stored closure", example: "let cond = {|el| ($el mod 2) == 0 }; [2 4 6 8] | all $cond", result: Some(Value::test_bool(true)), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { utils::boolean_fold(engine_state, stack, call, input, false) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(All) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/compact.rs
crates/nu-command/src/filters/compact.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Compact; impl Command for Compact { fn name(&self) -> &str { "compact" } fn signature(&self) -> Signature { Signature::build("compact") .input_output_types(vec![ (Type::record(), Type::record()), (Type::list(Type::Any), Type::list(Type::Any)), ]) .switch( "empty", "also compact empty items like \"\", {}, and []", Some('e'), ) .rest( "columns", SyntaxShape::Any, "The columns to compact from the table.", ) .category(Category::Filters) } fn description(&self) -> &str { "Creates a table with non-empty rows." } fn extra_description(&self) -> &str { "Can be used to remove `null` or empty values from lists and records too." } fn search_terms(&self) -> Vec<&str> { vec!["empty", "remove"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, mut input: PipelineData, ) -> Result<PipelineData, ShellError> { let empty = call.has_flag(engine_state, stack, "empty")?; let columns: Vec<String> = call.rest(engine_state, stack, 0)?; match input { PipelineData::Value(Value::Record { ref mut val, .. }, ..) => { val.to_mut().retain(|_, val| do_keep_value(val, empty)); Ok(input) } _ => input.filter( move |item| do_keep_row(item, empty, columns.as_slice()), engine_state.signals(), ), } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Filter out all records where 'Hello' is null", example: r#"[["Hello" "World"]; [null 3]] | compact Hello"#, result: Some(Value::test_list(vec![])), }, Example { description: "Filter out all records where 'World' is null", example: r#"[["Hello" "World"]; [null 3]] | compact World"#, result: Some(Value::test_list(vec![Value::test_record(record! { "Hello" => Value::nothing(Span::test_data()), "World" => Value::test_int(3), })])), }, Example { description: "Filter out all instances of null from a list", example: r#"[1, null, 2] | compact"#, result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), ])), }, Example { description: "Filter out all instances of null and empty items from a list", example: r#"[1, null, 2, "", 3, [], 4, {}, 5] | compact --empty"#, result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), Value::test_int(5), ])), }, Example { description: "Filter out all instances of null from a record", example: r#"{a: 1, b: null, c: 3} | compact"#, result: Some(Value::test_record(record! { "a" => Value::test_int(1), "c" => Value::test_int(3), })), }, ] } } fn do_keep_value(value: &Value, compact_empties: bool) -> bool { let remove = match compact_empties { true => value.is_empty(), false => value.is_nothing(), }; !remove } fn do_keep_row(row: &Value, compact_empties: bool, columns: &[impl AsRef<str>]) -> bool { let do_keep = move |value| do_keep_value(value, compact_empties); do_keep(row) && row.as_record().map_or(true, |record| { columns .iter() .all(|col| record.get(col).map(do_keep).unwrap_or(false)) }) } #[cfg(test)] mod tests { use super::Compact; #[test] fn examples_work_as_expected() { use crate::test_examples; test_examples(Compact {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/prepend.rs
crates/nu-command/src/filters/prepend.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Prepend; impl Command for Prepend { fn name(&self) -> &str { "prepend" } fn signature(&self) -> nu_protocol::Signature { Signature::build("prepend") .input_output_types(vec![(Type::Any, Type::List(Box::new(Type::Any)))]) .required( "row", SyntaxShape::Any, "The row, list, or table to prepend.", ) .category(Category::Filters) } fn description(&self) -> &str { "Prepend any number of rows to a table." } fn extra_description(&self) -> &str { r#"Be aware that this command 'unwraps' lists passed to it. So, if you pass a variable to it, and you want the variable's contents to be prepended without being unwrapped, it's wise to pre-emptively wrap the variable in a list, like so: `prepend [$val]`. This way, `prepend` will only unwrap the outer list, and leave the variable's contents untouched."# } fn search_terms(&self) -> Vec<&str> { vec!["add", "concatenate"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "0 | prepend [1 2 3]", description: "prepend a list to an item", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(0), ])), }, Example { example: r#""a" | prepend ["b"] "#, description: "Prepend a list of strings to a string", result: Some(Value::test_list(vec![ Value::test_string("b"), Value::test_string("a"), ])), }, Example { example: "[1 2 3 4] | prepend 0", description: "Prepend one int item", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { example: "[2 3 4] | prepend [0 1]", description: "Prepend two int items", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { example: "[2 nu 4 shell] | prepend [0 1 rocks]", description: "Prepend ints and strings", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_string("rocks"), Value::test_int(2), Value::test_string("nu"), Value::test_int(4), Value::test_string("shell"), ])), }, Example { example: "[3 4] | prepend 0..2", description: "Prepend a range", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let other: Value = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); Ok(other .into_pipeline_data() .into_iter() .chain(input) .into_pipeline_data_with_metadata(call.head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Prepend {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/filter.rs
crates/nu-command/src/filters/filter.rs
use nu_engine::command_prelude::*; use nu_protocol::{DeprecationEntry, DeprecationType, ReportMode}; #[derive(Clone)] pub struct Filter; impl Command for Filter { fn name(&self) -> &str { "filter" } fn description(&self) -> &str { "Filter values based on a predicate closure." } fn extra_description(&self) -> &str { r#"This command works similar to 'where' but can only use a closure as a predicate. The "row condition" syntax is not supported."# } fn signature(&self) -> nu_protocol::Signature { Signature::build("filter") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::Range, Type::List(Box::new(Type::Any))), ]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "Predicate closure.", ) .category(Category::Filters) } fn search_terms(&self) -> Vec<&str> { vec!["where", "find", "search", "condition"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { use super::where_::Where; <Where as Command>::run(&Where, engine_state, stack, call, input) } fn deprecation_info(&self) -> Vec<nu_protocol::DeprecationEntry> { vec![ DeprecationEntry { ty: DeprecationType::Command, report_mode: ReportMode::FirstUse, since: Some("0.105.0".into()), expected_removal: None, help: Some("`where` command can be used instead, as it can now read the predicate closure from a variable".into()), } ] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Filter items of a list according to a condition", example: "[1 2] | filter {|x| $x > 1}", result: Some(Value::test_list(vec![Value::test_int(2)])), }, Example { description: "Filter rows of a table according to a condition", example: "[{a: 1} {a: 2}] | filter {|x| $x.a > 1}", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(2), })])), }, Example { description: "Filter rows of a table according to a stored condition", example: "let cond = {|x| $x.a > 1}; [{a: 1} {a: 2}] | filter $cond", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(2), })])), }, Example { description: "Filter items of a range according to a condition", example: "9..13 | filter {|el| $el mod 2 != 0}", result: Some(Value::test_list(vec![ Value::test_int(9), Value::test_int(11), Value::test_int(13), ])), }, Example { description: "List all numbers above 3, using an existing closure condition", example: "let a = {$in > 3}; [1, 2, 5, 6] | filter $a", result: None, // TODO: This should work // result: Some(Value::test_list( // vec![ // Value::Int { // val: 5, // Span::test_data(), // }, // Value::Int { // val: 6, // span: Span::test_data(), // }, // ], // }), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Filter {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/columns.rs
crates/nu-command/src/filters/columns.rs
use nu_engine::{column::get_columns, command_prelude::*}; #[derive(Clone)] pub struct Columns; impl Command for Columns { fn name(&self) -> &str { "columns" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::table(), Type::List(Box::new(Type::String))), (Type::record(), Type::List(Box::new(Type::String))), ]) .category(Category::Filters) } fn description(&self) -> &str { "Given a record or table, produce a list of its columns' names." } fn extra_description(&self) -> &str { "This is a counterpart to `values`, which produces a list of columns' values." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "{ acronym:PWD, meaning:'Print Working Directory' } | columns", description: "Get the columns from the record", result: Some(Value::list( vec![Value::test_string("acronym"), Value::test_string("meaning")], Span::test_data(), )), }, Example { example: "[[name,age,grade]; [bill,20,a]] | columns", description: "Get the columns from the table", result: Some(Value::list( vec![ Value::test_string("name"), Value::test_string("age"), Value::test_string("grade"), ], Span::test_data(), )), }, Example { example: "[[name,age,grade]; [bill,20,a]] | columns | first", description: "Get the first column from the table", result: None, }, Example { example: "[[name,age,grade]; [bill,20,a]] | columns | select 1", description: "Get the second column from the table", result: None, }, ] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { getcol(call.head, input) } } fn getcol(head: Span, input: PipelineData) -> Result<PipelineData, ShellError> { let metadata = input.metadata(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(v, ..) => { let span = v.span(); let cols = match v { Value::List { vals: input_vals, .. } => get_columns(&input_vals) .into_iter() .map(move |x| Value::string(x, span)) .collect(), Value::Custom { val, .. } => { // TODO: should we get CustomValue to expose columns in a more efficient way? // Would be nice to be able to get columns without generating the whole value let input_as_base_value = val.to_base_value(span)?; get_columns(&[input_as_base_value]) .into_iter() .map(move |x| Value::string(x, span)) .collect() } Value::Record { val, .. } => val .into_owned() .into_iter() .map(move |(x, _)| Value::string(x, head)) .collect(), // Propagate errors Value::Error { error, .. } => return Err(*error), other => { return Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or table".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }); } }; Ok(Value::list(cols, head) .into_pipeline_data() .set_metadata(metadata)) } PipelineData::ListStream(stream, ..) => { let values = stream.into_iter().collect::<Vec<_>>(); let cols = get_columns(&values) .into_iter() .map(|s| Value::string(s, head)) .collect(); Ok(Value::list(cols, head) .into_pipeline_data() .set_metadata(metadata)) } PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or table".into(), wrong_type: "byte stream".into(), dst_span: head, src_span: stream.span(), }), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Columns {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/sort.rs
crates/nu-command/src/filters/sort.rs
use nu_engine::command_prelude::*; use nu_protocol::{ast::PathMember, casing::Casing}; use crate::Comparator; #[derive(Clone)] pub struct Sort; impl Command for Sort { fn name(&self) -> &str { "sort" } fn signature(&self) -> nu_protocol::Signature { Signature::build("sort") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)) ), (Type::record(), Type::record()) ]) .switch("reverse", "Sort in reverse order", Some('r')) .switch( "ignore-case", "Sort string-based data case-insensitively", Some('i'), ) .switch( "values", "If input is a single record, sort the record by values; ignored if input is not a single record", Some('v'), ) .switch( "natural", "Sort alphanumeric string-based values naturally (1, 9, 10, 99, 100, ...)", Some('n'), ) .category(Category::Filters) } fn description(&self) -> &str { "Sort in increasing order." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[2 0 1] | sort", description: "Sort the list by increasing value", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), ])), }, Example { example: "[2 0 1] | sort --reverse", description: "Sort the list by decreasing value", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(1), Value::test_int(0), ])), }, Example { example: "[betty amy sarah] | sort", description: "Sort a list of strings", result: Some(Value::test_list(vec![ Value::test_string("amy"), Value::test_string("betty"), Value::test_string("sarah"), ])), }, Example { example: "[betty amy sarah] | sort --reverse", description: "Sort a list of strings in reverse", result: Some(Value::test_list(vec![ Value::test_string("sarah"), Value::test_string("betty"), Value::test_string("amy"), ])), }, Example { description: "Sort strings (case-insensitive)", example: "[airplane Truck Car] | sort -i", result: Some(Value::test_list(vec![ Value::test_string("airplane"), Value::test_string("Car"), Value::test_string("Truck"), ])), }, Example { description: "Sort strings (reversed case-insensitive)", example: "[airplane Truck Car] | sort -i -r", result: Some(Value::test_list(vec![ Value::test_string("Truck"), Value::test_string("Car"), Value::test_string("airplane"), ])), }, Example { description: "Sort alphanumeric strings in natural order", example: "[foo1 foo10 foo9] | sort -n", result: Some(Value::test_list(vec![ Value::test_string("foo1"), Value::test_string("foo9"), Value::test_string("foo10"), ])), }, Example { description: "Sort record by key (case-insensitive)", example: "{b: 3, a: 4} | sort", result: Some(Value::test_record(record! { "a" => Value::test_int(4), "b" => Value::test_int(3), })), }, Example { description: "Sort record by value", example: "{b: 4, a: 3, c:1} | sort -v", result: Some(Value::test_record(record! { "c" => Value::test_int(1), "a" => Value::test_int(3), "b" => Value::test_int(4), })), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let reverse = call.has_flag(engine_state, stack, "reverse")?; let insensitive = call.has_flag(engine_state, stack, "ignore-case")?; let natural = call.has_flag(engine_state, stack, "natural")?; let sort_by_value = call.has_flag(engine_state, stack, "values")?; let metadata = input.metadata(); let span = input.span().unwrap_or(call.head); let value = input.into_value(span)?; let sorted: Value = match value { Value::Record { val, .. } => { // Records have two sorting methods, toggled by presence or absence of -v let record = crate::sort_record( val.into_owned(), sort_by_value, reverse, insensitive, natural, )?; Value::record(record, span) } value @ Value::List { .. } => { // If we have a table specifically, then we want to sort along each column. // Record's PartialOrd impl dictates that columns are compared in alphabetical order, // so we have to explicitly compare by each column. let r#type = value.get_type(); let mut vec = value.into_list().expect("matched list above"); if let Type::Table(cols) = r#type { let columns: Vec<Comparator> = cols .iter() .map(|col| { vec![PathMember::string( col.0.clone(), false, Casing::Sensitive, Span::unknown(), )] }) .map(|members| CellPath { members }) .map(Comparator::CellPath) .collect(); crate::sort_by(&mut vec, columns, span, insensitive, natural)?; } else { crate::sort(&mut vec, insensitive, natural)?; } if reverse { vec.reverse() } Value::list(vec, span) } Value::Nothing { .. } => { return Err(ShellError::PipelineEmpty { dst_span: value.span(), }); } ref other => { return Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or list".to_string(), wrong_type: other.get_type().to_string(), dst_span: call.head, src_span: value.span(), }); } }; Ok(sorted.into_pipeline_data_with_metadata(metadata)) } } #[cfg(test)] mod test { use nu_protocol::engine::CommandType; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Sort {}) } #[test] fn test_command_type() { assert!(matches!(Sort.command_type(), CommandType::Builtin)); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/rename.rs
crates/nu-command/src/filters/rename.rs
use indexmap::IndexMap; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct Rename; impl Command for Rename { fn name(&self) -> &str { "rename" } fn signature(&self) -> Signature { Signature::build("rename") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ]) .named( "column", SyntaxShape::Record(vec![]), "column name to be changed", Some('c'), ) .named( "block", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "A closure to apply changes on each column", Some('b'), ) .rest( "rest", SyntaxShape::String, "The new names for the columns.", ) .category(Category::Filters) } fn description(&self) -> &str { "Creates a new table with columns renamed." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { rename(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rename a column", example: "[[a, b]; [1, 2]] | rename my_column", result: Some(Value::test_list(vec![Value::test_record(record! { "my_column" => Value::test_int(1), "b" => Value::test_int(2), })])), }, Example { description: "Rename many columns", example: "[[a, b, c]; [1, 2, 3]] | rename eggs ham bacon", result: Some(Value::test_list(vec![Value::test_record(record! { "eggs" => Value::test_int(1), "ham" => Value::test_int(2), "bacon" => Value::test_int(3), })])), }, Example { description: "Rename a specific column", example: "[[a, b, c]; [1, 2, 3]] | rename --column { a: ham }", result: Some(Value::test_list(vec![Value::test_record(record! { "ham" => Value::test_int(1), "b" => Value::test_int(2), "c" => Value::test_int(3), })])), }, Example { description: "Rename the fields of a record", example: "{a: 1 b: 2} | rename x y", result: Some(Value::test_record(record! { "x" => Value::test_int(1), "y" => Value::test_int(2), })), }, Example { description: "Rename fields based on a given closure", example: "{abc: 1, bbc: 2} | rename --block {str replace --all 'b' 'z'}", result: Some(Value::test_record(record! { "azc" => Value::test_int(1), "zzc" => Value::test_int(2), })), }, ] } } fn rename( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let columns: Vec<String> = call.rest(engine_state, stack, 0)?; let specified_column: Option<Record> = call.get_flag(engine_state, stack, "column")?; // convert from Record to HashMap for easily query. let specified_column: Option<IndexMap<String, String>> = match specified_column { Some(query) => { let mut columns = IndexMap::new(); for (col, val) in query { let val_span = val.span(); match val { Value::String { val, .. } => { columns.insert(col, val); } _ => { return Err(ShellError::TypeMismatch { err_message: "new column name must be a string".to_owned(), span: val_span, }); } } } if columns.is_empty() { return Err(ShellError::TypeMismatch { err_message: "The column info cannot be empty".to_owned(), span: call.head, }); } Some(columns) } None => None, }; let closure: Option<Closure> = call.get_flag(engine_state, stack, "block")?; let mut closure = closure.map(|closure| ClosureEval::new(engine_state, stack, closure)); let metadata = input.metadata(); input .map( move |item| { let span = item.span(); match item { Value::Record { val: record, .. } => { let record = if let Some(closure) = &mut closure { record .into_owned() .into_iter() .map(|(col, val)| { let col = Value::string(col, span); let data = closure.run_with_value(col)?; let col = data.collect_string_strict(span)?.0; Ok((col, val)) }) .collect::<Result<Record, _>>() } else { match &specified_column { Some(columns) => { // record columns are unique so we can track the number // of renamed columns to check if any were missed let mut renamed = 0; let record = record .into_owned() .into_iter() .map(|(col, val)| { let col = if let Some(col) = columns.get(&col) { renamed += 1; col.clone() } else { col }; (col, val) }) .collect::<Record>(); let missing_column = if renamed < columns.len() { columns.iter().find_map(|(col, new_col)| { (!record.contains(new_col)).then_some(col) }) } else { None }; if let Some(missing) = missing_column { Err(ShellError::UnsupportedInput { msg: format!( "The column '{missing}' does not exist in the input" ), input: "value originated from here".into(), msg_span: head, input_span: span, }) } else { Ok(record) } } None => Ok(record .into_owned() .into_iter() .enumerate() .map(|(i, (col, val))| { (columns.get(i).cloned().unwrap_or(col), val) }) .collect()), } }; match record { Ok(record) => Value::record(record, span), Err(err) => Value::error(err, span), } } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => item, other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "record".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }, head, ), } }, engine_state.signals(), ) .map(|data| data.set_metadata(metadata)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Rename {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/empty.rs
crates/nu-command/src/filters/empty.rs
use nu_engine::command_prelude::*; use nu_protocol::shell_error::io::IoError; use std::io::Read; pub fn empty( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, negate: bool, ) -> Result<PipelineData, ShellError> { let head = call.head; let columns: Vec<CellPath> = call.rest(engine_state, stack, 0)?; if !columns.is_empty() { for val in input { for column in &columns { if !val.follow_cell_path(&column.members)?.is_nothing() { return Ok(Value::bool(negate, head).into_pipeline_data()); } } } if negate { Ok(Value::bool(false, head).into_pipeline_data()) } else { Ok(Value::bool(true, head).into_pipeline_data()) } } else { match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::ByteStream(stream, ..) => { let span = stream.span(); match stream.reader() { Some(reader) => { let is_empty = reader .bytes() .next() .transpose() .map_err(|err| IoError::new(err, span, None))? .is_none(); if negate { Ok(Value::bool(!is_empty, head).into_pipeline_data()) } else { Ok(Value::bool(is_empty, head).into_pipeline_data()) } } None => { if negate { Ok(Value::bool(false, head).into_pipeline_data()) } else { Ok(Value::bool(true, head).into_pipeline_data()) } } } } PipelineData::ListStream(s, ..) => { let empty = s.into_iter().next().is_none(); if negate { Ok(Value::bool(!empty, head).into_pipeline_data()) } else { Ok(Value::bool(empty, head).into_pipeline_data()) } } PipelineData::Value(value, ..) => { if negate { Ok(Value::bool(!value.is_empty(), head).into_pipeline_data()) } else { Ok(Value::bool(value.is_empty(), head).into_pipeline_data()) } } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/chunks.rs
crates/nu-command/src/filters/chunks.rs
use nu_engine::command_prelude::*; use nu_protocol::{ListStream, shell_error::io::IoError}; use std::{ io::{BufRead, Cursor, ErrorKind}, num::NonZeroUsize, }; #[derive(Clone)] pub struct Chunks; impl Command for Chunks { fn name(&self) -> &str { "chunks" } fn signature(&self) -> Signature { Signature::build("chunks") .input_output_types(vec![ (Type::table(), Type::list(Type::table())), (Type::list(Type::Any), Type::list(Type::list(Type::Any))), (Type::Binary, Type::list(Type::Binary)), ]) .required("chunk_size", SyntaxShape::Int, "The size of each chunk.") .category(Category::Filters) } fn description(&self) -> &str { "Divide a list, table or binary input into chunks of `chunk_size`." } fn extra_description(&self) -> &str { "This command will error if `chunk_size` is negative or zero." } fn search_terms(&self) -> Vec<&str> { vec!["batch", "group", "split", "bytes"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[1 2 3 4] | chunks 2", description: "Chunk a list into pairs", result: Some(Value::test_list(vec![ Value::test_list(vec![Value::test_int(1), Value::test_int(2)]), Value::test_list(vec![Value::test_int(3), Value::test_int(4)]), ])), }, Example { example: "[[foo bar]; [0 1] [2 3] [4 5] [6 7] [8 9]] | chunks 3", description: "Chunk the rows of a table into triplets", result: Some(Value::test_list(vec![ Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_int(0), "bar" => Value::test_int(1), }), Value::test_record(record! { "foo" => Value::test_int(2), "bar" => Value::test_int(3), }), Value::test_record(record! { "foo" => Value::test_int(4), "bar" => Value::test_int(5), }), ]), Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_int(6), "bar" => Value::test_int(7), }), Value::test_record(record! { "foo" => Value::test_int(8), "bar" => Value::test_int(9), }), ]), ])), }, Example { example: "0x[11 22 33 44 55 66 77 88] | chunks 3", description: "Chunk the bytes of a binary into triplets", result: Some(Value::test_list(vec![ Value::test_binary(vec![0x11, 0x22, 0x33]), Value::test_binary(vec![0x44, 0x55, 0x66]), Value::test_binary(vec![0x77, 0x88]), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let chunk_size: Value = call.req(engine_state, stack, 0)?; let size = usize::try_from(chunk_size.as_int()?).map_err(|_| ShellError::NeedsPositiveValue { span: chunk_size.span(), })?; let size = NonZeroUsize::try_from(size).map_err(|_| ShellError::IncorrectValue { msg: "`chunk_size` cannot be zero".into(), val_span: chunk_size.span(), call_span: head, })?; chunks(engine_state, input, size, head) } } pub fn chunks( engine_state: &EngineState, input: PipelineData, chunk_size: NonZeroUsize, span: Span, ) -> Result<PipelineData, ShellError> { let from_io_error = IoError::factory(span, None); match input { PipelineData::Value(Value::List { vals, .. }, metadata) => { let chunks = ChunksIter::new(vals, chunk_size, span); let stream = ListStream::new(chunks, span, engine_state.signals().clone()); Ok(PipelineData::list_stream(stream, metadata)) } PipelineData::ListStream(stream, metadata) => { let stream = stream.modify(|iter| ChunksIter::new(iter, chunk_size, span)); Ok(PipelineData::list_stream(stream, metadata)) } PipelineData::Value(Value::Binary { val, .. }, metadata) => { let chunk_read = ChunkRead { reader: Cursor::new(val), size: chunk_size, }; let value_stream = chunk_read.map(move |chunk| match chunk { Ok(chunk) => Value::binary(chunk, span), Err(e) => Value::error(from_io_error(e).into(), span), }); let pipeline_data_with_metadata = value_stream.into_pipeline_data_with_metadata( span, engine_state.signals().clone(), metadata, ); Ok(pipeline_data_with_metadata) } PipelineData::ByteStream(stream, metadata) => { let pipeline_data = match stream.reader() { None => PipelineData::empty(), Some(reader) => { let chunk_read = ChunkRead { reader, size: chunk_size, }; let value_stream = chunk_read.map(move |chunk| match chunk { Ok(chunk) => Value::binary(chunk, span), Err(e) => Value::error(from_io_error(e).into(), span), }); value_stream.into_pipeline_data_with_metadata( span, engine_state.signals().clone(), metadata, ) } }; Ok(pipeline_data) } input => Err(input.unsupported_input_error("list", span)), } } struct ChunksIter<I: Iterator<Item = Value>> { iter: I, size: usize, span: Span, } impl<I: Iterator<Item = Value>> ChunksIter<I> { fn new(iter: impl IntoIterator<IntoIter = I>, size: NonZeroUsize, span: Span) -> Self { Self { iter: iter.into_iter(), size: size.into(), span, } } } impl<I: Iterator<Item = Value>> Iterator for ChunksIter<I> { type Item = Value; fn next(&mut self) -> Option<Self::Item> { let first = self.iter.next()?; let mut chunk = Vec::with_capacity(self.size); // delay allocation to optimize for empty iter chunk.push(first); chunk.extend((&mut self.iter).take(self.size - 1)); Some(Value::list(chunk, self.span)) } } struct ChunkRead<R: BufRead> { reader: R, size: NonZeroUsize, } impl<R: BufRead> Iterator for ChunkRead<R> { type Item = Result<Vec<u8>, std::io::Error>; fn next(&mut self) -> Option<Self::Item> { let mut buf = Vec::with_capacity(self.size.get()); while buf.len() < self.size.get() { let available = match self.reader.fill_buf() { Ok([]) if buf.is_empty() => return None, Ok([]) => return Some(Ok(buf)), Ok(n) => n, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Some(Err(e)), }; let needed = self.size.get() - buf.len(); let have = available.len().min(needed); buf.extend_from_slice(&available[..have]); self.reader.consume(have); } Some(Ok(buf)) } } #[cfg(test)] mod test { use std::io::Read; use super::*; #[test] fn chunk_read() { let s = "hello world"; let data = Cursor::new(s); let chunk_read = ChunkRead { reader: data, size: NonZeroUsize::new(4).unwrap(), }; let chunks = chunk_read.map(|e| e.unwrap()).collect::<Vec<_>>(); assert_eq!( chunks, [&s.as_bytes()[..4], &s.as_bytes()[4..8], &s.as_bytes()[8..]] ); } #[test] fn chunk_read_stream() { let s = "hello world"; let data = Cursor::new(&s[..3]) .chain(Cursor::new(&s[3..9])) .chain(Cursor::new(&s[9..])); let chunk_read = ChunkRead { reader: data, size: NonZeroUsize::new(4).unwrap(), }; let chunks = chunk_read.map(|e| e.unwrap()).collect::<Vec<_>>(); assert_eq!( chunks, [&s.as_bytes()[..4], &s.as_bytes()[4..8], &s.as_bytes()[8..]] ); } #[test] fn test_examples() { use crate::test_examples; test_examples(Chunks {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/values.rs
crates/nu-command/src/filters/values.rs
use indexmap::IndexMap; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Values; impl Command for Values { fn name(&self) -> &str { "values" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::record(), Type::List(Box::new(Type::Any))), (Type::table(), Type::List(Box::new(Type::Any))), ]) .category(Category::Filters) } fn description(&self) -> &str { "Given a record or table, produce a list of its columns' values." } fn extra_description(&self) -> &str { "This is a counterpart to `columns`, which produces a list of columns' names." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "{ mode:normal userid:31415 } | values", description: "Get the values from the record (produce a list)", result: Some(Value::list( vec![Value::test_string("normal"), Value::test_int(31415)], Span::test_data(), )), }, Example { example: "{ f:250 g:191 c:128 d:1024 e:2000 a:16 b:32 } | values", description: "Values are ordered by the column order of the record", result: Some(Value::list( vec![ Value::test_int(250), Value::test_int(191), Value::test_int(128), Value::test_int(1024), Value::test_int(2000), Value::test_int(16), Value::test_int(32), ], Span::test_data(), )), }, Example { example: "[[name meaning]; [ls list] [mv move] [cd 'change directory']] | values", description: "Get the values from the table (produce a list of lists)", result: Some(Value::list( vec![ Value::list( vec![ Value::test_string("ls"), Value::test_string("mv"), Value::test_string("cd"), ], Span::test_data(), ), Value::list( vec![ Value::test_string("list"), Value::test_string("move"), Value::test_string("change directory"), ], Span::test_data(), ), ], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; values(engine_state, span, input) } } // The semantics of `values` are as follows: // For each column, get the values for that column, in row order. // Holes are not preserved, i.e. position in the resulting list // does not necessarily equal row number. pub fn get_values<'a>( input: impl IntoIterator<Item = &'a Value>, head: Span, input_span: Span, ) -> Result<Vec<Value>, ShellError> { let mut output: IndexMap<String, Vec<Value>> = IndexMap::new(); for item in input { match item { Value::Record { val, .. } => { for (k, v) in &**val { if let Some(vec) = output.get_mut(k) { vec.push(v.clone()); } else { output.insert(k.clone(), vec![v.clone()]); } } } Value::Error { error, .. } => return Err(*error.clone()), _ => { return Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or table".into(), wrong_type: item.get_type().to_string(), dst_span: head, src_span: input_span, }); } } } Ok(output.into_values().map(|v| Value::list(v, head)).collect()) } fn values( engine_state: &EngineState, head: Span, input: PipelineData, ) -> Result<PipelineData, ShellError> { let signals = engine_state.signals().clone(); let metadata = input.metadata(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(v, ..) => { let span = v.span(); match v { Value::List { vals, .. } => match get_values(&vals, head, span) { Ok(cols) => Ok(cols .into_iter() .into_pipeline_data_with_metadata(head, signals, metadata)), Err(err) => Err(err), }, Value::Custom { val, .. } => { let input_as_base_value = val.to_base_value(span)?; match get_values(&[input_as_base_value], head, span) { Ok(cols) => Ok(cols .into_iter() .into_pipeline_data_with_metadata(head, signals, metadata)), Err(err) => Err(err), } } Value::Record { val, .. } => Ok(val .values() .cloned() .collect::<Vec<_>>() .into_pipeline_data_with_metadata(head, signals, metadata)), // Propagate errors Value::Error { error, .. } => Err(*error), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or table".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }), } } PipelineData::ListStream(stream, ..) => { let vals: Vec<_> = stream.into_iter().collect(); match get_values(&vals, head, head) { Ok(cols) => Ok(cols .into_iter() .into_pipeline_data_with_metadata(head, signals, metadata)), Err(err) => Err(err), } } PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "record or table".into(), wrong_type: stream.type_().describe().into(), dst_span: head, src_span: stream.span(), }), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Values {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/flatten.rs
crates/nu-command/src/filters/flatten.rs
use indexmap::IndexMap; use nu_engine::command_prelude::*; use nu_protocol::ast::PathMember; #[derive(Clone)] pub struct Flatten; impl Command for Flatten { fn name(&self) -> &str { "flatten" } fn signature(&self) -> Signature { Signature::build("flatten") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::record(), Type::table()), ]) .rest( "rest", SyntaxShape::String, "Optionally flatten data by column.", ) .switch("all", "flatten inner table one level out", Some('a')) .category(Category::Filters) } fn description(&self) -> &str { "Flatten the table." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { flatten(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "flatten a table", example: "[[N, u, s, h, e, l, l]] | flatten ", result: Some(Value::test_list(vec![ Value::test_string("N"), Value::test_string("u"), Value::test_string("s"), Value::test_string("h"), Value::test_string("e"), Value::test_string("l"), Value::test_string("l"), ])), }, Example { description: "flatten a table, get the first item", example: "[[N, u, s, h, e, l, l]] | flatten | first", result: None, //Some(Value::test_string("N")), }, Example { description: "flatten a column having a nested table", example: "[[origin, people]; [Ecuador, ([[name, meal]; ['Andres', 'arepa']])]] | flatten --all | get meal", result: None, //Some(Value::test_string("arepa")), }, Example { description: "restrict the flattening by passing column names", example: "[[origin, crate, versions]; [World, ([[name]; ['nu-cli']]), ['0.21', '0.22']]] | flatten versions --all | last | get versions", result: None, //Some(Value::test_string("0.22")), }, Example { description: "Flatten inner table", example: "{ a: b, d: [ 1 2 3 4 ], e: [ 4 3 ] } | flatten d --all", result: Some(Value::list( vec![ Value::test_record(record! { "a" => Value::test_string("b"), "d" => Value::test_int(1), "e" => Value::test_list( vec![Value::test_int(4), Value::test_int(3)], ), }), Value::test_record(record! { "a" => Value::test_string("b"), "d" => Value::test_int(2), "e" => Value::test_list( vec![Value::test_int(4), Value::test_int(3)], ), }), Value::test_record(record! { "a" => Value::test_string("b"), "d" => Value::test_int(3), "e" => Value::test_list( vec![Value::test_int(4), Value::test_int(3)], ), }), Value::test_record(record! { "a" => Value::test_string("b"), "d" => Value::test_int(4), "e" => Value::test_list( vec![Value::test_int(4), Value::test_int(3)], ) }), ], Span::test_data(), )), }, ] } } fn flatten( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let metadata = input.metadata(); let flatten_all = call.has_flag(engine_state, stack, "all")?; input .flat_map( move |item| flat_value(&columns, item, flatten_all), engine_state.signals(), ) .map(|x| x.set_metadata(metadata)) } enum TableInside { // handle for a column which contains a single list(but not list of records) // it contains (column, span, values in the column, column index). Entries(String, Vec<Value>, usize), // handle for a column which contains a table, we can flatten the inner column to outer level // `records` is the nested/inner table to flatten to the outer level // `parent_column_name` is handled for conflicting column name, the nested table may contains columns which has the same name // to outer level, for that case, the output column name should be f"{parent_column_name}_{inner_column_name}". // `parent_column_index` is the column index in original table. FlattenedRows { records: Vec<Record>, parent_column_name: String, parent_column_index: usize, }, } fn flat_value(columns: &[CellPath], item: Value, all: bool) -> Vec<Value> { let tag = item.span(); match item { Value::Record { val, .. } => { let mut out = IndexMap::<String, Value>::new(); let mut inner_table = None; for (column_index, (column, value)) in val.into_owned().into_iter().enumerate() { let column_requested = columns.iter().find(|c| c.to_column_name() == column); let need_flatten = { columns.is_empty() || column_requested.is_some() }; let span = value.span(); match value { Value::Record { ref val, .. } => { if need_flatten { for (col, val) in val.clone().into_owned() { if out.contains_key(&col) { out.insert(format!("{column}_{col}"), val); } else { out.insert(col, val); } } } else if out.contains_key(&column) { out.insert(format!("{column}_{column}"), value); } else { out.insert(column, value); } } Value::List { vals, .. } => { if need_flatten && inner_table.is_some() { return vec![Value::error( ShellError::UnsupportedInput { msg: "can only flatten one inner list at a time. tried flattening more than one column with inner lists... but is flattened already".into(), input: "value originates from here".into(), msg_span: tag, input_span: span }, span, )]; } if all && vals.iter().all(|f| f.as_record().is_ok()) { // it's a table (a list of record, we can flatten inner record) if need_flatten { let records = vals .into_iter() .filter_map(|v| v.into_record().ok()) .collect(); inner_table = Some(TableInside::FlattenedRows { records, parent_column_name: column, parent_column_index: column_index, }); } else if out.contains_key(&column) { out.insert(format!("{column}_{column}"), Value::list(vals, span)); } else { out.insert(column, Value::list(vals, span)); } } else if !columns.is_empty() { let cell_path = column_requested.and_then(|x| match x.members.first() { Some(PathMember::String { val, .. }) => Some(val), _ => None, }); if let Some(r) = cell_path { inner_table = Some(TableInside::Entries(r.clone(), vals, column_index)); } else { out.insert(column, Value::list(vals, span)); } } else { inner_table = Some(TableInside::Entries(column, vals, column_index)); } } _ => { out.insert(column, value); } } } let mut expanded = vec![]; match inner_table { Some(TableInside::Entries(column, entries, parent_column_index)) => { for entry in entries { let base = out.clone(); let mut record = Record::new(); let mut index = 0; for (col, val) in base.into_iter() { // meet the flattened column, push them to result record first // this can avoid output column order changed. if index == parent_column_index { record.push(column.clone(), entry.clone()); } record.push(col, val); index += 1; } // the flattened column may be the last column in the original table. if index == parent_column_index { record.push(column.clone(), entry); } expanded.push(Value::record(record, tag)); } } Some(TableInside::FlattenedRows { records, parent_column_name, parent_column_index, }) => { for inner_record in records { let base = out.clone(); let mut record = Record::new(); let mut index = 0; for (base_col, base_val) in base { // meet the flattened column, push them to result record first // this can avoid output column order changed. if index == parent_column_index { for (col, val) in &inner_record { if record.contains(col) { record.push( format!("{parent_column_name}_{col}"), val.clone(), ); } else { record.push(col, val.clone()); }; } } record.push(base_col, base_val); index += 1; } // the flattened column may be the last column in the original table. if index == parent_column_index { for (col, val) in inner_record { if record.contains(&col) { record.push(format!("{parent_column_name}_{col}"), val); } else { record.push(col, val); } } } expanded.push(Value::record(record, tag)); } } None => { expanded.push(Value::record(out.into_iter().collect(), tag)); } } expanded } Value::List { vals, .. } => vals, item => vec![item], } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Flatten {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/interleave.rs
crates/nu-command/src/filters/interleave.rs
use nu_engine::{ClosureEvalOnce, command_prelude::*}; use nu_protocol::{engine::Closure, shell_error::io::IoError}; use std::{sync::mpsc, thread}; #[derive(Clone)] pub struct Interleave; impl Command for Interleave { fn name(&self) -> &str { "interleave" } fn description(&self) -> &str { "Read multiple streams in parallel and combine them into one stream." } fn extra_description(&self) -> &str { r#"This combinator is useful for reading output from multiple commands. If input is provided to `interleave`, the input will be combined with the output of the closures. This enables `interleave` to be used at any position within a pipeline. Because items from each stream will be inserted into the final stream as soon as they are available, there is no guarantee of how the final output will be ordered. However, the order of items from any given stream is guaranteed to be preserved as they were in that stream. If interleaving streams in a fair (round-robin) manner is desired, consider using `zip { ... } | flatten` instead."# } fn signature(&self) -> Signature { Signature::build("interleave") .input_output_types(vec![ (Type::List(Type::Any.into()), Type::List(Type::Any.into())), (Type::Nothing, Type::List(Type::Any.into())), ]) .named( "buffer-size", SyntaxShape::Int, "Number of items to buffer from the streams. Increases memory usage, but can help \ performance when lots of output is produced.", Some('b'), ) .rest( "closures", SyntaxShape::Closure(None), "The closures that will generate streams to be combined.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "seq 1 50 | wrap a | interleave { seq 1 50 | wrap b }", description: r#"Read two sequences of numbers into separate columns of a table. Note that the order of rows with 'a' columns and rows with 'b' columns is arbitrary."#, result: None, }, Example { example: "seq 1 3 | interleave { seq 4 6 } | sort", description: "Read two sequences of numbers, one from input. Sort for consistency.", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), Value::test_int(5), Value::test_int(6), ])), }, Example { example: r#"interleave { "foo\nbar\n" | lines } { "baz\nquux\n" | lines } | sort"#, description: "Read two sequences, but without any input. Sort for consistency.", result: Some(Value::test_list(vec![ Value::test_string("bar"), Value::test_string("baz"), Value::test_string("foo"), Value::test_string("quux"), ])), }, Example { example: r#"( interleave { nu -c "print hello; print world" | lines | each { "greeter: " ++ $in } } { nu -c "print nushell; print rocks" | lines | each { "evangelist: " ++ $in } } )"#, description: "Run two commands in parallel and annotate their output.", result: None, }, Example { example: "seq 1 20000 | interleave --buffer-size 16 { seq 1 20000 } | math sum", description: "Use a buffer to increase the performance of high-volume streams.", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closures: Vec<Closure> = call.rest(engine_state, stack, 0)?; let buffer_size: usize = call .get_flag(engine_state, stack, "buffer-size")? .unwrap_or(0); let (tx, rx) = mpsc::sync_channel(buffer_size); // Spawn the threads for the input and closure outputs (!input.is_nothing()) .then(|| Ok(input)) .into_iter() .chain(closures.into_iter().map(|closure| { ClosureEvalOnce::new(engine_state, stack, closure) .run_with_input(PipelineData::empty()) })) .try_for_each(|stream| { stream.and_then(|stream| { // Then take the stream and spawn a thread to send it to our channel let tx = tx.clone(); thread::Builder::new() .name("interleave consumer".into()) .spawn(move || { for value in stream { if tx.send(value).is_err() { // Stop sending if the channel is dropped break; } } }) .map(|_| ()) .map_err(|err| IoError::new(err, head, None).into()) }) })?; // Now that threads are writing to the channel, we just return it as a stream Ok(rx .into_iter() .into_pipeline_data(head, engine_state.signals().clone())) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Interleave {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/last.rs
crates/nu-command/src/filters/last.rs
use nu_engine::command_prelude::*; use nu_protocol::shell_error::io::IoError; use std::{collections::VecDeque, io::Read}; #[derive(Clone)] pub struct Last; impl Command for Last { fn name(&self) -> &str { "last" } fn signature(&self) -> Signature { Signature::build("last") .input_output_types(vec![ ( // TODO: This is too permissive; if we could express this // using a type parameter it would be List<T> -> T. Type::List(Box::new(Type::Any)), Type::Any, ), (Type::Binary, Type::Binary), (Type::Range, Type::Any), ]) .optional( "rows", SyntaxShape::Int, "Starting from the back, the number of rows to return.", ) .switch("strict", "Throw an error if input is empty", Some('s')) .category(Category::Filters) } fn description(&self) -> &str { "Return only the last several rows of the input. Counterpart of `first`. Opposite of `drop`." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[1,2,3] | last 2", description: "Return the last 2 items of a list/table", result: Some(Value::list( vec![Value::test_int(2), Value::test_int(3)], Span::test_data(), )), }, Example { example: "[1,2,3] | last", description: "Return the last item of a list/table", result: Some(Value::test_int(3)), }, Example { example: "0x[01 23 45] | last 2", description: "Return the last 2 bytes of a binary value", result: Some(Value::binary(vec![0x23, 0x45], Span::test_data())), }, Example { example: "1..3 | last", description: "Return the last item of a range", result: Some(Value::test_int(3)), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let rows: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?; let strict_mode = call.has_flag(engine_state, stack, "strict")?; // FIXME: Please read the FIXME message in `first.rs`'s `first_helper` implementation. // It has the same issue. let return_single_element = rows.is_none(); let rows = if let Some(rows) = rows { if rows.item < 0 { return Err(ShellError::NeedsPositiveValue { span: rows.span }); } else { rows.item as usize } } else { 1 }; let metadata = input.metadata(); // early exit for `last 0` if rows == 0 { return Ok(Value::list(Vec::new(), head).into_pipeline_data_with_metadata(metadata)); } match input { PipelineData::ListStream(_, _) | PipelineData::Value(Value::Range { .. }, _) => { let iterator = input.into_iter_strict(head)?; // only keep the last `rows` in memory let mut buf = VecDeque::new(); for row in iterator { engine_state.signals().check(&head)?; if buf.len() == rows { buf.pop_front(); } buf.push_back(row); } if return_single_element { if let Some(last) = buf.pop_back() { Ok(last.into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { Ok(Value::list(buf.into(), head).into_pipeline_data_with_metadata(metadata)) } } PipelineData::Value(val, _) => { let span = val.span(); match val { Value::List { mut vals, .. } => { if return_single_element { if let Some(v) = vals.pop() { Ok(v.into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { let i = vals.len().saturating_sub(rows); vals.drain(..i); Ok(Value::list(vals, span).into_pipeline_data_with_metadata(metadata)) } } Value::Binary { mut val, .. } => { if return_single_element { if let Some(val) = val.pop() { Ok(Value::int(val.into(), span).into_pipeline_data()) } else if strict_mode { Err(ShellError::AccessEmptyContent { span: head }) } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. Ok(Value::nothing(head).into_pipeline_data_with_metadata(metadata)) } } else { let i = val.len().saturating_sub(rows); val.drain(..i); Ok(Value::binary(val, span).into_pipeline_data()) } } // Propagate errors by explicitly matching them before the final case. Value::Error { error, .. } => Err(*error), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }), } } PipelineData::ByteStream(stream, ..) => { if stream.type_().is_binary_coercible() { let span = stream.span(); if let Some(mut reader) = stream.reader() { // Have to be a bit tricky here, but just consume into a VecDeque that we // shrink to fit each time const TAKE: u64 = 8192; let mut buf = VecDeque::with_capacity(rows + TAKE as usize); loop { let taken = std::io::copy(&mut (&mut reader).take(TAKE), &mut buf) .map_err(|err| IoError::new(err, span, None))?; if buf.len() > rows { buf.drain(..(buf.len() - rows)); } if taken < TAKE { // This must be EOF. if return_single_element { if !buf.is_empty() { return Ok( Value::int(buf[0] as i64, head).into_pipeline_data() ); } else if strict_mode { return Err(ShellError::AccessEmptyContent { span: head }); } else { // There are no values, so return nothing instead of an error so // that users can pipe this through 'default' if they want to. return Ok(Value::nothing(head) .into_pipeline_data_with_metadata(metadata)); } } else { return Ok(Value::binary(buf, head).into_pipeline_data()); } } } } else { Ok(PipelineData::empty()) } } else { Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: stream.type_().describe().into(), dst_span: head, src_span: stream.span(), }) } } PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: "null".into(), dst_span: call.head, src_span: call.head, }), } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Last {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/default.rs
crates/nu-command/src/filters/default.rs
use std::{borrow::Cow, ops::Deref}; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::{ ListStream, ReportMode, ShellWarning, Signals, ast::{Expr, Expression}, report_shell_warning, }; #[derive(Clone)] pub struct Default; impl Command for Default { fn name(&self) -> &str { "default" } fn signature(&self) -> Signature { Signature::build("default") // TODO: Give more specific type signature? // TODO: Declare usage of cell paths in signature? (It seems to behave as if it uses cell paths) .input_output_types(vec![(Type::Any, Type::Any)]) .required( "default value", SyntaxShape::Any, "The value to use as a default.", ) .rest( "column name", SyntaxShape::String, "The name of the column.", ) .switch( "empty", "also replace empty items like \"\", {}, and []", Some('e'), ) .category(Category::Filters) } // FIXME remove once deprecation warning is no longer needed fn requires_ast_for_arguments(&self) -> bool { true } fn description(&self) -> &str { "Sets a default value if a row's column is missing or null." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let default_value: Value = call.req(engine_state, stack, 0)?; let columns: Vec<String> = call.rest(engine_state, stack, 1)?; let empty = call.has_flag(engine_state, stack, "empty")?; // FIXME for deprecation of closure passed via variable let default_value_expr = call.positional_nth(stack, 0); let default_value = DefaultValue::new(engine_state, stack, default_value, default_value_expr); default( call, input, default_value, empty, columns, engine_state.signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Give a default 'target' column to all file entries", example: "ls -la | default 'nothing' target ", result: None, }, Example { description: "Get the env value of `MY_ENV` with a default value 'abc' if not present", example: "$env | get --optional MY_ENV | default 'abc'", result: Some(Value::test_string("abc")), }, Example { description: "Replace the `null` value in a list", example: "[1, 2, null, 4] | each { default 3 }", result: Some(Value::list( vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ], Span::test_data(), )), }, Example { description: r#"Replace the missing value in the "a" column of a list"#, example: "[{a:1 b:2} {b:1}] | default 'N/A' a", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_string("N/A"), "b" => Value::test_int(1), }), ])), }, Example { description: r#"Replace the empty string in the "a" column of a list"#, example: "[{a:1 b:2} {a:'' b:1}] | default -e 'N/A' a", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_string("N/A"), "b" => Value::test_int(1), }), ])), }, Example { description: r#"Generate a default value from a closure"#, example: "null | default { 1 + 2 }", result: Some(Value::test_int(3)), }, Example { description: r#"Fill missing column values based on other columns"#, example: r#"[{a:1 b:2} {b:1}] | upsert a {|rc| default { $rc.b + 1 } }"#, result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_int(2), "b" => Value::test_int(1), }), ])), }, ] } } fn default( call: &Call, input: PipelineData, mut default_value: DefaultValue, default_when_empty: bool, columns: Vec<String>, signals: &Signals, ) -> Result<PipelineData, ShellError> { let input_span = input.span().unwrap_or(call.head); let metadata = input.metadata(); // If user supplies columns, check if input is a record or list of records // and set the default value for the specified record columns if !columns.is_empty() { if let PipelineData::Value(Value::Record { .. }, _) = input { let record = input.into_value(input_span)?.into_record()?; fill_record( record, input_span, &mut default_value, columns.as_slice(), default_when_empty, ) .map(|x| x.into_pipeline_data_with_metadata(metadata)) } else if matches!( input, PipelineData::ListStream(..) | PipelineData::Value(Value::List { .. }, _) ) { // Potential enhancement: add another branch for Value::List, // and collect the iterator into a Result<Value::List, ShellError> // so we can preemptively return an error for collected lists let head = call.head; Ok(input .into_iter() .map(move |item| { let span = item.span(); if let Value::Record { val, .. } = item { fill_record( val.into_owned(), span, &mut default_value, columns.as_slice(), default_when_empty, ) .unwrap_or_else(|err| Value::error(err, head)) } else { item } }) .into_pipeline_data_with_metadata(head, signals.clone(), metadata)) // If columns are given, but input does not use columns, return an error } else { Err(ShellError::PipelineMismatch { exp_input_type: "record, table".to_string(), dst_span: input_span, src_span: input_span, }) } // Otherwise, if no column name is given, check if value is null // or an empty string, list, or record when --empty is passed } else if input.is_nothing() || (default_when_empty && matches!(input, PipelineData::Value(ref value, _) if value.is_empty())) { default_value.single_run_pipeline_data() } else if default_when_empty && matches!(input, PipelineData::ListStream(..)) { let PipelineData::ListStream(ls, metadata) = input else { unreachable!() }; let span = ls.span(); let mut stream = ls.into_inner().peekable(); if stream.peek().is_none() { return default_value.single_run_pipeline_data(); } // stream's internal state already preserves the original signals config, so if this // Signals::empty list stream gets interrupted it will be caught by the underlying iterator let ls = ListStream::new(stream, span, Signals::empty()); Ok(PipelineData::list_stream(ls, metadata)) // Otherwise, return the input as is } else { Ok(input) } } /// A wrapper around the default value to handle closures and caching values enum DefaultValue { Uncalculated(Box<Spanned<ClosureEval>>), Calculated(Value), } impl DefaultValue { fn new( engine_state: &EngineState, stack: &Stack, value: Value, expr: Option<&Expression>, ) -> Self { let span = value.span(); // FIXME temporary workaround to warn people of breaking change from #15654 let value = match closure_variable_warning(stack, engine_state, value, expr) { Ok(val) => val, Err(default_value) => return default_value, }; match value { Value::Closure { val, .. } => { let closure_eval = ClosureEval::new(engine_state, stack, *val); DefaultValue::Uncalculated(Box::new(closure_eval.into_spanned(span))) } _ => DefaultValue::Calculated(value), } } fn value(&mut self) -> Result<Value, ShellError> { match self { DefaultValue::Uncalculated(closure) => { let value = closure .item .run_with_input(PipelineData::empty())? .into_value(closure.span)?; *self = DefaultValue::Calculated(value.clone()); Ok(value) } DefaultValue::Calculated(value) => Ok(value.clone()), } } /// Used when we know the value won't need to be cached to allow streaming. fn single_run_pipeline_data(self) -> Result<PipelineData, ShellError> { match self { DefaultValue::Uncalculated(mut closure) => { closure.item.run_with_input(PipelineData::empty()) } DefaultValue::Calculated(val) => Ok(val.into_pipeline_data()), } } } /// Given a record, fill missing columns with a default value fn fill_record( mut record: Record, span: Span, default_value: &mut DefaultValue, columns: &[String], empty: bool, ) -> Result<Value, ShellError> { for col in columns { if let Some(val) = record.get_mut(col) { if matches!(val, Value::Nothing { .. }) || (empty && val.is_empty()) { *val = default_value.value()?; } } else { record.push(col.clone(), default_value.value()?); } } Ok(Value::record(record, span)) } fn closure_variable_warning( stack: &Stack, engine_state: &EngineState, value: Value, value_expr: Option<&Expression>, ) -> Result<Value, DefaultValue> { // only warn if we are passed a closure inside a variable let from_variable = matches!( value_expr, Some(Expression { expr: Expr::FullCellPath(_), .. }) ); let span = value.span(); match (&value, from_variable) { // this is a closure from inside a variable (Value::Closure { .. }, true) => { let span_contents = String::from_utf8_lossy(engine_state.get_span_contents(span)); let carapace_suggestion = "re-run carapace init with version v1.3.3 or later\nor, change this to `{ $carapace_completer }`"; let label = match span_contents { Cow::Borrowed("$carapace_completer") => carapace_suggestion.to_string(), Cow::Owned(s) if s.deref() == "$carapace_completer" => { carapace_suggestion.to_string() } _ => format!("change this to {{ {span_contents} }}").to_string(), }; report_shell_warning( Some(stack), engine_state, &ShellWarning::Deprecated { dep_type: "Behavior".to_string(), label, span, help: Some( r"Since 0.105.0, closure literals passed to default are lazily evaluated, rather than returned as a value. In a future release, closures passed by variable will also be lazily evaluated.".to_string(), ), report_mode: ReportMode::FirstUse, }, ); // bypass the normal DefaultValue::new logic Err(DefaultValue::Calculated(value)) } _ => Ok(value), } } #[cfg(test)] mod test { use crate::Upsert; use super::*; #[test] fn test_examples() { use crate::test_examples_with_commands; test_examples_with_commands(Default {}, &[&Upsert]); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/find.rs
crates/nu-command/src/filters/find.rs
use fancy_regex::{Regex, escape}; use nu_ansi_term::Style; use nu_color_config::StyleComputer; use nu_engine::command_prelude::*; use nu_protocol::Config; #[derive(Clone)] pub struct Find; impl Command for Find { fn name(&self) -> &str { "find" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ ( // TODO: This is too permissive; if we could express this // using a type parameter it would be List<T> -> List<T>. Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::String, Type::Any), ]) .named( "regex", SyntaxShape::String, "regex to match with", Some('r'), ) .switch( "ignore-case", "case-insensitive; when in regex mode, this is equivalent to (?i)", Some('i'), ) .switch( "multiline", "don't split multi-line strings into lists of lines. you should use this option when using the (?m) or (?s) flags in regex mode", Some('m'), ) .switch( "dotall", "dotall regex mode: allow a dot . to match newlines \\n; equivalent to (?s)", Some('s'), ) .named( "columns", SyntaxShape::List(Box::new(SyntaxShape::String)), "column names to be searched", Some('c'), ) .switch( "no-highlight", "no-highlight mode: find without marking with ansi code", Some('n'), ) .switch("invert", "invert the match", Some('v')) .switch( "rfind", "search from the end of the string and only return the first match", Some('R'), ) .rest("rest", SyntaxShape::Any, "Terms to search.") .category(Category::Filters) } fn description(&self) -> &str { "Searches terms in the input." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Search for multiple terms in a command output", example: r#"ls | find toml md sh"#, result: None, }, Example { description: "Search and highlight text for a term in a string.", example: r#"'Cargo.toml' | find Cargo"#, result: Some(Value::test_string( "\u{1b}[39m\u{1b}[0m\u{1b}[41;39mCargo\u{1b}[0m\u{1b}[39m.toml\u{1b}[0m" .to_owned(), )), }, Example { description: "Search a number or a file size in a list of numbers", example: r#"[1 5 3kb 4 35 3Mb] | find 5 3kb"#, result: Some(Value::list( vec![Value::test_int(5), Value::test_filesize(3000)], Span::test_data(), )), }, Example { description: "Search a char in a list of string", example: r#"[moe larry curly] | find l"#, result: Some(Value::list( vec![ Value::test_string( "\u{1b}[39m\u{1b}[0m\u{1b}[41;39ml\u{1b}[0m\u{1b}[39marry\u{1b}[0m", ), Value::test_string( "\u{1b}[39mcur\u{1b}[0m\u{1b}[41;39ml\u{1b}[0m\u{1b}[39my\u{1b}[0m", ), ], Span::test_data(), )), }, Example { description: "Search using regex", example: r#"[abc odb arc abf] | find --regex "b.""#, result: Some(Value::list( vec![ Value::test_string( "\u{1b}[39ma\u{1b}[0m\u{1b}[41;39mbc\u{1b}[0m\u{1b}[39m\u{1b}[0m" .to_string(), ), Value::test_string( "\u{1b}[39ma\u{1b}[0m\u{1b}[41;39mbf\u{1b}[0m\u{1b}[39m\u{1b}[0m" .to_string(), ), ], Span::test_data(), )), }, Example { description: "Case insensitive search", example: r#"[aBc bde Arc abf] | find "ab" -i"#, result: Some(Value::list( vec![ Value::test_string( "\u{1b}[39m\u{1b}[0m\u{1b}[41;39maB\u{1b}[0m\u{1b}[39mc\u{1b}[0m" .to_string(), ), Value::test_string( "\u{1b}[39m\u{1b}[0m\u{1b}[41;39mab\u{1b}[0m\u{1b}[39mf\u{1b}[0m" .to_string(), ), ], Span::test_data(), )), }, Example { description: "Find value in records using regex", example: r#"[[version name]; ['0.1.0' nushell] ['0.1.1' fish] ['0.2.0' zsh]] | find --regex "nu""#, result: Some(Value::test_list(vec![Value::test_record(record! { "version" => Value::test_string("0.1.0"), "name" => Value::test_string("\u{1b}[39m\u{1b}[0m\u{1b}[41;39mnu\u{1b}[0m\u{1b}[39mshell\u{1b}[0m".to_string()), })])), }, Example { description: "Find inverted values in records using regex", example: r#"[[version name]; ['0.1.0' nushell] ['0.1.1' fish] ['0.2.0' zsh]] | find --regex "nu" --invert"#, result: Some(Value::test_list(vec![ Value::test_record(record! { "version" => Value::test_string("0.1.1"), "name" => Value::test_string("fish".to_string()), }), Value::test_record(record! { "version" => Value::test_string("0.2.0"), "name" =>Value::test_string("zsh".to_string()), }), ])), }, Example { description: "Find value in list using regex", example: r#"[["Larry", "Moe"], ["Victor", "Marina"]] | find --regex "rr""#, result: Some(Value::list( vec![Value::list( vec![ Value::test_string( "\u{1b}[39mLa\u{1b}[0m\u{1b}[41;39mrr\u{1b}[0m\u{1b}[39my\u{1b}[0m", ), Value::test_string("Moe"), ], Span::test_data(), )], Span::test_data(), )), }, Example { description: "Find inverted values in records using regex", example: r#"[["Larry", "Moe"], ["Victor", "Marina"]] | find --regex "rr" --invert"#, result: Some(Value::list( vec![Value::list( vec![Value::test_string("Victor"), Value::test_string("Marina")], Span::test_data(), )], Span::test_data(), )), }, Example { description: "Remove ANSI sequences from result", example: "[[foo bar]; [abc 123] [def 456]] | find --no-highlight 123", result: Some(Value::list( vec![Value::test_record(record! { "foo" => Value::test_string("abc"), "bar" => Value::test_int(123) })], Span::test_data(), )), }, Example { description: "Find and highlight text in specific columns", example: "[[col1 col2 col3]; [moe larry curly] [larry curly moe]] | find moe --columns [col1]", result: Some(Value::list( vec![Value::test_record(record! { "col1" => Value::test_string( "\u{1b}[39m\u{1b}[0m\u{1b}[41;39mmoe\u{1b}[0m\u{1b}[39m\u{1b}[0m" .to_string(), ), "col2" => Value::test_string("larry".to_string()), "col3" => Value::test_string("curly".to_string()), })], Span::test_data(), )), }, Example { description: "Find in a multi-line string", example: "'Violets are red\nAnd roses are blue\nWhen metamaterials\nAlter their hue' | find ue", result: Some(Value::list( vec![ Value::test_string( "\u{1b}[39mAnd roses are bl\u{1b}[0m\u{1b}[41;39mue\u{1b}[0m\u{1b}[39m\u{1b}[0m", ), Value::test_string( "\u{1b}[39mAlter their h\u{1b}[0m\u{1b}[41;39mue\u{1b}[0m\u{1b}[39m\u{1b}[0m", ), ], Span::test_data(), )), }, Example { description: "Find in a multi-line string without splitting the input into a list of lines", example: "'Violets are red\nAnd roses are blue\nWhen metamaterials\nAlter their hue' | find --multiline ue", result: Some(Value::test_string( "\u{1b}[39mViolets are red\nAnd roses are bl\u{1b}[0m\u{1b}[41;39mue\u{1b}[0m\u{1b}[39m\nWhen metamaterials\nAlter their h\u{1b}[0m\u{1b}[41;39mue\u{1b}[0m\u{1b}[39m\u{1b}[0m", )), }, Example { description: "Find and highlight the last occurrence in a string", example: r#"'hello world hello' | find --rfind hello"#, result: Some(Value::test_string( "\u{1b}[39mhello world \u{1b}[0m\u{1b}[41;39mhello\u{1b}[0m\u{1b}[39m\u{1b}[0m", )), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["filter", "regex", "search", "condition", "grep"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let pattern = get_match_pattern_from_arguments(engine_state, stack, call)?; let multiline = call.has_flag(engine_state, stack, "multiline")?; let columns_to_search: Vec<_> = call .get_flag(engine_state, stack, "columns")? .unwrap_or_default(); let input = if multiline { if let PipelineData::ByteStream(..) = input { // ByteStream inputs are processed by iterating over the lines, which necessarily // breaks the multi-line text being streamed into a list of lines. return Err(ShellError::IncompatibleParametersSingle { msg: "Flag `--multiline` currently doesn't work for byte stream inputs. Consider using `collect`".into(), span: call.get_flag_span(stack, "multiline").expect("has flag"), }); }; input } else { split_string_if_multiline(input, call.head) }; find_in_pipelinedata(pattern, columns_to_search, engine_state, stack, input) } } #[derive(Clone)] struct MatchPattern { /// the regex to be used for matching in text regex: Regex, /// the list of match terms (converted to lowercase if needed), or empty if a regex was provided search_terms: Vec<String>, /// case-insensitive match ignore_case: bool, /// return a modified version of the value where matching parts are highlighted highlight: bool, /// return the values that aren't a match instead invert: bool, /// search from the end (find last occurrence) rfind: bool, /// style of the non-highlighted string sections string_style: Style, /// style of the highlighted string sections highlight_style: Style, } fn get_match_pattern_from_arguments( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<MatchPattern, ShellError> { let config = stack.get_config(engine_state); let span = call.head; let regex = call.get_flag::<String>(engine_state, stack, "regex")?; let terms = call.rest::<Value>(engine_state, stack, 0)?; let invert = call.has_flag(engine_state, stack, "invert")?; let highlight = !call.has_flag(engine_state, stack, "no-highlight")?; let rfind = call.has_flag(engine_state, stack, "rfind")?; let ignore_case = call.has_flag(engine_state, stack, "ignore-case")?; let dotall = call.has_flag(engine_state, stack, "dotall")?; let style_computer = StyleComputer::from_config(engine_state, stack); // Currently, search results all use the same style. // Also note that this sample string is passed into user-written code (the closure that may or may not be // defined for "string"). let string_style = style_computer.compute("string", &Value::string("search result", span)); let highlight_style = style_computer.compute("search_result", &Value::string("search result", span)); let (regex_str, search_terms) = if let Some(regex) = regex { if !terms.is_empty() { return Err(ShellError::IncompatibleParametersSingle { msg: "Cannot use a `--regex` parameter with additional search terms".into(), span: call.get_flag_span(stack, "regex").expect("has flag"), }); } let flags = match (ignore_case, dotall) { (false, false) => "", (true, false) => "(?i)", // case insensitive (false, true) => "(?s)", // allow . to match \n (true, true) => "(?is)", // case insensitive and allow . to match \n }; (flags.to_string() + regex.as_str(), Vec::new()) } else { if dotall { return Err(ShellError::IncompatibleParametersSingle { msg: "Flag --dotall only works for regex search".into(), span: call.get_flag_span(stack, "dotall").expect("has flag"), }); } let mut regex = String::new(); if ignore_case { regex += "(?i)"; } let search_terms = terms .iter() .map(|v| { if ignore_case { v.to_expanded_string("", &config).to_lowercase() } else { v.to_expanded_string("", &config) } }) .collect::<Vec<String>>(); let escaped_terms = search_terms .iter() .map(|v| escape(v).into()) .collect::<Vec<String>>(); if let Some(term) = escaped_terms.first() { regex += term; } for term in escaped_terms.iter().skip(1) { regex += "|"; regex += term; } (regex, search_terms) }; let regex = Regex::new(regex_str.as_str()).map_err(|e| ShellError::TypeMismatch { err_message: format!("invalid regex: {e}"), span, })?; Ok(MatchPattern { regex, search_terms, ignore_case, invert, highlight, rfind, string_style, highlight_style, }) } // map functions fn highlight_matches_in_string(pattern: &MatchPattern, val: String) -> String { if !pattern.regex.is_match(&val).unwrap_or(false) { return val; } let stripped_val = nu_utils::strip_ansi_string_unlikely(val); if pattern.rfind { highlight_last_match(pattern, &stripped_val) } else { highlight_all_matches(pattern, &stripped_val) } } fn highlight_last_match(pattern: &MatchPattern, text: &str) -> String { // Find the last match using fold to avoid collecting all matches let last_match = pattern.regex.find_iter(text).fold(None, |_, m| m.ok()); match last_match { Some(m) => { let start = m.start(); let end = m.end(); format!( "{}{}{}", pattern.string_style.paint(&text[..start]), pattern.highlight_style.paint(&text[start..end]), pattern.string_style.paint(&text[end..]) ) } None => pattern.string_style.paint(text).to_string(), } } fn highlight_all_matches(pattern: &MatchPattern, text: &str) -> String { let mut last_match_end = 0; let mut highlighted = String::new(); for cap in pattern.regex.captures_iter(text) { let capture = match cap { Ok(capture) => capture, Err(_) => return pattern.string_style.paint(text).to_string(), }; let m = match capture.get(0) { Some(m) => m, None => continue, }; highlighted.push_str( &pattern .string_style .paint(&text[last_match_end..m.start()]) .to_string(), ); highlighted.push_str( &pattern .highlight_style .paint(&text[m.start()..m.end()]) .to_string(), ); last_match_end = m.end(); } highlighted.push_str( &pattern .string_style .paint(&text[last_match_end..]) .to_string(), ); highlighted } fn highlight_matches_in_value( pattern: &MatchPattern, value: Value, columns_to_search: &[String], ) -> Value { if !pattern.highlight || pattern.invert { return value; } let span = value.span(); match value { Value::Record { val: record, .. } => { let col_select = !columns_to_search.is_empty(); // TODO: change API to mutate in place let mut record = record.into_owned(); for (col, val) in record.iter_mut() { if col_select && !columns_to_search.contains(col) { continue; } *val = highlight_matches_in_value(pattern, std::mem::take(val), &[]); } Value::record(record, span) } Value::List { vals, .. } => vals .into_iter() .map(|item| highlight_matches_in_value(pattern, item, &[])) .collect::<Vec<Value>>() .into_value(span), Value::String { val, .. } => highlight_matches_in_string(pattern, val).into_value(span), _ => value, } } fn find_in_pipelinedata( pattern: MatchPattern, columns_to_search: Vec<String>, engine_state: &EngineState, stack: &mut Stack, input: PipelineData, ) -> Result<PipelineData, ShellError> { let config = stack.get_config(engine_state); let map_pattern = pattern.clone(); let map_columns_to_search = columns_to_search.clone(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(_, _) => input .filter( move |value| { value_should_be_printed(&pattern, value, &columns_to_search, &config) != pattern.invert }, engine_state.signals(), )? .map( move |x| highlight_matches_in_value(&map_pattern, x, &map_columns_to_search), engine_state.signals(), ), PipelineData::ListStream(stream, metadata) => { let stream = stream.modify(|iter| { iter.filter(move |value| { value_should_be_printed(&pattern, value, &columns_to_search, &config) != pattern.invert }) .map(move |x| highlight_matches_in_value(&map_pattern, x, &map_columns_to_search)) }); Ok(PipelineData::list_stream(stream, metadata)) } PipelineData::ByteStream(stream, ..) => { let span = stream.span(); if let Some(lines) = stream.lines() { let mut output: Vec<Value> = vec![]; for line in lines { let line = line?; if string_should_be_printed(&pattern, &line) != pattern.invert { if pattern.highlight && !pattern.invert { output .push(highlight_matches_in_string(&pattern, line).into_value(span)) } else { output.push(line.into_value(span)) } } } Ok(Value::list(output, span).into_pipeline_data()) } else { Ok(PipelineData::empty()) } } } } // filter functions fn string_should_be_printed(pattern: &MatchPattern, value: &str) -> bool { pattern.regex.is_match(value).unwrap_or(false) } fn value_should_be_printed( pattern: &MatchPattern, value: &Value, columns_to_search: &[String], config: &Config, ) -> bool { let value_as_string = if pattern.ignore_case { value.to_expanded_string("", config).to_lowercase() } else { value.to_expanded_string("", config) }; match value { Value::Bool { .. } | Value::Int { .. } | Value::Filesize { .. } | Value::Duration { .. } | Value::Date { .. } | Value::Range { .. } | Value::Float { .. } | Value::Closure { .. } | Value::Nothing { .. } => { if !pattern.search_terms.is_empty() { // look for exact match when searching with terms pattern .search_terms .iter() .any(|term: &String| term == &value_as_string) } else { string_should_be_printed(pattern, &value_as_string) } } Value::Glob { .. } | Value::CellPath { .. } | Value::Custom { .. } => { string_should_be_printed(pattern, &value_as_string) } Value::String { val, .. } => string_should_be_printed(pattern, val), Value::List { vals, .. } => vals .iter() .any(|item| value_should_be_printed(pattern, item, &[], config)), Value::Record { val: record, .. } => { let col_select = !columns_to_search.is_empty(); record.iter().any(|(col, val)| { if col_select && !columns_to_search.contains(col) { return false; } value_should_be_printed(pattern, val, &[], config) }) } Value::Binary { .. } => false, Value::Error { .. } => true, } } // utility fn split_string_if_multiline(input: PipelineData, head_span: Span) -> PipelineData { let span = input.span().unwrap_or(head_span); match input { PipelineData::Value(Value::String { ref val, .. }, _) => { if val.contains('\n') { Value::list( val.lines() .map(|s| Value::string(s.to_string(), span)) .collect(), span, ) .into_pipeline_data_with_metadata(input.metadata()) } else { input } } _ => input, } } /// function for using find from other commands pub fn find_internal( input: PipelineData, engine_state: &EngineState, stack: &mut Stack, search_term: &str, columns_to_search: &[&str], highlight: bool, ) -> Result<PipelineData, ShellError> { let span = input.span().unwrap_or(Span::unknown()); let style_computer = StyleComputer::from_config(engine_state, stack); let string_style = style_computer.compute("string", &Value::string("search result", span)); let highlight_style = style_computer.compute("search_result", &Value::string("search result", span)); let regex_str = format!("(?i){}", escape(search_term)); let regex = Regex::new(regex_str.as_str()).map_err(|e| ShellError::TypeMismatch { err_message: format!("invalid regex: {e}"), span: Span::unknown(), })?; let pattern = MatchPattern { regex, search_terms: vec![search_term.to_lowercase()], ignore_case: true, highlight, invert: false, rfind: false, string_style, highlight_style, }; let columns_to_search = columns_to_search .iter() .map(|str| String::from(*str)) .collect(); find_in_pipelinedata(pattern, columns_to_search, engine_state, stack, input) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Find) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/enumerate.rs
crates/nu-command/src/filters/enumerate.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Enumerate; impl Command for Enumerate { fn name(&self) -> &str { "enumerate" } fn description(&self) -> &str { "Enumerate the elements in a stream." } fn search_terms(&self) -> Vec<&str> { vec!["itemize"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("enumerate") .input_output_types(vec![(Type::Any, Type::table())]) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Add an index to each element of a list", example: r#"[a, b, c] | enumerate "#, result: Some(Value::test_list(vec![ Value::test_record(record! { "index" => Value::test_int(0), "item" => Value::test_string("a"), }), Value::test_record(record! { "index" => Value::test_int(1), "item" => Value::test_string("b"), }), Value::test_record(record! { "index" => Value::test_int(2), "item" => Value::test_string("c"), }), ])), }] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let metadata = input.metadata(); Ok(input .into_iter() .enumerate() .map(move |(idx, x)| { Value::record( record! { "index" => Value::int(idx as i64, head), "item" => x, }, head, ) }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Enumerate {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/reduce.rs
crates/nu-command/src/filters/reduce.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct Reduce; impl Command for Reduce { fn name(&self) -> &str { "reduce" } fn signature(&self) -> Signature { Signature::build("reduce") .input_output_types(vec![ (Type::List(Box::new(Type::Any)), Type::Any), (Type::table(), Type::Any), (Type::Range, Type::Any), ]) .named( "fold", SyntaxShape::Any, "reduce with initial value", Some('f'), ) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])), "Reducing function.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Aggregate a list (starting from the left) to a single value using an accumulator closure." } fn search_terms(&self) -> Vec<&str> { vec!["map", "fold", "foldl"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[ 1 2 3 4 ] | reduce {|it, acc| $it + $acc }", description: "Sum values of a list (same as 'math sum')", result: Some(Value::test_int(10)), }, Example { example: "[ 1 2 3 4 ] | reduce {|it, acc| $acc - $it }", description: r#"`reduce` accumulates value from left to right, equivalent to (((1 - 2) - 3) - 4)."#, result: Some(Value::test_int(-8)), }, Example { example: "[ 8 7 6 ] | enumerate | reduce --fold 0 {|it, acc| $acc + $it.item + $it.index }", description: "Sum values of a list, plus their indexes", result: Some(Value::test_int(24)), }, Example { example: "[ 1 2 3 4 ] | reduce --fold 10 {|it, acc| $acc + $it }", description: "Sum values with a starting value (fold)", result: Some(Value::test_int(20)), }, Example { example: r#"[[foo baz] [baz quux]] | reduce --fold "foobar" {|it, acc| $acc | str replace $it.0 $it.1}"#, description: "Iteratively perform string replace (from left to right): 'foobar' -> 'bazbar' -> 'quuxbar'", result: Some(Value::test_string("quuxbar")), }, Example { example: r#"[ i o t ] | reduce --fold "Arthur, King of the Britons" {|it, acc| $acc | str replace --all $it "X" }"#, description: "Replace selected characters in a string with 'X'", result: Some(Value::test_string("ArXhur, KXng Xf Xhe BrXXXns")), }, Example { example: r#"['foo.gz', 'bar.gz', 'baz.gz'] | enumerate | reduce --fold '' {|str all| $"($all)(if $str.index != 0 {'; '})($str.index + 1)-($str.item)" }"#, description: "Add ascending numbers to each of the filenames, and join with semicolons.", result: Some(Value::test_string("1-foo.gz; 2-bar.gz; 3-baz.gz")), }, Example { example: r#"let s = "Str"; 0..2 | reduce --fold '' {|it, acc| $acc + $s}"#, description: "Concatenate a string with itself, using a range to determine the number of times.", result: Some(Value::test_string("StrStrStr")), }, Example { example: r#"[{a: 1} {b: 2} {c: 3}] | reduce {|it| merge $it}"#, description: "Merge multiple records together, making use of the fact that the accumulated value is also supplied as pipeline input to the closure.", result: Some(Value::test_record(record!( "a" => Value::test_int(1), "b" => Value::test_int(2), "c" => Value::test_int(3), ))), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let fold: Option<Value> = call.get_flag(engine_state, stack, "fold")?; let closure: Closure = call.req(engine_state, stack, 0)?; let mut iter = input.into_iter(); let mut acc = fold .or_else(|| iter.next()) .ok_or_else(|| ShellError::GenericError { error: "Expected input".into(), msg: "needs input".into(), span: Some(head), help: None, inner: vec![], })?; let mut closure = ClosureEval::new(engine_state, stack, closure); for value in iter { engine_state.signals().check(&head)?; acc = closure .add_arg(value) .add_arg(acc.clone()) .run_with_input(PipelineData::value(acc, None))? .into_value(head)?; } Ok(acc.with_span(head).into_pipeline_data()) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::{Merge, test_examples_with_commands}; test_examples_with_commands(Reduce {}, &[&Merge]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/uniq_by.rs
crates/nu-command/src/filters/uniq_by.rs
pub use super::uniq; use nu_engine::{column::nonexistent_column, command_prelude::*}; #[derive(Clone)] pub struct UniqBy; impl Command for UniqBy { fn name(&self) -> &str { "uniq-by" } fn signature(&self) -> Signature { Signature::build("uniq-by") .input_output_types(vec![ (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .rest("columns", SyntaxShape::Any, "The column(s) to filter by.") .switch( "count", "Return a table containing the distinct input values together with their counts", Some('c'), ) .switch( "repeated", "Return the input values that occur more than once", Some('d'), ) .switch( "ignore-case", "Ignore differences in case when comparing input values", Some('i'), ) .switch( "unique", "Return the input values that occur once only", Some('u'), ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Return the distinct values in the input by the given column(s)." } fn search_terms(&self) -> Vec<&str> { vec!["distinct", "deduplicate"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Vec<String> = call.rest(engine_state, stack, 0)?; if columns.is_empty() { return Err(ShellError::MissingParameter { param_name: "columns".into(), span: call.head, }); } let metadata = input.metadata(); let vec: Vec<_> = input.into_iter().collect(); match validate(&vec, &columns, call.head) { Ok(_) => {} Err(err) => { return Err(err); } } let mapper = Box::new(item_mapper_by_col(columns)); uniq(engine_state, stack, call, vec, mapper, metadata) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Get rows from table filtered by column uniqueness ", example: "[[fruit count]; [apple 9] [apple 2] [pear 3] [orange 7]] | uniq-by fruit", result: Some(Value::test_list(vec![ Value::test_record(record! { "fruit" => Value::test_string("apple"), "count" => Value::test_int(9), }), Value::test_record(record! { "fruit" => Value::test_string("pear"), "count" => Value::test_int(3), }), Value::test_record(record! { "fruit" => Value::test_string("orange"), "count" => Value::test_int(7), }), ])), }] } } fn validate(vec: &[Value], columns: &[String], span: Span) -> Result<(), ShellError> { let first = vec.first(); if let Some(v) = first { let val_span = v.span(); if let Value::Record { val: record, .. } = &v { if columns.is_empty() { return Err(ShellError::GenericError { error: "expected name".into(), msg: "requires a column name to filter table data".into(), span: Some(span), help: None, inner: vec![], }); } if let Some(nonexistent) = nonexistent_column(columns, record.columns()) { return Err(ShellError::CantFindColumn { col_name: nonexistent, span: Some(span), src_span: val_span, }); } } } Ok(()) } fn get_data_by_columns(columns: &[String], item: &Value) -> Vec<Value> { columns .iter() .filter_map(|col| item.get_data_by_key(col)) .collect::<Vec<_>>() } fn item_mapper_by_col(cols: Vec<String>) -> impl Fn(crate::ItemMapperState) -> crate::ValueCounter { let columns = cols; Box::new(move |ms: crate::ItemMapperState| -> crate::ValueCounter { let item_column_values = get_data_by_columns(&columns, &ms.item); let col_vals = Value::list(item_column_values, Span::unknown()); crate::ValueCounter::new_vals_to_compare(ms.item, ms.flag_ignore_case, col_vals, ms.index) }) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(UniqBy {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/uniq.rs
crates/nu-command/src/filters/uniq.rs
use itertools::Itertools; use nu_engine::command_prelude::*; use nu_protocol::PipelineMetadata; use nu_utils::IgnoreCaseExt; use std::collections::{HashMap, hash_map::IntoIter}; #[derive(Clone)] pub struct Uniq; impl Command for Uniq { fn name(&self) -> &str { "uniq" } fn signature(&self) -> Signature { Signature::build("uniq") .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .switch( "count", "Return a table containing the distinct input values together with their counts", Some('c'), ) .switch( "repeated", "Return the input values that occur more than once", Some('d'), ) .switch( "ignore-case", "Compare input values case-insensitively", Some('i'), ) .switch( "unique", "Return the input values that occur once only", Some('u'), ) .category(Category::Filters) } fn description(&self) -> &str { "Return the distinct values in the input." } fn search_terms(&self) -> Vec<&str> { vec!["distinct", "deduplicate", "count"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let mapper = Box::new(move |ms: ItemMapperState| -> ValueCounter { item_mapper(ms.item, ms.flag_ignore_case, ms.index) }); let metadata = input.metadata(); uniq( engine_state, stack, call, input.into_iter().collect(), mapper, metadata, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return the distinct values of a list/table (remove duplicates so that each value occurs once only)", example: "[2 3 3 4] | uniq", result: Some(Value::list( vec![Value::test_int(2), Value::test_int(3), Value::test_int(4)], Span::test_data(), )), }, Example { description: "Return the input values that occur more than once", example: "[1 2 2] | uniq -d", result: Some(Value::list(vec![Value::test_int(2)], Span::test_data())), }, Example { description: "Return the input values that occur once only", example: "[1 2 2] | uniq --unique", result: Some(Value::list(vec![Value::test_int(1)], Span::test_data())), }, Example { description: "Ignore differences in case when comparing input values", example: "['hello' 'goodbye' 'Hello'] | uniq --ignore-case", result: Some(Value::test_list(vec![ Value::test_string("hello"), Value::test_string("goodbye"), ])), }, Example { description: "Return a table containing the distinct input values together with their counts", example: "[1 2 2] | uniq --count", result: Some(Value::test_list(vec![ Value::test_record(record! { "value" => Value::test_int(1), "count" => Value::test_int(1), }), Value::test_record(record! { "value" => Value::test_int(2), "count" => Value::test_int(2), }), ])), }, ] } } pub struct ItemMapperState { pub item: Value, pub flag_ignore_case: bool, pub index: usize, } fn item_mapper(item: Value, flag_ignore_case: bool, index: usize) -> ValueCounter { ValueCounter::new(item, flag_ignore_case, index) } pub struct ValueCounter { val: Value, val_to_compare: Value, count: i64, index: usize, } impl PartialEq<Self> for ValueCounter { fn eq(&self, other: &Self) -> bool { self.val == other.val } } impl ValueCounter { fn new(val: Value, flag_ignore_case: bool, index: usize) -> Self { Self::new_vals_to_compare(val.clone(), flag_ignore_case, val, index) } pub fn new_vals_to_compare( val: Value, flag_ignore_case: bool, vals_to_compare: Value, index: usize, ) -> Self { ValueCounter { val, val_to_compare: if flag_ignore_case { clone_to_folded_case(&vals_to_compare.with_span(Span::unknown())) } else { vals_to_compare.with_span(Span::unknown()) }, count: 1, index, } } } fn clone_to_folded_case(value: &Value) -> Value { let span = value.span(); match value { Value::String { val: s, .. } => Value::string(s.clone().to_folded_case(), span), Value::List { vals: vec, .. } => { Value::list(vec.iter().map(clone_to_folded_case).collect(), span) } Value::Record { val: record, .. } => Value::record( record .iter() .map(|(k, v)| (k.to_owned(), clone_to_folded_case(v))) .collect(), span, ), other => other.clone(), } } fn sort_attributes(val: Value) -> Value { let span = val.span(); match val { Value::Record { val, .. } => { // TODO: sort inplace let sorted = val .into_owned() .into_iter() .sorted_by(|a, b| a.0.cmp(&b.0)) .collect_vec(); let record = sorted .into_iter() .map(|(k, v)| (k, sort_attributes(v))) .collect(); Value::record(record, span) } Value::List { vals, .. } => { Value::list(vals.into_iter().map(sort_attributes).collect_vec(), span) } other => other, } } fn generate_key(engine_state: &EngineState, item: &ValueCounter) -> Result<String, ShellError> { let value = sort_attributes(item.val_to_compare.clone()); //otherwise, keys could be different for Records nuon::to_nuon( engine_state, &value, nuon::ToStyle::Default, Some(Span::unknown()), false, ) } fn generate_results_with_count(head: Span, uniq_values: Vec<ValueCounter>) -> Vec<Value> { uniq_values .into_iter() .map(|item| { Value::record( record! { "value" => item.val, "count" => Value::int(item.count, head), }, head, ) }) .collect() } pub fn uniq( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: Vec<Value>, item_mapper: Box<dyn Fn(ItemMapperState) -> ValueCounter>, metadata: Option<PipelineMetadata>, ) -> Result<PipelineData, ShellError> { let head = call.head; let flag_show_count = call.has_flag(engine_state, stack, "count")?; let flag_show_repeated = call.has_flag(engine_state, stack, "repeated")?; let flag_ignore_case = call.has_flag(engine_state, stack, "ignore-case")?; let flag_only_uniques = call.has_flag(engine_state, stack, "unique")?; let signals = engine_state.signals().clone(); let uniq_values = input .into_iter() .enumerate() .map_while(|(index, item)| { if signals.interrupted() { return None; } Some(item_mapper(ItemMapperState { item, flag_ignore_case, index, })) }) .try_fold( HashMap::<String, ValueCounter>::new(), |mut counter, item| { let key = generate_key(engine_state, &item); match key { Ok(key) => { match counter.get_mut(&key) { Some(x) => x.count += 1, None => { counter.insert(key, item); } }; Ok(counter) } Err(err) => Err(err), } }, ); let mut uniq_values: HashMap<String, ValueCounter> = uniq_values?; if flag_show_repeated { uniq_values.retain(|_v, value_count_pair| value_count_pair.count > 1); } if flag_only_uniques { uniq_values.retain(|_v, value_count_pair| value_count_pair.count == 1); } let uniq_values = sort(uniq_values.into_iter()); let result = if flag_show_count { generate_results_with_count(head, uniq_values) } else { uniq_values.into_iter().map(|v| v.val).collect() }; Ok(Value::list(result, head).into_pipeline_data_with_metadata(metadata)) } fn sort(iter: IntoIter<String, ValueCounter>) -> Vec<ValueCounter> { iter.map(|item| item.1) .sorted_by(|a, b| a.index.cmp(&b.index)) .collect() } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Uniq {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/utils.rs
crates/nu-command/src/filters/utils.rs
use nu_engine::{CallExt, ClosureEval}; use nu_protocol::{ IntoPipelineData, PipelineData, ShellError, Span, Value, engine::{Call, Closure, EngineState, Stack}, }; pub fn chain_error_with_input( error_source: ShellError, input_is_error: bool, span: Span, ) -> ShellError { if !input_is_error { return ShellError::EvalBlockWithInput { span, sources: vec![error_source], }; } error_source } pub fn boolean_fold( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, accumulator: bool, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let mut closure = ClosureEval::new(engine_state, stack, closure); for value in input { engine_state.signals().check(&head)?; let pred = closure.run_with_value(value)?.into_value(head)?.is_true(); if pred == accumulator { return Ok(Value::bool(accumulator, head).into_pipeline_data()); } } Ok(Value::bool(!accumulator, head).into_pipeline_data()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/chunk_by.rs
crates/nu-command/src/filters/chunk_by.rs
use super::utils::chain_error_with_input; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::Signals; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct ChunkBy; impl Command for ChunkBy { fn name(&self) -> &str { "chunk-by" } fn signature(&self) -> Signature { Signature::build("chunk-by") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::list(Type::list(Type::Any)), ), (Type::Range, Type::list(Type::list(Type::Any))), ]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run.", ) .category(Category::Filters) } fn description(&self) -> &str { r#"Divides a sequence into sub-sequences based on a closure."# } fn extra_description(&self) -> &str { r#"chunk-by applies the given closure to each value of the input list, and groups consecutive elements that share the same closure result value into lists."# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { chunk_by(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Chunk data into runs of larger than zero or not.", example: "[1, 3, -2, -2, 0, 1, 2] | chunk-by {|it| $it >= 0 }", result: Some(Value::test_list(vec![ Value::test_list(vec![Value::test_int(1), Value::test_int(3)]), Value::test_list(vec![Value::test_int(-2), Value::test_int(-2)]), Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), ]), ])), }, Example { description: "Identify repetitions in a string", example: r#"[a b b c c c] | chunk-by { |it| $it }"#, result: Some(Value::test_list(vec![ Value::test_list(vec![Value::test_string("a")]), Value::test_list(vec![Value::test_string("b"), Value::test_string("b")]), Value::test_list(vec![ Value::test_string("c"), Value::test_string("c"), Value::test_string("c"), ]), ])), }, Example { description: "Chunk values of range by predicate", example: r#"(0..8) | chunk-by { |it| $it // 3 }"#, result: Some(Value::test_list(vec![ Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), ]), Value::test_list(vec![ Value::test_int(3), Value::test_int(4), Value::test_int(5), ]), Value::test_list(vec![ Value::test_int(6), Value::test_int(7), Value::test_int(8), ]), ])), }, ] } } struct Chunk<I, T, F, K> { iterator: I, last_value: Option<(T, K)>, closure: F, done: bool, signals: Signals, } impl<I, T, F, K> Chunk<I, T, F, K> where I: Iterator<Item = T>, F: FnMut(&T) -> K, K: PartialEq, { fn inner_iterator_next(&mut self) -> Option<I::Item> { if self.signals.interrupted() { self.done = true; return None; } self.iterator.next() } } impl<I, T, F, K> Iterator for Chunk<I, T, F, K> where I: Iterator<Item = T>, F: FnMut(&T) -> K, K: PartialEq, { type Item = Vec<T>; fn next(&mut self) -> Option<Self::Item> { if self.done { return None; } let (head, head_key) = match self.last_value.take() { None => { let head = self.inner_iterator_next()?; let key = (self.closure)(&head); (head, key) } Some((value, key)) => (value, key), }; let mut result = vec![head]; loop { match self.inner_iterator_next() { None => { self.done = true; return Some(result); } Some(value) => { let value_key = (self.closure)(&value); if value_key == head_key { result.push(value); } else { self.last_value = Some((value, value_key)); return Some(result); } } } } } } /// An iterator with the semantics of the chunk_by operation. fn chunk_iter_by<I, T, F, K>(iterator: I, signals: Signals, closure: F) -> Chunk<I, T, F, K> where I: Iterator<Item = T>, F: FnMut(&T) -> K, K: PartialEq, { Chunk { closure, iterator, last_value: None, done: false, signals, } } pub fn chunk_by( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(Value::Range { .. }, ..) | PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream(..) => { let closure = ClosureEval::new(engine_state, stack, closure); let result = chunk_value_stream( input.into_iter(), closure, head, engine_state.signals().clone(), ); Ok(result.into_pipeline_data(head, engine_state.signals().clone())) } PipelineData::ByteStream(..) | PipelineData::Value(..) => { Err(input.unsupported_input_error("list", head)) } } .map(|data| data.set_metadata(metadata)) } fn chunk_value_stream<I>( iterator: I, mut closure: ClosureEval, head: Span, signals: Signals, ) -> impl Iterator<Item = Value> + 'static + Send where I: Iterator<Item = Value> + 'static + Send, { chunk_iter_by(iterator, signals, move |value| { match closure.run_with_value(value.clone()) { Ok(data) => data.into_value(head).unwrap_or_else(|error| { Value::error(chain_error_with_input(error, value.is_error(), head), head) }), Err(error) => Value::error(chain_error_with_input(error, value.is_error(), head), head), } }) .map(move |it| Value::list(it, head)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ChunkBy {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/any.rs
crates/nu-command/src/filters/any.rs
use super::utils; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Any; impl Command for Any { fn name(&self) -> &str { "any" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::Bool)]) .required( "predicate", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "A closure that must evaluate to a boolean.", ) .category(Category::Filters) } fn description(&self) -> &str { "Tests if any element of the input fulfills a predicate expression." } fn search_terms(&self) -> Vec<&str> { vec!["some", "or"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Check if a list contains any true values", example: "[false true true false] | any {}", result: Some(Value::test_bool(true)), }, Example { description: "Check if any row's status is the string 'DOWN'", example: "[[status]; [UP] [DOWN] [UP]] | any {|el| $el.status == DOWN }", result: Some(Value::test_bool(true)), }, Example { description: "Check that any item is a string", example: "[1 2 3 4] | any {|| ($in | describe) == 'string' }", result: Some(Value::test_bool(false)), }, Example { description: "Check if any value is equal to twice its own index", example: "[9 8 7 6] | enumerate | any {|i| $i.item == $i.index * 2 }", result: Some(Value::test_bool(true)), }, Example { description: "Check if any of the values are odd, using a stored closure", example: "let cond = {|e| $e mod 2 == 1 }; [2 4 1 6 8] | any $cond", result: Some(Value::test_bool(true)), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { utils::boolean_fold(engine_state, stack, call, input, true) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Any) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/transpose.rs
crates/nu-command/src/filters/transpose.rs
use nu_engine::{column::get_columns, command_prelude::*}; #[derive(Clone)] pub struct Transpose; pub struct TransposeArgs { rest: Vec<Spanned<String>>, header_row: bool, ignore_titles: bool, as_record: bool, keep_last: bool, keep_all: bool, } impl Command for Transpose { fn name(&self) -> &str { "transpose" } fn signature(&self) -> Signature { Signature::build("transpose") .input_output_types(vec![ (Type::table(), Type::Any), (Type::record(), Type::table()), ]) .switch( "header-row", "use the first input column as the table header-row (or keynames when combined with --as-record)", Some('r'), ) .switch( "ignore-titles", "don't transpose the column names into values", Some('i'), ) .switch( "as-record", "transfer to record if the result is a table and contains only one row", Some('d'), ) .switch( "keep-last", "on repetition of record fields due to `header-row`, keep the last value obtained", Some('l'), ) .switch( "keep-all", "on repetition of record fields due to `header-row`, keep all the values obtained", Some('a'), ) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::String, "The names to give columns once transposed.", ) .category(Category::Filters) } fn description(&self) -> &str { "Transposes the table contents so rows become columns and columns become rows." } fn search_terms(&self) -> Vec<&str> { vec!["pivot"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { transpose(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Transposes the table contents with default column names", example: "[[c1 c2]; [1 2]] | transpose", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("c1"), "column1" => Value::test_int(1), }), Value::test_record(record! { "column0" => Value::test_string("c2"), "column1" => Value::test_int(2), }), ])), }, Example { description: "Transposes the table contents with specified column names", example: "[[c1 c2]; [1 2]] | transpose key val", result: Some(Value::test_list(vec![ Value::test_record(record! { "key" => Value::test_string("c1"), "val" => Value::test_int(1), }), Value::test_record(record! { "key" => Value::test_string("c2"), "val" => Value::test_int(2), }), ])), }, Example { description: "Transposes the table without column names and specify a new column name", example: "[[c1 c2]; [1 2]] | transpose --ignore-titles val", result: Some(Value::test_list(vec![ Value::test_record(record! { "val" => Value::test_int(1), }), Value::test_record(record! { "val" => Value::test_int(2), }), ])), }, Example { description: "Transfer back to record with -d flag", example: "{c1: 1, c2: 2} | transpose | transpose --ignore-titles -r -d", result: Some(Value::test_record(record! { "c1" => Value::test_int(1), "c2" => Value::test_int(2), })), }, ] } } pub fn transpose( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let name = call.head; let args = TransposeArgs { header_row: call.has_flag(engine_state, stack, "header-row")?, ignore_titles: call.has_flag(engine_state, stack, "ignore-titles")?, as_record: call.has_flag(engine_state, stack, "as-record")?, keep_last: call.has_flag(engine_state, stack, "keep-last")?, keep_all: call.has_flag(engine_state, stack, "keep-all")?, rest: call.rest(engine_state, stack, 0)?, }; if !args.rest.is_empty() && args.header_row { return Err(ShellError::IncompatibleParametersSingle { msg: "Can not provide header names and use `--header-row`".into(), span: call.get_flag_span(stack, "header-row").expect("has flag"), }); } if !args.header_row && args.keep_all { return Err(ShellError::IncompatibleParametersSingle { msg: "Can only be used with `--header-row`(`-r`)".into(), span: call.get_flag_span(stack, "keep-all").expect("has flag"), }); } if !args.header_row && args.keep_last { return Err(ShellError::IncompatibleParametersSingle { msg: "Can only be used with `--header-row`(`-r`)".into(), span: call.get_flag_span(stack, "keep-last").expect("has flag"), }); } if args.keep_all && args.keep_last { return Err(ShellError::IncompatibleParameters { left_message: "can't use `--keep-last` at the same time".into(), left_span: call.get_flag_span(stack, "keep-last").expect("has flag"), right_message: "because of `--keep-all`".into(), right_span: call.get_flag_span(stack, "keep-all").expect("has flag"), }); } let metadata = input.metadata(); let input: Vec<_> = input.into_iter().collect(); // Ensure error values are propagated and non-record values are rejected for value in input.iter() { match value { Value::Error { .. } => { return Ok(value.clone().into_pipeline_data_with_metadata(metadata)); } Value::Record { .. } => {} // go on, this is what we're looking for _ => { return Err(ShellError::OnlySupportsThisInputType { exp_input_type: "table or record".into(), wrong_type: "list<any>".into(), dst_span: call.head, src_span: value.span(), }); } } } let descs = get_columns(&input); let mut headers: Vec<String> = Vec::with_capacity(input.len()); if args.header_row { for i in input.iter() { if let Some(desc) = descs.first() { match &i.get_data_by_key(desc) { Some(x) => { if let Ok(s) = x.coerce_string() { headers.push(s); } else { return Err(ShellError::GenericError { error: "Header row needs string headers".into(), msg: "used non-string headers".into(), span: Some(name), help: None, inner: vec![], }); } } _ => { return Err(ShellError::GenericError { error: "Header row is incomplete and can't be used".into(), msg: "using incomplete header row".into(), span: Some(name), help: None, inner: vec![], }); } } } else { return Err(ShellError::GenericError { error: "Header row is incomplete and can't be used".into(), msg: "using incomplete header row".into(), span: Some(name), help: None, inner: vec![], }); } } } else { for i in 0..=input.len() { if let Some(name) = args.rest.get(i) { headers.push(name.item.clone()) } else { headers.push(format!("column{i}")); } } } let mut descs = descs.into_iter(); if args.header_row { descs.next(); } let mut result_data = descs .map(|desc| { let mut column_num: usize = 0; let mut record = Record::new(); if !args.ignore_titles && !args.header_row { record.push( headers[column_num].clone(), Value::string(desc.clone(), name), ); column_num += 1 } for i in input.iter() { let x = i .get_data_by_key(&desc) .unwrap_or_else(|| Value::nothing(name)); match record.get_mut(&headers[column_num]) { None => { record.push(headers[column_num].clone(), x); } Some(val) => { if args.keep_all { let current_span = val.span(); match val { Value::List { vals, .. } => { vals.push(x); } v => { *v = Value::list(vec![std::mem::take(v), x], current_span); } }; } else if args.keep_last { *val = x; } } } column_num += 1; } Value::record(record, name) }) .collect::<Vec<Value>>(); if result_data.len() == 1 && args.as_record { Ok(PipelineData::value( result_data .pop() .expect("already check result only contains one item"), metadata, )) } else { Ok(result_data.into_pipeline_data_with_metadata( name, engine_state.signals().clone(), metadata, )) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Transpose {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/mod.rs
crates/nu-command/src/filters/mod.rs
mod all; mod any; mod append; mod chunk_by; mod chunks; mod columns; mod compact; mod default; mod drop; mod each; mod empty; mod enumerate; mod every; mod filter; mod find; mod first; mod flatten; mod get; mod group_by; mod headers; mod insert; mod interleave; mod is_empty; mod is_not_empty; mod items; mod join; mod last; mod length; mod lines; mod merge; mod move_; mod par_each; mod prepend; mod reduce; mod reject; mod rename; mod reverse; mod select; #[cfg(feature = "rand")] mod shuffle; mod skip; mod slice; mod sort; mod sort_by; mod take; mod tee; mod transpose; mod uniq; mod uniq_by; mod update; mod upsert; mod utils; mod values; mod where_; mod window; mod wrap; mod zip; pub use all::All; pub use any::Any; pub use append::Append; pub use chunk_by::ChunkBy; pub use chunks::Chunks; pub use columns::Columns; pub use compact::Compact; pub use default::Default; pub use drop::*; pub use each::Each; pub use empty::empty; pub use enumerate::Enumerate; pub use every::Every; pub use filter::Filter; pub use find::{Find, find_internal}; pub use first::First; pub use flatten::Flatten; pub use get::Get; pub use group_by::GroupBy; pub use headers::Headers; pub use insert::Insert; pub use interleave::Interleave; pub use is_empty::IsEmpty; pub use is_not_empty::IsNotEmpty; pub use items::Items; pub use join::Join; pub use last::Last; pub use length::Length; pub use lines::Lines; pub use merge::Merge; pub use merge::MergeDeep; pub use move_::Move; pub use par_each::ParEach; pub use prepend::Prepend; pub use reduce::Reduce; pub use reject::Reject; pub use rename::Rename; pub use reverse::Reverse; pub use select::Select; #[cfg(feature = "rand")] pub use shuffle::Shuffle; pub use skip::*; pub use slice::Slice; pub use sort::Sort; pub use sort_by::SortBy; pub use take::*; pub use tee::Tee; pub use transpose::Transpose; pub use uniq::*; pub use uniq_by::UniqBy; pub use update::Update; pub use upsert::Upsert; pub use values::Values; pub use where_::Where; pub use window::Window; pub use wrap::Wrap; pub use zip::Zip;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/append.rs
crates/nu-command/src/filters/append.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Append; impl Command for Append { fn name(&self) -> &str { "append" } fn signature(&self) -> nu_protocol::Signature { Signature::build("append") .input_output_types(vec![(Type::Any, Type::List(Box::new(Type::Any)))]) .required( "row", SyntaxShape::Any, "The row, list, or table to append.", ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Append any number of rows to a table." } fn extra_description(&self) -> &str { r#"Be aware that this command 'unwraps' lists passed to it. So, if you pass a variable to it, and you want the variable's contents to be appended without being unwrapped, it's wise to pre-emptively wrap the variable in a list, like so: `append [$val]`. This way, `append` will only unwrap the outer list, and leave the variable's contents untouched."# } fn search_terms(&self) -> Vec<&str> { vec!["add", "concatenate"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[0 1 2 3] | append 4", description: "Append one int to a list", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { example: "0 | append [1 2 3]", description: "Append a list to an item", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), ])), }, Example { example: r#""a" | append ["b"] "#, description: "Append a list of string to a string", result: Some(Value::test_list(vec![ Value::test_string("a"), Value::test_string("b"), ])), }, Example { example: "[0 1] | append [2 3 4]", description: "Append three int items", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, Example { example: "[0 1] | append [2 nu 4 shell]", description: "Append ints and strings", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_string("nu"), Value::test_int(4), Value::test_string("shell"), ])), }, Example { example: "[0 1] | append 2..4", description: "Append a range of ints to a list", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), Value::test_int(4), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let other: Value = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); Ok(input .into_iter() .chain(other.into_pipeline_data()) .into_pipeline_data_with_metadata(call.head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Append {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/join.rs
crates/nu-command/src/filters/join.rs
use nu_engine::command_prelude::*; use nu_protocol::Config; use std::{ cmp::max, collections::{HashMap, HashSet}, }; #[derive(Clone)] pub struct Join; enum JoinType { Inner, Left, Right, Outer, } enum IncludeInner { No, Yes, } impl Command for Join { fn name(&self) -> &str { "join" } fn signature(&self) -> Signature { Signature::build("join") .required( "right-table", SyntaxShape::Table([].into()), "The right table in the join.", ) .required( "left-on", SyntaxShape::String, "Name of column in input (left) table to join on.", ) .optional( "right-on", SyntaxShape::String, "Name of column in right table to join on. Defaults to same column as left table.", ) .switch("inner", "Inner join (default)", Some('i')) .switch("left", "Left-outer join", Some('l')) .switch("right", "Right-outer join", Some('r')) .switch("outer", "Outer join", Some('o')) .input_output_types(vec![(Type::table(), Type::table())]) .category(Category::Filters) } fn description(&self) -> &str { "Join two tables." } fn search_terms(&self) -> Vec<&str> { vec!["sql"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { let metadata = input.metadata(); let table_2: Value = call.req(engine_state, stack, 0)?; let l_on: Value = call.req(engine_state, stack, 1)?; let r_on: Value = call .opt(engine_state, stack, 2)? .unwrap_or_else(|| l_on.clone()); let span = call.head; let join_type = join_type(engine_state, stack, call)?; // FIXME: we should handle ListStreams properly instead of collecting let collected_input = input.into_value(span)?; match (&collected_input, &table_2, &l_on, &r_on) { ( Value::List { vals: rows_1, .. }, Value::List { vals: rows_2, .. }, Value::String { val: l_on, .. }, Value::String { val: r_on, .. }, ) => { let result = join(rows_1, rows_2, l_on, r_on, join_type, span); Ok(PipelineData::value(result, metadata)) } _ => Err(ShellError::UnsupportedInput { msg: "(PipelineData<table>, table, string, string)".into(), input: format!( "({:?}, {:?}, {:?} {:?})", collected_input, table_2.get_type(), l_on.get_type(), r_on.get_type(), ), msg_span: span, input_span: span, }), } } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Join two tables", example: "[{a: 1 b: 2}] | join [{a: 1 c: 3}] a", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), "c" => Value::test_int(3), })])), }] } } fn join_type( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<JoinType, nu_protocol::ShellError> { match ( call.has_flag(engine_state, stack, "inner")?, call.has_flag(engine_state, stack, "left")?, call.has_flag(engine_state, stack, "right")?, call.has_flag(engine_state, stack, "outer")?, ) { (_, false, false, false) => Ok(JoinType::Inner), (false, true, false, false) => Ok(JoinType::Left), (false, false, true, false) => Ok(JoinType::Right), (false, false, false, true) => Ok(JoinType::Outer), _ => Err(ShellError::UnsupportedInput { msg: "Choose one of: --inner, --left, --right, --outer".into(), input: "".into(), msg_span: call.head, input_span: call.head, }), } } fn join( left: &[Value], right: &[Value], left_join_key: &str, right_join_key: &str, join_type: JoinType, span: Span, ) -> Value { // Inner / Right Join // ------------------ // Make look-up table from rows on left // For each row r on right: // If any matching rows on left: // For each matching row l on left: // Emit (l, r) // Else if RightJoin: // Emit (null, r) // Left Join // ---------- // Make look-up table from rows on right // For each row l on left: // If any matching rows on right: // For each matching row r on right: // Emit (l, r) // Else: // Emit (l, null) // Outer Join // ---------- // Perform Left Join procedure // Perform Right Join procedure, but excluding rows in Inner Join let config = Config::default(); let sep = ","; let cap = max(left.len(), right.len()); let shared_join_key = if left_join_key == right_join_key { Some(left_join_key) } else { None }; // For the "other" table, create a map from value in `on` column to a list of the // rows having that value. let mut result: Vec<Value> = Vec::new(); let is_outer = matches!(join_type, JoinType::Outer); let (this, this_join_key, other, other_keys, join_type) = match join_type { JoinType::Left | JoinType::Outer => ( left, left_join_key, lookup_table(right, right_join_key, sep, cap, &config), column_names(right), // For Outer we do a Left pass and a Right pass; this is the Left // pass. JoinType::Left, ), JoinType::Inner | JoinType::Right => ( right, right_join_key, lookup_table(left, left_join_key, sep, cap, &config), column_names(left), join_type, ), }; join_rows( &mut result, this, this_join_key, other, other_keys, shared_join_key, &join_type, IncludeInner::Yes, sep, &config, span, ); if is_outer { let (this, this_join_key, other, other_names, join_type) = ( right, right_join_key, lookup_table(left, left_join_key, sep, cap, &config), column_names(left), JoinType::Right, ); join_rows( &mut result, this, this_join_key, other, other_names, shared_join_key, &join_type, IncludeInner::No, sep, &config, span, ); } Value::list(result, span) } // Join rows of `this` (a nushell table) to rows of `other` (a lookup-table // containing rows of a nushell table). #[allow(clippy::too_many_arguments)] fn join_rows( result: &mut Vec<Value>, this: &[Value], this_join_key: &str, other: HashMap<String, Vec<&Record>>, other_keys: Vec<&String>, shared_join_key: Option<&str>, join_type: &JoinType, include_inner: IncludeInner, sep: &str, config: &Config, span: Span, ) { if !this .iter() .any(|this_record| match this_record.as_record() { Ok(record) => record.contains(this_join_key), Err(_) => false, }) { // `this` table does not contain the join column; do nothing return; } for this_row in this { if let Value::Record { val: this_record, .. } = this_row { if let Some(this_valkey) = this_record.get(this_join_key) && let Some(other_rows) = other.get(&this_valkey.to_expanded_string(sep, config)) { if let IncludeInner::Yes = include_inner { for other_record in other_rows { // `other` table contains rows matching `this` row on the join column let record = match join_type { JoinType::Inner | JoinType::Right => merge_records( other_record, // `other` (lookup) is the left input table this_record, shared_join_key, ), JoinType::Left => merge_records( this_record, // `this` is the left input table other_record, shared_join_key, ), _ => panic!("not implemented"), }; result.push(Value::record(record, span)) } } continue; } if !matches!(join_type, JoinType::Inner) { // Either `this` row is missing a value for the join column or // `other` table did not contain any rows matching // `this` row on the join column; emit a single joined // row with null values for columns not present let other_record = other_keys .iter() .map(|&key| { let val = if Some(key.as_ref()) == shared_join_key { this_record .get(key) .cloned() .unwrap_or_else(|| Value::nothing(span)) } else { Value::nothing(span) }; (key.clone(), val) }) .collect(); let record = match join_type { JoinType::Inner | JoinType::Right => { merge_records(&other_record, this_record, shared_join_key) } JoinType::Left => merge_records(this_record, &other_record, shared_join_key), _ => panic!("not implemented"), }; result.push(Value::record(record, span)) } }; } } // Return column names (i.e. ordered keys from the first row; we assume that // these are the same for all rows). fn column_names(table: &[Value]) -> Vec<&String> { table .iter() .find_map(|val| match val { Value::Record { val, .. } => Some(val.columns().collect()), _ => None, }) .unwrap_or_default() } // Create a map from value in `on` column to a list of the rows having that // value. fn lookup_table<'a>( rows: &'a [Value], on: &str, sep: &str, cap: usize, config: &Config, ) -> HashMap<String, Vec<&'a Record>> { let mut map = HashMap::<String, Vec<&'a Record>>::with_capacity(cap); for row in rows { if let Value::Record { val: record, .. } = row && let Some(val) = record.get(on) { let valkey = val.to_expanded_string(sep, config); map.entry(valkey).or_default().push(record); }; } map } // Merge `left` and `right` records, renaming keys in `right` where they clash // with keys in `left`. If `shared_key` is supplied then it is the name of a key // that should not be renamed (its values are guaranteed to be equal). fn merge_records(left: &Record, right: &Record, shared_key: Option<&str>) -> Record { let cap = max(left.len(), right.len()); let mut seen = HashSet::with_capacity(cap); let mut record = Record::with_capacity(cap); for (k, v) in left { record.push(k.clone(), v.clone()); seen.insert(k); } for (k, v) in right { let k_seen = seen.contains(k); let k_shared = shared_key == Some(k.as_str()); // Do not output shared join key twice if !(k_seen && k_shared) { record.push(if k_seen { format!("{k}_") } else { k.clone() }, v.clone()); } } record } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Join {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/window.rs
crates/nu-command/src/filters/window.rs
use nu_engine::command_prelude::*; use nu_protocol::ListStream; use std::num::NonZeroUsize; #[derive(Clone)] pub struct Window; impl Command for Window { fn name(&self) -> &str { "window" } fn signature(&self) -> Signature { Signature::build("window") .input_output_types(vec![( Type::list(Type::Any), Type::list(Type::list(Type::Any)), )]) .required("window_size", SyntaxShape::Int, "The size of each window.") .named( "stride", SyntaxShape::Int, "the number of rows to slide over between windows", Some('s'), ) .switch( "remainder", "yield last chunks even if they have fewer elements than size", Some('r'), ) .category(Category::Filters) } fn description(&self) -> &str { "Creates a sliding window of `window_size` that slide by n rows/elements across input." } fn extra_description(&self) -> &str { "This command will error if `window_size` or `stride` are negative or zero." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[1 2 3 4] | window 2", description: "A sliding window of two elements", result: Some(Value::test_list(vec![ Value::test_list(vec![Value::test_int(1), Value::test_int(2)]), Value::test_list(vec![Value::test_int(2), Value::test_int(3)]), Value::test_list(vec![Value::test_int(3), Value::test_int(4)]), ])), }, Example { example: "[1, 2, 3, 4, 5, 6, 7, 8] | window 2 --stride 3", description: "A sliding window of two elements, with a stride of 3", result: Some(Value::test_list(vec![ Value::test_list(vec![Value::test_int(1), Value::test_int(2)]), Value::test_list(vec![Value::test_int(4), Value::test_int(5)]), Value::test_list(vec![Value::test_int(7), Value::test_int(8)]), ])), }, Example { example: "[1, 2, 3, 4, 5] | window 3 --stride 3 --remainder", description: "A sliding window of equal stride that includes remainder. Equivalent to chunking", result: Some(Value::test_list(vec![ Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), ]), Value::test_list(vec![Value::test_int(4), Value::test_int(5)]), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let window_size: Value = call.req(engine_state, stack, 0)?; let stride: Option<Value> = call.get_flag(engine_state, stack, "stride")?; let remainder = call.has_flag(engine_state, stack, "remainder")?; let size = usize::try_from(window_size.as_int()?).map_err(|_| ShellError::NeedsPositiveValue { span: window_size.span(), })?; let size = NonZeroUsize::try_from(size).map_err(|_| ShellError::IncorrectValue { msg: "`window_size` cannot be zero".into(), val_span: window_size.span(), call_span: head, })?; let stride = if let Some(stride_val) = stride { let stride = usize::try_from(stride_val.as_int()?).map_err(|_| { ShellError::NeedsPositiveValue { span: stride_val.span(), } })?; NonZeroUsize::try_from(stride).map_err(|_| ShellError::IncorrectValue { msg: "`stride` cannot be zero".into(), val_span: stride_val.span(), call_span: head, })? } else { NonZeroUsize::MIN }; if remainder && size == stride { super::chunks::chunks(engine_state, input, size, head) } else if stride >= size { match input { PipelineData::Value(Value::List { vals, .. }, metadata) => { let chunks = WindowGapIter::new(vals, size, stride, remainder, head); let stream = ListStream::new(chunks, head, engine_state.signals().clone()); Ok(PipelineData::list_stream(stream, metadata)) } PipelineData::ListStream(stream, metadata) => { let stream = stream .modify(|iter| WindowGapIter::new(iter, size, stride, remainder, head)); Ok(PipelineData::list_stream(stream, metadata)) } input => Err(input.unsupported_input_error("list", head)), } } else { match input { PipelineData::Value(Value::List { vals, .. }, metadata) => { let chunks = WindowOverlapIter::new(vals, size, stride, remainder, head); let stream = ListStream::new(chunks, head, engine_state.signals().clone()); Ok(PipelineData::list_stream(stream, metadata)) } PipelineData::ListStream(stream, metadata) => { let stream = stream .modify(|iter| WindowOverlapIter::new(iter, size, stride, remainder, head)); Ok(PipelineData::list_stream(stream, metadata)) } input => Err(input.unsupported_input_error("list", head)), } } } } struct WindowOverlapIter<I: Iterator<Item = Value>> { iter: I, window: Vec<Value>, stride: usize, remainder: bool, span: Span, } impl<I: Iterator<Item = Value>> WindowOverlapIter<I> { fn new( iter: impl IntoIterator<IntoIter = I>, size: NonZeroUsize, stride: NonZeroUsize, remainder: bool, span: Span, ) -> Self { Self { iter: iter.into_iter(), window: Vec::with_capacity(size.into()), stride: stride.into(), remainder, span, } } } impl<I: Iterator<Item = Value>> Iterator for WindowOverlapIter<I> { type Item = Value; fn next(&mut self) -> Option<Self::Item> { let len = if self.window.is_empty() { self.window.capacity() } else { self.stride }; self.window.extend((&mut self.iter).take(len)); if self.window.len() == self.window.capacity() || (self.remainder && !self.window.is_empty()) { let mut next = Vec::with_capacity(self.window.len()); next.extend(self.window.iter().skip(self.stride).cloned()); let window = std::mem::replace(&mut self.window, next); Some(Value::list(window, self.span)) } else { None } } } struct WindowGapIter<I: Iterator<Item = Value>> { iter: I, size: usize, skip: usize, first: bool, remainder: bool, span: Span, } impl<I: Iterator<Item = Value>> WindowGapIter<I> { fn new( iter: impl IntoIterator<IntoIter = I>, size: NonZeroUsize, stride: NonZeroUsize, remainder: bool, span: Span, ) -> Self { let size = size.into(); Self { iter: iter.into_iter(), size, skip: stride.get() - size, first: true, remainder, span, } } } impl<I: Iterator<Item = Value>> Iterator for WindowGapIter<I> { type Item = Value; fn next(&mut self) -> Option<Self::Item> { let mut window = Vec::with_capacity(self.size); window.extend( (&mut self.iter) .skip(if self.first { 0 } else { self.skip }) .take(self.size), ); self.first = false; if window.len() == self.size || (self.remainder && !window.is_empty()) { Some(Value::list(window, self.span)) } else { None } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Window {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/reject.rs
crates/nu-command/src/filters/reject.rs
use nu_engine::command_prelude::*; use nu_protocol::{DeprecationEntry, DeprecationType, ReportMode, ast::PathMember, casing::Casing}; use std::{cmp::Reverse, collections::HashSet}; #[derive(Clone)] pub struct Reject; impl Command for Reject { fn name(&self) -> &str { "reject" } fn signature(&self) -> Signature { Signature::build("reject") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), (Type::list(Type::Any), Type::list(Type::Any)), ]) .switch("optional", "make all cell path members optional", Some('o')) .switch( "ignore-case", "make all cell path members case insensitive", None, ) .switch( "ignore-errors", "ignore missing data (make all cell path members optional) (deprecated)", Some('i'), ) .rest( "rest", SyntaxShape::CellPath, "The names of columns to remove from the table.", ) .category(Category::Filters) } fn description(&self) -> &str { "Remove the given columns or rows from the table. Opposite of `select`." } fn extra_description(&self) -> &str { "To remove a quantity of rows or columns, use `skip`, `drop`, or `drop column`." } fn search_terms(&self) -> Vec<&str> { vec!["drop", "key"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let columns: Vec<Value> = call.rest(engine_state, stack, 0)?; let mut new_columns: Vec<CellPath> = vec![]; for col_val in columns { let col_span = &col_val.span(); match col_val { Value::CellPath { val, .. } => { new_columns.push(val); } Value::String { val, .. } => { let cv = CellPath { members: vec![PathMember::String { val: val.clone(), span: *col_span, optional: false, casing: Casing::Sensitive, }], }; new_columns.push(cv.clone()); } Value::Int { val, .. } => { let cv = CellPath { members: vec![PathMember::Int { val: val as usize, span: *col_span, optional: false, }], }; new_columns.push(cv.clone()); } x => { return Err(ShellError::CantConvert { to_type: "cell path".into(), from_type: x.get_type().to_string(), span: x.span(), help: None, }); } } } let span = call.head; let optional = call.has_flag(engine_state, stack, "optional")? || call.has_flag(engine_state, stack, "ignore-errors")?; let ignore_case = call.has_flag(engine_state, stack, "ignore-case")?; if optional { for cell_path in &mut new_columns { cell_path.make_optional(); } } if ignore_case { for cell_path in &mut new_columns { cell_path.make_insensitive(); } } reject(engine_state, span, input, new_columns) } fn deprecation_info(&self) -> Vec<DeprecationEntry> { vec![DeprecationEntry { ty: DeprecationType::Flag("ignore-errors".into()), report_mode: ReportMode::FirstUse, since: Some("0.106.0".into()), expected_removal: None, help: Some( "This flag has been renamed to `--optional (-o)` to better reflect its behavior." .into(), ), }] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Reject a column in the `ls` table", example: "ls | reject modified", result: None, }, Example { description: "Reject a column in a table", example: "[[a, b]; [1, 2]] | reject a", result: Some(Value::test_list(vec![Value::test_record(record! { "b" => Value::test_int(2), })])), }, Example { description: "Reject a row in a table", example: "[[a, b]; [1, 2] [3, 4]] | reject 1", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), })])), }, Example { description: "Reject the specified field in a record", example: "{a: 1, b: 2} | reject a", result: Some(Value::test_record(record! { "b" => Value::test_int(2), })), }, Example { description: "Reject a nested field in a record", example: "{a: {b: 3, c: 5}} | reject a.b", result: Some(Value::test_record(record! { "a" => Value::test_record(record! { "c" => Value::test_int(5), }), })), }, Example { description: "Reject multiple rows", example: "[[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb] [file.json json 3kb]] | reject 0 2", result: None, }, Example { description: "Reject multiple columns", example: "[[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb]] | reject type size", result: Some(Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("Cargo.toml") }), Value::test_record(record! { "name" => Value::test_string("Cargo.lock") }), ])), }, Example { description: "Reject multiple columns by spreading a list", example: "let cols = [type size]; [[name type size]; [Cargo.toml toml 1kb] [Cargo.lock toml 2kb]] | reject ...$cols", result: Some(Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("Cargo.toml") }), Value::test_record(record! { "name" => Value::test_string("Cargo.lock") }), ])), }, Example { description: "Reject item in list", example: "[1 2 3] | reject 1", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(3), ])), }, ] } } fn reject( engine_state: &EngineState, span: Span, input: PipelineData, cell_paths: Vec<CellPath>, ) -> Result<PipelineData, ShellError> { let mut unique_rows: HashSet<usize> = HashSet::new(); let metadata = input.metadata(); let mut new_columns = vec![]; let mut new_rows = vec![]; for column in cell_paths { let CellPath { ref members } = column; match members.first() { Some(PathMember::Int { val, span, .. }) => { if members.len() > 1 { return Err(ShellError::GenericError { error: "Reject only allows row numbers for rows".into(), msg: "extra after row number".into(), span: Some(*span), help: None, inner: vec![], }); } if !unique_rows.contains(val) { unique_rows.insert(*val); new_rows.push(column); } } _ => { if !new_columns.contains(&column) { new_columns.push(column) } } }; } new_rows.sort_unstable_by_key(|k| { Reverse({ match k.members[0] { PathMember::Int { val, .. } => val, PathMember::String { .. } => usize::MIN, } }) }); new_columns.append(&mut new_rows); let has_integer_path_member = new_columns.iter().any(|path| { path.members .iter() .any(|member| matches!(member, PathMember::Int { .. })) }); match input { PipelineData::ListStream(stream, ..) if !has_integer_path_member => { let result = stream .into_iter() .map(move |mut value| { let span = value.span(); for cell_path in new_columns.iter() { if let Err(error) = value.remove_data_at_cell_path(&cell_path.members) { return Value::error(error, span); } } value }) .into_pipeline_data(span, engine_state.signals().clone()); Ok(result) } input => { let mut val = input.into_value(span)?; for cell_path in new_columns { val.remove_data_at_cell_path(&cell_path.members)?; } Ok(val.into_pipeline_data_with_metadata(metadata)) } } } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Reject; use crate::test_examples; test_examples(Reject {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/each.rs
crates/nu-command/src/filters/each.rs
use super::utils::chain_error_with_input; use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct Each; impl Command for Each { fn name(&self) -> &str { "each" } fn description(&self) -> &str { "Run a closure on each row of the input list, creating a new list with the results." } fn extra_description(&self) -> &str { r#"Since tables are lists of records, passing a table into 'each' will iterate over each record, not necessarily each cell within it. Avoid passing single records to this command. Since a record is a one-row structure, 'each' will only run once, behaving similar to 'do'. To iterate over a record's values, use 'items' or try converting it to a table with 'transpose' first. By default, for each input there is a single output value. If the closure returns a stream rather than value, the stream is collected completely, and the resulting value becomes one of the items in `each`'s output. To receive items from those streams without waiting for the whole stream to be collected, `each --flatten` can be used. Instead of waiting for the stream to be collected before returning the result as a single item, `each --flatten` will return each item as soon as they are received. This "flattens" the output, turning an output that would otherwise be a list of lists like `list<list<string>>` into a flat list like `list<string>`."# } fn search_terms(&self) -> Vec<&str> { vec!["for", "loop", "iterate", "map"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("each") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::table(), Type::List(Box::new(Type::Any))), (Type::Any, Type::Any), ]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run.", ) .switch("keep-empty", "keep empty result cells", Some('k')) .switch( "flatten", "combine outputs into a single stream instead of \ collecting them to separate values", Some('f'), ) .allow_variants_without_examples(true) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[1 2 3] | each {|e| 2 * $e }", description: "Multiplies elements in the list", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(4), Value::test_int(6), ])), }, Example { example: "{major:2, minor:1, patch:4} | values | each {|| into string }", description: "Produce a list of values in the record, converted to string", result: Some(Value::test_list(vec![ Value::test_string("2"), Value::test_string("1"), Value::test_string("4"), ])), }, Example { example: r#"[1 2 3 2] | each {|e| if $e == 2 { "two" } }"#, description: "'null' items will be dropped from the result list. It has the same effect as 'filter_map' in other languages.", result: Some(Value::test_list(vec![ Value::test_string("two"), Value::test_string("two"), ])), }, Example { example: r#"[1 2 3] | enumerate | each {|e| if $e.item == 2 { $"found 2 at ($e.index)!"} }"#, description: "Iterate over each element, producing a list showing indexes of any 2s", result: Some(Value::test_list(vec![Value::test_string("found 2 at 1!")])), }, Example { example: r#"[1 2 3] | each --keep-empty {|e| if $e == 2 { "found 2!"} }"#, description: "Iterate over each element, keeping null results", result: Some(Value::test_list(vec![ Value::nothing(Span::test_data()), Value::test_string("found 2!"), Value::nothing(Span::test_data()), ])), }, Example { example: r#"$env.name? | each { $"hello ($in)" } | default "bye""#, description: "Update value if not null, otherwise do nothing", result: None, }, Example { description: "Scan through multiple files without pause", example: "\ ls *.txt \ | each --flatten {|f| open $f.name | lines } \ | find -i 'note: ' \ | str join \"\\n\"\ ", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let keep_empty = call.has_flag(engine_state, stack, "keep-empty")?; let flatten = call.has_flag(engine_state, stack, "flatten")?; let metadata = input.metadata(); let result = match input { empty @ (PipelineData::Empty | PipelineData::Value(Value::Nothing { .. }, ..)) => { return Ok(empty); } PipelineData::Value(Value::Range { .. }, ..) | PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream(..) => { let mut closure = ClosureEval::new(engine_state, stack, closure); let out = if flatten { input .into_iter() .flat_map(move |value| { closure.run_with_value(value).unwrap_or_else(|error| { Value::error(error, head).into_pipeline_data() }) }) .into_pipeline_data(head, engine_state.signals().clone()) } else { input .into_iter() .map(move |value| { each_map(value, &mut closure, head) .unwrap_or_else(|error| Value::error(error, head)) }) .into_pipeline_data(head, engine_state.signals().clone()) }; Ok(out) } PipelineData::ByteStream(stream, ..) => { let Some(chunks) = stream.chunks() else { return Ok(PipelineData::empty().set_metadata(metadata)); }; let mut closure = ClosureEval::new(engine_state, stack, closure); let out = if flatten { chunks .flat_map(move |result| { result .and_then(|value| closure.run_with_value(value)) .unwrap_or_else(|error| { Value::error(error, head).into_pipeline_data() }) }) .into_pipeline_data(head, engine_state.signals().clone()) } else { chunks .map(move |result| { result .and_then(|value| each_map(value, &mut closure, head)) .unwrap_or_else(|error| Value::error(error, head)) }) .into_pipeline_data(head, engine_state.signals().clone()) }; Ok(out) } // This match allows non-iterables to be accepted, // which is currently considered undesirable (Nov 2022). PipelineData::Value(value, ..) => { ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value) } }; if keep_empty { result } else { result.and_then(|x| x.filter(|v| !v.is_nothing(), engine_state.signals())) } .map(|data| data.set_metadata(metadata)) } } #[inline] fn each_map(value: Value, closure: &mut ClosureEval, head: Span) -> Result<Value, ShellError> { let span = value.span(); let is_error = value.is_error(); closure .run_with_value(value) .and_then(|pipeline_data| pipeline_data.into_value(head)) .map_err(|error| chain_error_with_input(error, is_error, span)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Each {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/is_empty.rs
crates/nu-command/src/filters/is_empty.rs
use crate::filters::empty::empty; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct IsEmpty; impl Command for IsEmpty { fn name(&self) -> &str { "is-empty" } fn signature(&self) -> Signature { Signature::build("is-empty") .input_output_types(vec![(Type::Any, Type::Bool)]) .rest( "rest", SyntaxShape::CellPath, "The names of the columns to check emptiness.", ) .category(Category::Filters) } fn description(&self) -> &str { "Check for empty values." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { empty(engine_state, stack, call, input, false) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Check if a string is empty", example: "'' | is-empty", result: Some(Value::test_bool(true)), }, Example { description: "Check if a list is empty", example: "[] | is-empty", result: Some(Value::test_bool(true)), }, Example { // TODO: revisit empty cell path semantics for a record. description: "Check if more than one column are empty", example: "[[meal size]; [arepa small] [taco '']] | is-empty meal size", result: Some(Value::test_bool(false)), }, ] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(IsEmpty {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/lines.rs
crates/nu-command/src/filters/lines.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Lines; impl Command for Lines { fn name(&self) -> &str { "lines" } fn description(&self) -> &str { "Converts input to lines." } fn signature(&self) -> nu_protocol::Signature { Signature::build("lines") .input_output_types(vec![(Type::Any, Type::List(Box::new(Type::String)))]) .switch("skip-empty", "skip empty lines", Some('s')) .category(Category::Filters) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let skip_empty = call.has_flag(engine_state, stack, "skip-empty")?; let span = input.span().unwrap_or(call.head); match input { PipelineData::Value(value, ..) => match value { Value::String { val, .. } => { let lines = if skip_empty { val.lines() .filter_map(|s| { if s.trim().is_empty() { None } else { Some(Value::string(s, span)) } }) .collect() } else { val.lines().map(|s| Value::string(s, span)).collect() }; Ok(Value::list(lines, span).into_pipeline_data()) } // Propagate existing errors Value::Error { error, .. } => Err(*error), value => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "string or byte stream".into(), wrong_type: value.get_type().to_string(), dst_span: head, src_span: value.span(), }), }, PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::ListStream(stream, metadata) => { let stream = stream.modify(|iter| { iter.filter_map(move |value| { let span = value.span(); if let Value::String { val, .. } = value { Some( val.lines() .filter_map(|s| { if skip_empty && s.trim().is_empty() { None } else { Some(Value::string(s, span)) } }) .collect::<Vec<_>>(), ) } else { None } }) .flatten() }); Ok(PipelineData::list_stream(stream, metadata)) } PipelineData::ByteStream(stream, ..) => { if let Some(lines) = stream.lines() { Ok(lines .map(move |line| match line { Ok(line) => Value::string(line, head), Err(err) => Value::error(err, head), }) .into_pipeline_data(head, engine_state.signals().clone())) } else { Ok(PipelineData::empty()) } } } } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Split multi-line string into lines", example: r#"$"two\nlines" | lines"#, result: Some(Value::list( vec![Value::test_string("two"), Value::test_string("lines")], Span::test_data(), )), }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Lines {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/group_by.rs
crates/nu-command/src/filters/group_by.rs
use indexmap::IndexMap; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::{FromValue, IntoValue, engine::Closure}; #[derive(Clone)] pub struct GroupBy; impl Command for GroupBy { fn name(&self) -> &str { "group-by" } fn signature(&self) -> Signature { Signature::build("group-by") .input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::Any)]) .switch( "to-table", "Return a table with \"groups\" and \"items\" columns", None, ) .rest( "grouper", SyntaxShape::OneOf(vec![ SyntaxShape::CellPath, SyntaxShape::Closure(None), SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), ]), "The path to the column to group on.", ) .category(Category::Filters) } fn description(&self) -> &str { "Splits a list or table into groups, and returns a record containing those groups." } fn extra_description(&self) -> &str { r#"the group-by command makes some assumptions: - if the input data is not a string, the grouper will convert the key to string but the values will remain in their original format. e.g. with bools, "true" and true would be in the same group (see example). - datetime is formatted based on your configuration setting. use `format date` to change the format. - filesize is formatted based on your configuration setting. use `format filesize` to change the format. - some nushell values are not supported, such as closures."# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { group_by(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Group items by the \"type\" column's values", example: r#"ls | group-by type"#, result: None, }, Example { description: "Group items by the \"foo\" column's values, ignoring records without a \"foo\" column", example: r#"open cool.json | group-by foo?"#, result: None, }, Example { description: "Group using a block which is evaluated against each input value", example: "[foo.txt bar.csv baz.txt] | group-by { path parse | get extension }", result: Some(Value::test_record(record! { "txt" => Value::test_list(vec![ Value::test_string("foo.txt"), Value::test_string("baz.txt"), ]), "csv" => Value::test_list(vec![Value::test_string("bar.csv")]), })), }, Example { description: "You can also group by raw values by leaving out the argument", example: "['1' '3' '1' '3' '2' '1' '1'] | group-by", result: Some(Value::test_record(record! { "1" => Value::test_list(vec![ Value::test_string("1"), Value::test_string("1"), Value::test_string("1"), Value::test_string("1"), ]), "3" => Value::test_list(vec![ Value::test_string("3"), Value::test_string("3"), ]), "2" => Value::test_list(vec![Value::test_string("2")]), })), }, Example { description: "You can also output a table instead of a record", example: "['1' '3' '1' '3' '2' '1' '1'] | group-by --to-table", result: Some(Value::test_list(vec![ Value::test_record(record! { "group" => Value::test_string("1"), "items" => Value::test_list(vec![ Value::test_string("1"), Value::test_string("1"), Value::test_string("1"), Value::test_string("1"), ]), }), Value::test_record(record! { "group" => Value::test_string("3"), "items" => Value::test_list(vec![ Value::test_string("3"), Value::test_string("3"), ]), }), Value::test_record(record! { "group" => Value::test_string("2"), "items" => Value::test_list(vec![Value::test_string("2")]), }), ])), }, Example { description: "Group bools, whether they are strings or actual bools", example: r#"[true "true" false "false"] | group-by"#, result: Some(Value::test_record(record! { "true" => Value::test_list(vec![ Value::test_bool(true), Value::test_string("true"), ]), "false" => Value::test_list(vec![ Value::test_bool(false), Value::test_string("false"), ]), })), }, Example { description: "Group items by multiple columns' values", example: r#"[ [name, lang, year]; [andres, rb, "2019"], [jt, rs, "2019"], [storm, rs, "2021"] ] | group-by lang year"#, result: Some(Value::test_record(record! { "rb" => Value::test_record(record! { "2019" => Value::test_list( vec![Value::test_record(record! { "name" => Value::test_string("andres"), "lang" => Value::test_string("rb"), "year" => Value::test_string("2019"), })], ), }), "rs" => Value::test_record(record! { "2019" => Value::test_list( vec![Value::test_record(record! { "name" => Value::test_string("jt"), "lang" => Value::test_string("rs"), "year" => Value::test_string("2019"), })], ), "2021" => Value::test_list( vec![Value::test_record(record! { "name" => Value::test_string("storm"), "lang" => Value::test_string("rs"), "year" => Value::test_string("2021"), })], ), }), })), }, Example { description: "Group items by multiple columns' values", example: r#"[ [name, lang, year]; [andres, rb, "2019"], [jt, rs, "2019"], [storm, rs, "2021"] ] | group-by lang year --to-table"#, result: Some(Value::test_list(vec![ Value::test_record(record! { "lang" => Value::test_string("rb"), "year" => Value::test_string("2019"), "items" => Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("andres"), "lang" => Value::test_string("rb"), "year" => Value::test_string("2019"), }) ]), }), Value::test_record(record! { "lang" => Value::test_string("rs"), "year" => Value::test_string("2019"), "items" => Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("jt"), "lang" => Value::test_string("rs"), "year" => Value::test_string("2019"), }) ]), }), Value::test_record(record! { "lang" => Value::test_string("rs"), "year" => Value::test_string("2021"), "items" => Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("storm"), "lang" => Value::test_string("rs"), "year" => Value::test_string("2021"), }) ]), }), ])), }, Example { description: "Group items by column and delete the original", example: r#"[ [name, lang, year]; [andres, rb, "2019"], [jt, rs, "2019"], [storm, rs, "2021"] ] | group-by lang | update cells { reject lang }"#, #[cfg(test)] // Cannot test this example, it requires the nu-cmd-extra crate. result: None, #[cfg(not(test))] result: Some(Value::test_record(record! { "rb" => Value::test_list(vec![Value::test_record(record! { "name" => Value::test_string("andres"), "year" => Value::test_string("2019"), })], ), "rs" => Value::test_list( vec![ Value::test_record(record! { "name" => Value::test_string("jt"), "year" => Value::test_string("2019"), }), Value::test_record(record! { "name" => Value::test_string("storm"), "year" => Value::test_string("2021"), }) ]), })), }, ] } } pub fn group_by( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let groupers: Vec<Spanned<Grouper>> = call.rest(engine_state, stack, 0)?; let to_table = call.has_flag(engine_state, stack, "to-table")?; let config = &stack.get_config(engine_state); let values: Vec<Value> = input.into_iter().collect(); if values.is_empty() { let val = if to_table { Value::list(Vec::new(), head) } else { Value::record(Record::new(), head) }; return Ok(val.into_pipeline_data()); } let grouped = match &groupers[..] { [first, rest @ ..] => { let mut grouped = Grouped::new(first.as_ref(), values, config, engine_state, stack)?; for grouper in rest { grouped.subgroup(grouper.as_ref(), config, engine_state, stack)?; } grouped } [] => Grouped::empty(values, config), }; let value = if to_table { let column_names = groupers_to_column_names(&groupers)?; grouped.into_table(&column_names, head) } else { grouped.into_record(head) }; Ok(value.into_pipeline_data()) } fn groupers_to_column_names(groupers: &[Spanned<Grouper>]) -> Result<Vec<String>, ShellError> { if groupers.is_empty() { return Ok(vec!["group".into(), "items".into()]); } let mut closure_idx: usize = 0; let grouper_names = groupers.iter().map(|grouper| { grouper.as_ref().map(|item| match item { Grouper::CellPath { val } => val.to_column_name(), Grouper::Closure { .. } => { closure_idx += 1; format!("closure_{}", closure_idx - 1) } }) }); let mut name_set: Vec<Spanned<String>> = Vec::with_capacity(grouper_names.len()); for name in grouper_names { if name.item == "items" { return Err(ShellError::GenericError { error: "grouper arguments can't be named `items`".into(), msg: "here".into(), span: Some(name.span), help: Some("instead of a cell-path, try using a closure: { get items }".into()), inner: vec![], }); } if let Some(conflicting_name) = name_set .iter() .find(|elem| elem.as_ref().item == name.item.as_str()) { return Err(ShellError::GenericError { error: "grouper arguments result in colliding column names".into(), msg: "duplicate column names".into(), span: Some(conflicting_name.span.append(name.span)), help: Some( "instead of a cell-path, try using a closure or renaming columns".into(), ), inner: vec![ShellError::ColumnDefinedTwice { col_name: conflicting_name.item.clone(), first_use: conflicting_name.span, second_use: name.span, }], }); } name_set.push(name); } let column_names: Vec<String> = name_set .into_iter() .map(|elem| elem.item) .chain(["items".into()]) .collect(); Ok(column_names) } fn group_cell_path( column_name: &CellPath, values: Vec<Value>, config: &nu_protocol::Config, ) -> Result<IndexMap<String, Vec<Value>>, ShellError> { let mut groups = IndexMap::<_, Vec<_>>::new(); for value in values.into_iter() { let key = value.follow_cell_path(&column_name.members)?; if key.is_nothing() { continue; // likely the result of a failed optional access, ignore this value } let key = key.to_abbreviated_string(config); groups.entry(key).or_default().push(value); } Ok(groups) } fn group_closure( values: Vec<Value>, span: Span, closure: Closure, engine_state: &EngineState, stack: &mut Stack, ) -> Result<IndexMap<String, Vec<Value>>, ShellError> { let mut groups = IndexMap::<_, Vec<_>>::new(); let mut closure = ClosureEval::new(engine_state, stack, closure); let config = &stack.get_config(engine_state); for value in values { let key = closure .run_with_value(value.clone())? .into_value(span)? .to_abbreviated_string(config); groups.entry(key).or_default().push(value); } Ok(groups) } enum Grouper { CellPath { val: CellPath }, Closure { val: Box<Closure> }, } impl FromValue for Grouper { fn from_value(v: Value) -> Result<Self, ShellError> { match v { Value::CellPath { val, .. } => Ok(Grouper::CellPath { val }), Value::Closure { val, .. } => Ok(Grouper::Closure { val }), _ => Err(ShellError::TypeMismatch { err_message: "unsupported grouper type".to_string(), span: v.span(), }), } } } struct Grouped { groups: Tree, } enum Tree { Leaf(IndexMap<String, Vec<Value>>), Branch(IndexMap<String, Grouped>), } impl Grouped { fn empty(values: Vec<Value>, config: &nu_protocol::Config) -> Self { let mut groups = IndexMap::<_, Vec<_>>::new(); for value in values.into_iter() { let key = value.to_abbreviated_string(config); groups.entry(key).or_default().push(value); } Self { groups: Tree::Leaf(groups), } } fn new( grouper: Spanned<&Grouper>, values: Vec<Value>, config: &nu_protocol::Config, engine_state: &EngineState, stack: &mut Stack, ) -> Result<Self, ShellError> { let groups = match grouper.item { Grouper::CellPath { val } => group_cell_path(val, values, config)?, Grouper::Closure { val } => group_closure( values, grouper.span, Closure::clone(val), engine_state, stack, )?, }; Ok(Self { groups: Tree::Leaf(groups), }) } fn subgroup( &mut self, grouper: Spanned<&Grouper>, config: &nu_protocol::Config, engine_state: &EngineState, stack: &mut Stack, ) -> Result<(), ShellError> { let groups = match &mut self.groups { Tree::Leaf(groups) => std::mem::take(groups) .into_iter() .map(|(key, values)| -> Result<_, ShellError> { let leaf = Self::new(grouper, values, config, engine_state, stack)?; Ok((key, leaf)) }) .collect::<Result<IndexMap<_, _>, ShellError>>()?, Tree::Branch(nested_groups) => { let mut nested_groups = std::mem::take(nested_groups); for v in nested_groups.values_mut() { v.subgroup(grouper, config, engine_state, stack)?; } nested_groups } }; self.groups = Tree::Branch(groups); Ok(()) } fn into_table(self, column_names: &[String], head: Span) -> Value { self._into_table(head) .into_iter() .map(|row| { row.into_iter() .rev() .zip(column_names) .map(|(val, key)| (key.clone(), val)) .collect::<Record>() .into_value(head) }) .collect::<Vec<_>>() .into_value(head) } fn _into_table(self, head: Span) -> Vec<Vec<Value>> { match self.groups { Tree::Leaf(leaf) => leaf .into_iter() .map(|(group, values)| vec![(values.into_value(head)), (group.into_value(head))]) .collect::<Vec<Vec<Value>>>(), Tree::Branch(branch) => branch .into_iter() .flat_map(|(group, items)| { let mut inner = items._into_table(head); for row in &mut inner { row.push(group.clone().into_value(head)); } inner }) .collect(), } } fn into_record(self, head: Span) -> Value { match self.groups { Tree::Leaf(leaf) => Value::record( leaf.into_iter() .map(|(k, v)| (k, v.into_value(head))) .collect(), head, ), Tree::Branch(branch) => { let values = branch .into_iter() .map(|(k, v)| (k, v.into_record(head))) .collect(); Value::record(values, head) } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(GroupBy {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/sort_by.rs
crates/nu-command/src/filters/sort_by.rs
use nu_engine::{ClosureEval, command_prelude::*}; use crate::Comparator; #[derive(Clone)] pub struct SortBy; impl Command for SortBy { fn name(&self) -> &str { "sort-by" } fn signature(&self) -> nu_protocol::Signature { Signature::build("sort-by") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::record(), Type::table()), (Type::table(), Type::table()), ]) .rest( "comparator", SyntaxShape::OneOf(vec![ SyntaxShape::CellPath, SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), // key closure SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])), // custom closure ]), "The cell path(s) or closure(s) to compare elements by.", ) .switch("reverse", "Sort in reverse order", Some('r')) .switch( "ignore-case", "Sort string-based data case-insensitively", Some('i'), ) .switch( "natural", "Sort alphanumeric string-based data naturally (1, 9, 10, 99, 100, ...)", Some('n'), ) .switch( "custom", "Use closures to specify a custom sort order, rather than to compute a comparison key", Some('c'), ) .allow_variants_without_examples(true) .category(Category::Filters) } fn description(&self) -> &str { "Sort by the given cell path or closure." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Sort files by modified date", example: "ls | sort-by modified", result: None, }, Example { description: "Sort files by name (case-insensitive)", example: "ls | sort-by name --ignore-case", result: None, }, Example { description: "Sort a table by a column (reversed order)", example: "[[fruit count]; [apple 9] [pear 3] [orange 7]] | sort-by fruit --reverse", result: Some(Value::test_list(vec![ Value::test_record(record! { "fruit" => Value::test_string("pear"), "count" => Value::test_int(3), }), Value::test_record(record! { "fruit" => Value::test_string("orange"), "count" => Value::test_int(7), }), Value::test_record(record! { "fruit" => Value::test_string("apple"), "count" => Value::test_int(9), }), ])), }, Example { description: "Sort by a nested value", example: "[[name info]; [Cairo {founded: 969}] [Kyoto {founded: 794}]] | sort-by info.founded", result: Some(Value::test_list(vec![ Value::test_record(record! { "name" => Value::test_string("Kyoto"), "info" => Value::test_record( record! { "founded" => Value::test_int(794) }, )}), Value::test_record(record! { "name" => Value::test_string("Cairo"), "info" => Value::test_record( record! { "founded" => Value::test_int(969) }, )}), ])), }, Example { description: "Sort by the last value in a list", example: "[[2 50] [10 1]] | sort-by { last }", result: Some(Value::test_list(vec![ Value::test_list(vec![Value::test_int(10), Value::test_int(1)]), Value::test_list(vec![Value::test_int(2), Value::test_int(50)]), ])), }, Example { description: "Sort in a custom order", example: "[7 3 2 8 4] | sort-by -c {|a, b| $a < $b}", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(3), Value::test_int(4), Value::test_int(7), Value::test_int(8), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let comparator_vals: Vec<Value> = call.rest(engine_state, stack, 0)?; let reverse = call.has_flag(engine_state, stack, "reverse")?; let insensitive = call.has_flag(engine_state, stack, "ignore-case")?; let natural = call.has_flag(engine_state, stack, "natural")?; let custom = call.has_flag(engine_state, stack, "custom")?; let metadata = input.metadata(); let mut vec: Vec<_> = input.into_iter_strict(head)?.collect(); if comparator_vals.is_empty() { return Err(ShellError::MissingParameter { param_name: "comparator".into(), span: head, }); } let comparators = comparator_vals .into_iter() .map(|val| match val { Value::CellPath { val, .. } => Ok(Comparator::CellPath(val)), Value::Closure { val, .. } => { let closure_eval = ClosureEval::new(engine_state, stack, *val); if custom { Ok(Comparator::CustomClosure(closure_eval)) } else { Ok(Comparator::KeyClosure(closure_eval)) } } _ => Err(ShellError::TypeMismatch { err_message: "Cannot sort using a value which is not a cell path or closure" .into(), span: val.span(), }), }) .collect::<Result<_, _>>()?; crate::sort_by(&mut vec, comparators, head, insensitive, natural)?; if reverse { vec.reverse() } let val = Value::list(vec, head); Ok(val.into_pipeline_data_with_metadata(metadata)) } } #[cfg(test)] mod test { use crate::{Last, test_examples_with_commands}; use super::*; #[test] fn test_examples() { test_examples_with_commands(SortBy {}, &[&Last]); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/length.rs
crates/nu-command/src/filters/length.rs
use std::io::Read; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Length; impl Command for Length { fn name(&self) -> &str { "length" } fn description(&self) -> &str { "Count the number of items in an input list, rows in a table, or bytes in binary data." } fn signature(&self) -> nu_protocol::Signature { Signature::build("length") .input_output_types(vec![ (Type::List(Box::new(Type::Any)), Type::Int), (Type::Binary, Type::Int), (Type::Nothing, Type::Int), ]) .category(Category::Filters) } fn search_terms(&self) -> Vec<&str> { vec!["count", "size", "wc"] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { length_row(call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Count the number of items in a list", example: "[1 2 3 4 5] | length", result: Some(Value::test_int(5)), }, Example { description: "Count the number of rows in a table", example: "[{a:1 b:2}, {a:2 b:3}] | length", result: Some(Value::test_int(2)), }, Example { description: "Count the number of bytes in binary data", example: "0x[01 02] | length", result: Some(Value::test_int(2)), }, Example { description: "Count the length a null value", example: "null | length", result: Some(Value::test_int(0)), }, ] } } fn length_row(call: &Call, input: PipelineData) -> Result<PipelineData, ShellError> { let span = input.span().unwrap_or(call.head); match input { PipelineData::Empty | PipelineData::Value(Value::Nothing { .. }, ..) => { Ok(Value::int(0, call.head).into_pipeline_data()) } PipelineData::Value(Value::Binary { val, .. }, ..) => { Ok(Value::int(val.len() as i64, call.head).into_pipeline_data()) } PipelineData::Value(Value::List { vals, .. }, ..) => { Ok(Value::int(vals.len() as i64, call.head).into_pipeline_data()) } PipelineData::ListStream(stream, ..) => { Ok(Value::int(stream.into_iter().count() as i64, call.head).into_pipeline_data()) } PipelineData::ByteStream(stream, ..) if stream.type_().is_binary_coercible() => { Ok(Value::int( match stream.reader() { Some(r) => r.bytes().count() as i64, None => 0, }, call.head, ) .into_pipeline_data()) } _ => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, table, binary, and nothing".into(), wrong_type: input.get_type().to_string(), dst_span: call.head, src_span: span, }), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Length {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/zip.rs
crates/nu-command/src/filters/zip.rs
use nu_engine::{ClosureEvalOnce, command_prelude::*}; #[derive(Clone)] pub struct Zip; impl Command for Zip { fn name(&self) -> &str { "zip" } fn description(&self) -> &str { "Combine a stream with the input." } fn signature(&self) -> nu_protocol::Signature { Signature::build("zip") .input_output_types(vec![ ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::List(Box::new(Type::Any)))), ), ( Type::Range, Type::List(Box::new(Type::List(Box::new(Type::Any)))), ), ]) .required( "other", SyntaxShape::OneOf(vec![SyntaxShape::Any, SyntaxShape::Closure(Some(vec![]))]), "The other input, or closure returning a stream.", ) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { let test_row_1 = Value::list( vec![Value::test_int(1), Value::test_int(4)], Span::test_data(), ); let test_row_2 = Value::list( vec![Value::test_int(2), Value::test_int(5)], Span::test_data(), ); let test_row_3 = Value::list( vec![Value::test_int(3), Value::test_int(6)], Span::test_data(), ); vec![ Example { example: "[1 2] | zip [3 4]", description: "Zip two lists", result: Some(Value::list( vec![ Value::list( vec![Value::test_int(1), Value::test_int(3)], Span::test_data(), ), Value::list( vec![Value::test_int(2), Value::test_int(4)], Span::test_data(), ), ], Span::test_data(), )), }, Example { example: "1..3 | zip 4..6", description: "Zip two ranges", result: Some(Value::list( vec![test_row_1.clone(), test_row_2.clone(), test_row_3.clone()], Span::test_data(), )), }, Example { example: "seq 1 3 | zip { seq 4 600000000 }", description: "Zip two streams", result: Some(Value::list( vec![test_row_1, test_row_2, test_row_3], Span::test_data(), )), }, Example { example: "glob *.ogg | zip ['bang.ogg', 'fanfare.ogg', 'laser.ogg'] | each {|| mv $in.0 $in.1 }", description: "Rename .ogg files to match an existing list of filenames", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let other = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); let other = if let Value::Closure { val, .. } = other { // If a closure was provided, evaluate it and consume its stream output ClosureEvalOnce::new(engine_state, stack, *val).run_with_input(PipelineData::empty())? } else { other.into_pipeline_data() }; Ok(input .into_iter() .zip(other) .map(move |(x, y)| Value::list(vec![x, y], head)) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Zip {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/every.rs
crates/nu-command/src/filters/every.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Every; impl Command for Every { fn name(&self) -> &str { "every" } fn signature(&self) -> Signature { Signature::build("every") .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .required( "stride", SyntaxShape::Int, "How many rows to skip between (and including) each row returned.", ) .switch( "skip", "skip the rows that would be returned, instead of selecting them", Some('s'), ) .category(Category::Filters) } fn description(&self) -> &str { "Show (or skip) every n-th row, starting from the first one." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[1 2 3 4 5] | every 2", description: "Get every second row", result: Some(Value::list( vec![Value::test_int(1), Value::test_int(3), Value::test_int(5)], Span::test_data(), )), }, Example { example: "[1 2 3 4 5] | every 2 --skip", description: "Skip every second row", result: Some(Value::list( vec![Value::test_int(2), Value::test_int(4)], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let stride = match call.req::<usize>(engine_state, stack, 0)? { 0 => 1, stride => stride, }; let skip = call.has_flag(engine_state, stack, "skip")?; let metadata = input.metadata(); Ok(input .into_iter() .enumerate() .filter_map(move |(i, value)| { if (i % stride != 0) == skip { Some(value) } else { None } }) .into_pipeline_data_with_metadata(call.head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Every {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/shuffle.rs
crates/nu-command/src/filters/shuffle.rs
use nu_engine::command_prelude::*; use rand::{prelude::SliceRandom, rng}; #[derive(Clone)] pub struct Shuffle; impl Command for Shuffle { fn name(&self) -> &str { "shuffle" } fn signature(&self) -> nu_protocol::Signature { Signature::build("shuffle") .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .category(Category::Filters) } fn description(&self) -> &str { "Shuffle rows randomly." } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input.metadata(); let mut values = input.into_iter_strict(call.head)?.collect::<Vec<_>>(); values.shuffle(&mut rng()); let iter = values.into_iter(); Ok(iter.into_pipeline_data_with_metadata( call.head, engine_state.signals().clone(), metadata, )) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Shuffle rows randomly (execute it several times and see the difference)", example: r#"[[version patch]; ['1.0.0' false] ['3.0.1' true] ['2.0.0' false]] | shuffle"#, result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/wrap.rs
crates/nu-command/src/filters/wrap.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Wrap; impl Command for Wrap { fn name(&self) -> &str { "wrap" } fn description(&self) -> &str { "Wrap the value into a column." } fn signature(&self) -> nu_protocol::Signature { Signature::build("wrap") .input_output_types(vec![ (Type::List(Box::new(Type::Any)), Type::table()), (Type::Range, Type::table()), (Type::Any, Type::record()), ]) .required("name", SyntaxShape::String, "The name of the column.") .allow_variants_without_examples(true) .category(Category::Filters) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; let name: String = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(Value::Range { .. }, ..) | PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream { .. } => Ok(input .into_iter() .map(move |x| Value::record(record! { name.clone() => x }, span)) .into_pipeline_data_with_metadata(span, engine_state.signals().clone(), metadata)), PipelineData::ByteStream(stream, ..) => Ok(Value::record( record! { name => stream.into_value()? }, span, ) .into_pipeline_data_with_metadata(metadata)), PipelineData::Value(input, ..) => Ok(Value::record(record! { name => input }, span) .into_pipeline_data_with_metadata(metadata)), } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Wrap a list into a table with a given column name", example: "[ Pachisi Mahjong Catan Carcassonne ] | wrap game", result: Some(Value::test_list(vec![ Value::test_record(record! { "game" => Value::test_string("Pachisi"), }), Value::test_record(record! { "game" => Value::test_string("Mahjong"), }), Value::test_record(record! { "game" => Value::test_string("Catan"), }), Value::test_record(record! { "game" => Value::test_string("Carcassonne"), }), ])), }, Example { description: "Wrap a range into a table with a given column name", example: "4..6 | wrap num", result: Some(Value::test_list(vec![ Value::test_record(record! { "num" => Value::test_int(4), }), Value::test_record(record! { "num" => Value::test_int(5), }), Value::test_record(record! { "num" => Value::test_int(6), }), ])), }, ] } } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Wrap; use crate::test_examples; test_examples(Wrap {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/get.rs
crates/nu-command/src/filters/get.rs
use std::borrow::Cow; use nu_engine::command_prelude::*; use nu_protocol::{DeprecationEntry, DeprecationType, ReportMode, Signals, ast::PathMember}; #[derive(Clone)] pub struct Get; impl Command for Get { fn name(&self) -> &str { "get" } fn description(&self) -> &str { "Extract data using a cell path." } fn extra_description(&self) -> &str { r#"This is equivalent to using the cell path access syntax: `$env.OS` is the same as `$env | get OS`. If multiple cell paths are given, this will produce a list of values."# } fn signature(&self) -> nu_protocol::Signature { Signature::build("get") .input_output_types(vec![ ( // TODO: This is too permissive; if we could express this // using a type parameter it would be List<T> -> T. Type::List(Box::new(Type::Any)), Type::Any, ), (Type::table(), Type::Any), (Type::record(), Type::Any), (Type::Nothing, Type::Nothing), ]) .required( "cell_path", SyntaxShape::CellPath, "The cell path to the data.", ) .rest("rest", SyntaxShape::CellPath, "Additional cell paths.") .switch( "optional", "make all cell path members optional (returns `null` for missing values)", Some('o'), ) .switch( "ignore-case", "make all cell path members case insensitive", None, ) .switch( "ignore-errors", "ignore missing data (make all cell path members optional) (deprecated)", Some('i'), ) .switch( "sensitive", "get path in a case sensitive manner (deprecated)", Some('s'), ) .allow_variants_without_examples(true) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Get an item from a list", example: "[0 1 2] | get 1", result: Some(Value::test_int(1)), }, Example { description: "Get a column from a table", example: "[{A: A0}] | get A", result: Some(Value::list( vec![Value::test_string("A0")], Span::test_data(), )), }, Example { description: "Get a column from a table where some rows don't have that column, using optional cell-path syntax", example: "[{A: A0, B: B0}, {B: B1}, {A: A2, B: B2}] | get A?", result: Some(Value::list( vec![ Value::test_string("A0"), Value::test_nothing(), Value::test_string("A2"), ], Span::test_data(), )), }, Example { description: "Get a column from a table where some rows don't have that column, using the optional flag", example: "[{A: A0, B: B0}, {B: B1}, {A: A2, B: B2}] | get -o A", result: Some(Value::list( vec![ Value::test_string("A0"), Value::test_nothing(), Value::test_string("A2"), ], Span::test_data(), )), }, Example { description: "Get a cell from a table", example: "[{A: A0}] | get 0.A", result: Some(Value::test_string("A0")), }, Example { description: "Extract the name of the 3rd record in a list (same as `ls | $in.name.2`)", example: "ls | get name.2", result: None, }, Example { description: "Extract the name of the 3rd record in a list", example: "ls | get 2.name", result: None, }, Example { description: "Getting environment variables in a case insensitive way, using case insensitive cell-path syntax", example: "$env | get home! path!", result: None, }, Example { description: "Getting environment variables in a case insensitive way, using the '--ignore-case' flag", example: "$env | get --ignore-case home path", result: None, }, Example { description: "Getting Path in a case sensitive way, won't work for 'PATH'", example: "$env | get Path", result: None, }, ] } fn is_const(&self) -> bool { true } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_path: CellPath = call.req_const(working_set, 0)?; let rest: Vec<CellPath> = call.rest_const(working_set, 1)?; let optional = call.has_flag_const(working_set, "optional")? || call.has_flag_const(working_set, "ignore-errors")?; let ignore_case = call.has_flag_const(working_set, "ignore-case")?; let metadata = input.metadata(); action( input, cell_path, rest, optional, ignore_case, working_set.permanent().signals().clone(), call.head, ) .map(|x| x.set_metadata(metadata)) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_path: CellPath = call.req(engine_state, stack, 0)?; let rest: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let optional = call.has_flag(engine_state, stack, "optional")? || call.has_flag(engine_state, stack, "ignore-errors")?; let ignore_case = call.has_flag(engine_state, stack, "ignore-case")?; let metadata = input.metadata(); action( input, cell_path, rest, optional, ignore_case, engine_state.signals().clone(), call.head, ) .map(|x| x.set_metadata(metadata)) } fn deprecation_info(&self) -> Vec<DeprecationEntry> { vec![ DeprecationEntry { ty: DeprecationType::Flag("sensitive".into()), report_mode: ReportMode::FirstUse, since: Some("0.105.0".into()), expected_removal: None, help: Some("Cell-paths are now case-sensitive by default.\nTo access fields case-insensitively, add `!` after the relevant path member.".into()) }, DeprecationEntry { ty: DeprecationType::Flag("ignore-errors".into()), report_mode: ReportMode::FirstUse, since: Some("0.106.0".into()), expected_removal: None, help: Some("This flag has been renamed to `--optional (-o)` to better reflect its behavior.".into()) } ] } } fn action( input: PipelineData, mut cell_path: CellPath, mut rest: Vec<CellPath>, optional: bool, ignore_case: bool, signals: Signals, span: Span, ) -> Result<PipelineData, ShellError> { if optional { cell_path.make_optional(); for path in &mut rest { path.make_optional(); } } if ignore_case { cell_path.make_insensitive(); for path in &mut rest { path.make_insensitive(); } } if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: span }); } if rest.is_empty() { follow_cell_path_into_stream(input, signals, cell_path.members, span) } else { let mut output = vec![]; let paths = std::iter::once(cell_path).chain(rest); let input = input.into_value(span)?; for path in paths { output.push(input.follow_cell_path(&path.members)?.into_owned()); } Ok(output.into_iter().into_pipeline_data(span, signals)) } } // the PipelineData.follow_cell_path function, when given a // stream, collects it into a vec before doing its job // // this is fine, since it returns a Result<Value ShellError>, // but if we want to follow a PipelineData into a cell path and // return another PipelineData, then we have to take care to // make sure it streams pub fn follow_cell_path_into_stream( data: PipelineData, signals: Signals, cell_path: Vec<PathMember>, head: Span, ) -> Result<PipelineData, ShellError> { // when given an integer/indexing, we fallback to // the default nushell indexing behaviour let has_int_member = cell_path .iter() .any(|it| matches!(it, PathMember::Int { .. })); match data { PipelineData::ListStream(stream, ..) if !has_int_member => { let result = stream .into_iter() .map(move |value| { let span = value.span(); value .follow_cell_path(&cell_path) .map(Cow::into_owned) .unwrap_or_else(|error| Value::error(error, span)) }) .into_pipeline_data(head, signals); Ok(result) } _ => data .follow_cell_path(&cell_path, head) .map(|x| x.into_pipeline_data()), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Get) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/take/take_until.rs
crates/nu-command/src/filters/take/take_until.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct TakeUntil; impl Command for TakeUntil { fn name(&self) -> &str { "take until" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), )]) .required( "predicate", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The predicate that element(s) must not match.", ) .category(Category::Filters) } fn description(&self) -> &str { "Take elements of the input until a predicate is true." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Take until the element is positive", example: "[-1 -2 9 1] | take until {|x| $x > 0 }", result: Some(Value::test_list(vec![ Value::test_int(-1), Value::test_int(-2), ])), }, Example { description: "Take until the element is positive using stored condition", example: "let cond = {|x| $x > 0 }; [-1 -2 9 1] | take until $cond", result: Some(Value::test_list(vec![ Value::test_int(-1), Value::test_int(-2), ])), }, Example { description: "Take until the field value is positive", example: "[{a: -1} {a: -2} {a: 9} {a: 1}] | take until {|x| $x.a > 0 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(-1), }), Value::test_record(record! { "a" => Value::test_int(-2), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let mut closure = ClosureEval::new(engine_state, stack, closure); let metadata = input.metadata(); Ok(input .into_iter_strict(head)? .take_while(move |value| { closure .run_with_value(value.clone()) .and_then(|data| data.into_value(head)) .map(|cond| cond.is_false()) .unwrap_or(false) }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod tests { use crate::TakeUntil; #[test] fn test_examples() { use crate::test_examples; test_examples(TakeUntil) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/take/take_.rs
crates/nu-command/src/filters/take/take_.rs
use nu_engine::command_prelude::*; use nu_protocol::Signals; #[derive(Clone)] pub struct Take; impl Command for Take { fn name(&self) -> &str { "take" } fn signature(&self) -> Signature { Signature::build("take") .input_output_types(vec![ (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), (Type::Binary, Type::Binary), (Type::Range, Type::List(Box::new(Type::Number))), ]) .required( "n", SyntaxShape::Int, "Starting from the front, the number of elements to return.", ) .category(Category::Filters) } fn description(&self) -> &str { "Take only the first n elements of a list, or the first n bytes of a binary value." } fn search_terms(&self) -> Vec<&str> { vec!["first", "slice", "head"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let rows_desired: usize = call.req(engine_state, stack, 0)?; let metadata = input.metadata().map(|m| m.with_content_type(None)); match input { PipelineData::Value(val, _) => { let span = val.span(); match val { Value::List { vals, .. } => Ok(vals .into_iter() .take(rows_desired) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )), Value::Binary { val, .. } => { let slice: Vec<u8> = val.into_iter().take(rows_desired).collect(); Ok(PipelineData::value(Value::binary(slice, span), metadata)) } Value::Range { val, .. } => Ok(val .into_range_iter(span, Signals::empty()) .take(rows_desired) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )), // Propagate errors by explicitly matching them before the final case. Value::Error { error, .. } => Err(*error), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: other.get_type().to_string(), dst_span: head, src_span: other.span(), }), } } PipelineData::ListStream(stream, metadata) => Ok(PipelineData::list_stream( stream.modify(|iter| iter.take(rows_desired)), metadata, )), PipelineData::ByteStream(stream, metadata) => { if stream.type_().is_binary_coercible() { let span = stream.span(); Ok(PipelineData::byte_stream( stream.take(span, rows_desired as u64)?, // first 5 bytes of an image/png stream are not image/png themselves metadata.map(|m| m.with_content_type(None)), )) } else { Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: stream.type_().describe().into(), dst_span: head, src_span: stream.span(), }) } } PipelineData::Empty => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: "null".into(), dst_span: head, src_span: head, }), } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return the first item of a list/table", example: "[1 2 3] | take 1", result: Some(Value::test_list(vec![Value::test_int(1)])), }, Example { description: "Return the first 2 items of a list/table", example: "[1 2 3] | take 2", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), ])), }, Example { description: "Return the first two rows of a table", example: "[[editions]; [2015] [2018] [2021]] | take 2", result: Some(Value::test_list(vec![ Value::test_record(record! { "editions" => Value::test_int(2015), }), Value::test_record(record! { "editions" => Value::test_int(2018), }), ])), }, Example { description: "Return the first 2 bytes of a binary value", example: "0x[01 23 45] | take 2", result: Some(Value::test_binary(vec![0x01, 0x23])), }, Example { description: "Return the first 3 elements of a range", example: "1..10 | take 3", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), ])), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Take {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/take/mod.rs
crates/nu-command/src/filters/take/mod.rs
mod take_; mod take_until; mod take_while; pub use take_::Take; pub use take_until::TakeUntil; pub use take_while::TakeWhile;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/take/take_while.rs
crates/nu-command/src/filters/take/take_while.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct TakeWhile; impl Command for TakeWhile { fn name(&self) -> &str { "take while" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .required( "predicate", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The predicate that element(s) must match.", ) .category(Category::Filters) } fn description(&self) -> &str { "Take elements of the input while a predicate is true." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Take while the element is negative", example: "[-1 -2 9 1] | take while {|x| $x < 0 }", result: Some(Value::test_list(vec![ Value::test_int(-1), Value::test_int(-2), ])), }, Example { description: "Take while the element is negative using stored condition", example: "let cond = {|x| $x < 0 }; [-1 -2 9 1] | take while $cond", result: Some(Value::test_list(vec![ Value::test_int(-1), Value::test_int(-2), ])), }, Example { description: "Take while the field value is negative", example: "[{a: -1} {a: -2} {a: 9} {a: 1}] | take while {|x| $x.a < 0 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(-1), }), Value::test_record(record! { "a" => Value::test_int(-2), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let mut closure = ClosureEval::new(engine_state, stack, closure); let metadata = input.metadata(); Ok(input .into_iter_strict(head)? .take_while(move |value| { closure .run_with_value(value.clone()) .and_then(|data| data.into_value(head)) .map(|cond| cond.is_true()) .unwrap_or(false) }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod tests { use crate::TakeWhile; #[test] fn test_examples() { use crate::test_examples; test_examples(TakeWhile) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/drop/column.rs
crates/nu-command/src/filters/drop/column.rs
use nu_engine::command_prelude::*; use std::collections::HashSet; #[derive(Clone)] pub struct DropColumn; impl Command for DropColumn { fn name(&self) -> &str { "drop column" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .optional( "columns", SyntaxShape::Int, "Starting from the end, the number of columns to remove.", ) .category(Category::Filters) } fn description(&self) -> &str { "Remove N columns at the right-hand end of the input table. To remove columns by name, use `reject`." } fn search_terms(&self) -> Vec<&str> { vec!["delete", "remove"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { // the number of columns to drop let columns: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?; let columns = if let Some(columns) = columns { if columns.item < 0 { return Err(ShellError::NeedsPositiveValue { span: columns.span }); } else { columns.item as usize } } else { 1 }; drop_cols(engine_state, input, call.head, columns) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Remove the last column of a table", example: "[[lib, extension]; [nu-lib, rs] [nu-core, rb]] | drop column", result: Some(Value::test_list(vec![ Value::test_record(record! { "lib" => Value::test_string("nu-lib") }), Value::test_record(record! { "lib" => Value::test_string("nu-core") }), ])), }, Example { description: "Remove the last column of a record", example: "{lib: nu-lib, extension: rs} | drop column", result: Some(Value::test_record( record! { "lib" => Value::test_string("nu-lib") }, )), }, ] } } fn drop_cols( engine_state: &EngineState, input: PipelineData, head: Span, columns: usize, ) -> Result<PipelineData, ShellError> { // For simplicity and performance, we use the first row's columns // as the columns for the whole table, and assume that later rows/records // have these same columns. However, this can give weird results like: // `[{a: 1}, {b: 2}] | drop column` // This will drop the column "a" instead of "b" even though column "b" // is displayed farther to the right. let metadata = input.metadata(); match input { PipelineData::ListStream(stream, ..) => { let mut stream = stream.into_iter(); if let Some(mut first) = stream.next() { let drop_cols = drop_cols_set(&mut first, head, columns)?; Ok(std::iter::once(first) .chain(stream.map(move |mut v| { match drop_record_cols(&mut v, head, &drop_cols) { Ok(()) => v, Err(e) => Value::error(e, head), } })) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata, )) } else { Ok(PipelineData::empty()) } } PipelineData::Value(mut v, ..) => { let span = v.span(); match v { Value::List { mut vals, .. } => { if let Some((first, rest)) = vals.split_first_mut() { let drop_cols = drop_cols_set(first, head, columns)?; for val in rest { drop_record_cols(val, head, &drop_cols)? } } Ok(Value::list(vals, span).into_pipeline_data_with_metadata(metadata)) } Value::Record { val: ref mut record, .. } => { let len = record.len().saturating_sub(columns); record.to_mut().truncate(len); Ok(v.into_pipeline_data_with_metadata(metadata)) } // Propagate errors Value::Error { error, .. } => Err(*error), val => Err(unsupported_value_error(&val, head)), } } PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::ByteStream(stream, ..) => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "table or record".into(), wrong_type: stream.type_().describe().into(), dst_span: head, src_span: stream.span(), }), } } fn drop_cols_set(val: &mut Value, head: Span, drop: usize) -> Result<HashSet<String>, ShellError> { if let Value::Record { val: record, .. } = val { let len = record.len().saturating_sub(drop); Ok(record.to_mut().drain(len..).map(|(col, _)| col).collect()) } else { Err(unsupported_value_error(val, head)) } } fn drop_record_cols( val: &mut Value, head: Span, drop_cols: &HashSet<String>, ) -> Result<(), ShellError> { if let Value::Record { val, .. } = val { val.to_mut().retain(|col, _| !drop_cols.contains(col)); Ok(()) } else { Err(unsupported_value_error(val, head)) } } fn unsupported_value_error(val: &Value, head: Span) -> ShellError { ShellError::OnlySupportsThisInputType { exp_input_type: "table or record".into(), wrong_type: val.get_type().to_string(), dst_span: head, src_span: val.span(), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { crate::test_examples(DropColumn) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/drop/nth.rs
crates/nu-command/src/filters/drop/nth.rs
use nu_engine::command_prelude::*; use nu_protocol::{PipelineIterator, Range}; use std::collections::VecDeque; use std::ops::Bound; #[derive(Clone)] pub struct DropNth; impl Command for DropNth { fn name(&self) -> &str { "drop nth" } fn signature(&self) -> Signature { Signature::build("drop nth") .input_output_types(vec![ (Type::Range, Type::list(Type::Number)), (Type::list(Type::Any), Type::list(Type::Any)), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::Any, "The row numbers or ranges to drop.", ) .category(Category::Filters) } fn description(&self) -> &str { "Drop the selected rows." } fn search_terms(&self) -> Vec<&str> { vec!["delete", "remove", "index"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[sam,sarah,2,3,4,5] | drop nth 0 1 2", description: "Drop the first, second, and third row", result: Some(Value::list( vec![Value::test_int(3), Value::test_int(4), Value::test_int(5)], Span::test_data(), )), }, Example { example: "[0,1,2,3,4,5] | drop nth 0 1 2", description: "Drop the first, second, and third row", result: Some(Value::list( vec![Value::test_int(3), Value::test_int(4), Value::test_int(5)], Span::test_data(), )), }, Example { example: "[0,1,2,3,4,5] | drop nth 0 2 4", description: "Drop rows 0 2 4", result: Some(Value::list( vec![Value::test_int(1), Value::test_int(3), Value::test_int(5)], Span::test_data(), )), }, Example { example: "[0,1,2,3,4,5] | drop nth 2 0 4", description: "Drop rows 2 0 4", result: Some(Value::list( vec![Value::test_int(1), Value::test_int(3), Value::test_int(5)], Span::test_data(), )), }, Example { description: "Drop range rows from second to fourth", example: "[first second third fourth fifth] | drop nth (1..3)", result: Some(Value::list( vec![Value::test_string("first"), Value::test_string("fifth")], Span::test_data(), )), }, Example { example: "[0,1,2,3,4,5] | drop nth 1..", description: "Drop all rows except first row", result: Some(Value::list(vec![Value::test_int(0)], Span::test_data())), }, Example { example: "[0,1,2,3,4,5] | drop nth 3..", description: "Drop rows 3,4,5", result: Some(Value::list( vec![Value::test_int(0), Value::test_int(1), Value::test_int(2)], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let metadata = input.metadata(); let args: Vec<Value> = call.rest(engine_state, stack, 0)?; if args.is_empty() { return Ok(input); } let (rows_to_drop, min_unbounded_start) = get_rows_to_drop(&args, head)?; let input = if let Some(cutoff) = min_unbounded_start { input .into_iter() .take(cutoff) .into_pipeline_data_with_metadata( head, engine_state.signals().clone(), metadata.clone(), ) } else { input }; Ok(DropNthIterator { input: input.into_iter(), rows: rows_to_drop, current: 0, } .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } fn get_rows_to_drop( args: &[Value], head: Span, ) -> Result<(VecDeque<usize>, Option<usize>), ShellError> { let mut rows_to_drop = Vec::new(); let mut min_unbounded_start: Option<usize> = None; for value in args { if let Ok(i) = value.as_int() { if i < 0 { return Err(ShellError::UnsupportedInput { msg: "drop nth accepts only positive ints".into(), input: "value originates from here".into(), msg_span: head, input_span: value.span(), }); } rows_to_drop.push(i as usize); } else if let Ok(range) = value.as_range() { match range { Range::IntRange(range) => { let start = range.start(); if start < 0 { return Err(ShellError::UnsupportedInput { msg: "drop nth accepts only positive ints".into(), input: "value originates from here".into(), msg_span: head, input_span: value.span(), }); } match range.end() { Bound::Included(end) => { if end < start { return Err(ShellError::UnsupportedInput { msg: "The upper bound must be greater than or equal to the lower bound".into(), input: "value originates from here".into(), msg_span: head, input_span: value.span(), }); } rows_to_drop.extend((start as usize)..=(end as usize)); } Bound::Excluded(end) => { if end <= start { return Err(ShellError::UnsupportedInput { msg: "The upper bound must be greater than the lower bound" .into(), input: "value originates from here".into(), msg_span: head, input_span: value.span(), }); } rows_to_drop.extend((start as usize)..(end as usize)); } Bound::Unbounded => { let start_usize = start as usize; min_unbounded_start = Some( min_unbounded_start.map_or(start_usize, |s| s.min(start_usize)), ); } } } Range::FloatRange(_) => { return Err(ShellError::UnsupportedInput { msg: "float range not supported".into(), input: "value originates from here".into(), msg_span: head, input_span: value.span(), }); } } } else { return Err(ShellError::TypeMismatch { err_message: "Expected int or range".into(), span: value.span(), }); } } rows_to_drop.sort_unstable(); rows_to_drop.dedup(); Ok((VecDeque::from(rows_to_drop), min_unbounded_start)) } struct DropNthIterator { input: PipelineIterator, rows: VecDeque<usize>, current: usize, } impl Iterator for DropNthIterator { type Item = Value; fn next(&mut self) -> Option<Self::Item> { loop { if let Some(row) = self.rows.front() { if self.current == *row { self.rows.pop_front(); self.current += 1; let _ = self.input.next(); continue; } else { self.current += 1; return self.input.next(); } } else { return self.input.next(); } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(DropNth {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/drop/mod.rs
crates/nu-command/src/filters/drop/mod.rs
pub mod column; pub mod drop_; pub mod nth; pub use column::DropColumn; pub use drop_::Drop; pub use nth::DropNth;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/drop/drop_.rs
crates/nu-command/src/filters/drop/drop_.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Drop; impl Command for Drop { fn name(&self) -> &str { "drop" } fn signature(&self) -> Signature { Signature::build("drop") .input_output_types(vec![ (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .optional("rows", SyntaxShape::Int, "The number of items to remove.") .category(Category::Filters) } fn description(&self) -> &str { "Remove items/rows from the end of the input list/table. Counterpart of `skip`. Opposite of `last`." } fn search_terms(&self) -> Vec<&str> { vec!["delete", "remove"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[0,1,2,3] | drop", description: "Remove the last item of a list", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), ])), }, Example { example: "[0,1,2,3] | drop 0", description: "Remove zero item of a list", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), Value::test_int(2), Value::test_int(3), ])), }, Example { example: "[0,1,2,3] | drop 2", description: "Remove the last two items of a list", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(1), ])), }, Example { description: "Remove the last row in a table", example: "[[a, b]; [1, 2] [3, 4]] | drop 1", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), })])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let metadata = input.metadata(); let rows: Option<Spanned<i64>> = call.opt(engine_state, stack, 0)?; let mut values = input.into_iter_strict(head)?.collect::<Vec<_>>(); let rows_to_drop = if let Some(rows) = rows { if rows.item < 0 { return Err(ShellError::NeedsPositiveValue { span: rows.span }); } else { rows.item as usize } } else { 1 }; values.truncate(values.len().saturating_sub(rows_to_drop)); Ok(Value::list(values, head).into_pipeline_data_with_metadata(metadata)) } } #[cfg(test)] mod test { use crate::Drop; #[test] fn test_examples() { use crate::test_examples; test_examples(Drop {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/skip/skip_.rs
crates/nu-command/src/filters/skip/skip_.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Skip; impl Command for Skip { fn name(&self) -> &str { "skip" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::table(), Type::table()), (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .optional("n", SyntaxShape::Int, "The number of elements to skip.") .category(Category::Filters) } fn description(&self) -> &str { "Skip the first several rows of the input. Counterpart of `drop`. Opposite of `first`." } fn extra_description(&self) -> &str { r#"To skip specific numbered rows, try `drop nth`. To skip specific named columns, try `reject`."# } fn search_terms(&self) -> Vec<&str> { vec!["ignore", "remove", "last", "slice", "tail"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Skip the first value of a list", example: "[2 4 6 8] | skip 1", result: Some(Value::test_list(vec![ Value::test_int(4), Value::test_int(6), Value::test_int(8), ])), }, Example { description: "Skip two rows of a table", example: "[[editions]; [2015] [2018] [2021]] | skip 2", result: Some(Value::test_list(vec![Value::test_record(record! { "editions" => Value::test_int(2021), })])), }, Example { description: "Skip 2 bytes of a binary value", example: "0x[01 23 45 67] | skip 2", result: Some(Value::test_binary(vec![0x45, 0x67])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let n: Option<Value> = call.opt(engine_state, stack, 0)?; let metadata = input.metadata().map(|m| m.with_content_type(None)); let n: usize = match n { Some(v) => { let span = v.span(); match v { Value::Int { val, .. } => { val.try_into().map_err(|err| ShellError::TypeMismatch { err_message: format!("Could not convert {val} to unsigned int: {err}"), span, })? } _ => { return Err(ShellError::TypeMismatch { err_message: "expected int".into(), span, }); } } } None => 1, }; let input_span = input.span().unwrap_or(call.head); match input { PipelineData::ByteStream(stream, metadata) => { if stream.type_().is_binary_coercible() { let span = stream.span(); Ok(PipelineData::byte_stream( stream.skip(span, n as u64)?, // last 5 bytes of an image/png stream are not image/png themselves metadata.map(|m| m.with_content_type(None)), )) } else { Err(ShellError::OnlySupportsThisInputType { exp_input_type: "list, binary or range".into(), wrong_type: stream.type_().describe().into(), dst_span: call.head, src_span: stream.span(), }) } } PipelineData::Value(Value::Binary { val, .. }, metadata) => { let bytes = val.into_iter().skip(n).collect::<Vec<_>>(); let metadata = metadata.map(|m| m.with_content_type(None)); Ok(Value::binary(bytes, input_span).into_pipeline_data_with_metadata(metadata)) } _ => Ok(input .into_iter_strict(call.head)? .skip(n) .into_pipeline_data_with_metadata( input_span, engine_state.signals().clone(), metadata, )), } } } #[cfg(test)] mod tests { use crate::Skip; #[test] fn test_examples() { use crate::test_examples; test_examples(Skip {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/skip/skip_while.rs
crates/nu-command/src/filters/skip/skip_while.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct SkipWhile; impl Command for SkipWhile { fn name(&self) -> &str { "skip while" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .required( "predicate", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The predicate that skipped element must match.", ) .category(Category::Filters) } fn description(&self) -> &str { "Skip elements of the input while a predicate is true." } fn search_terms(&self) -> Vec<&str> { vec!["ignore"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Skip while the element is negative", example: "[-2 0 2 -1] | skip while {|x| $x < 0 }", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(2), Value::test_int(-1), ])), }, Example { description: "Skip while the element is negative using stored condition", example: "let cond = {|x| $x < 0 }; [-2 0 2 -1] | skip while $cond", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(2), Value::test_int(-1), ])), }, Example { description: "Skip while the field value is negative", example: "[{a: -2} {a: 0} {a: 2} {a: -1}] | skip while {|x| $x.a < 0 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(0), }), Value::test_record(record! { "a" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_int(-1), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let mut closure = ClosureEval::new(engine_state, stack, closure); let metadata = input.metadata(); Ok(input .into_iter_strict(head)? .skip_while(move |value| { closure .run_with_value(value.clone()) .and_then(|data| data.into_value(head)) .map(|cond| cond.is_true()) .unwrap_or(false) }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod tests { use crate::SkipWhile; #[test] fn test_examples() { use crate::test_examples; test_examples(SkipWhile) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/skip/mod.rs
crates/nu-command/src/filters/skip/mod.rs
mod skip_; mod skip_until; mod skip_while; pub use skip_::Skip; pub use skip_until::SkipUntil; pub use skip_while::SkipWhile;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/skip/skip_until.rs
crates/nu-command/src/filters/skip/skip_until.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct SkipUntil; impl Command for SkipUntil { fn name(&self) -> &str { "skip until" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::table(), Type::table()), ( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::Any)), ), ]) .required( "predicate", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The predicate that skipped element must not match.", ) .category(Category::Filters) } fn description(&self) -> &str { "Skip elements of the input until a predicate is true." } fn search_terms(&self) -> Vec<&str> { vec!["ignore"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Skip until the element is positive", example: "[-2 0 2 -1] | skip until {|x| $x > 0 }", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(-1), ])), }, Example { description: "Skip until the element is positive using stored condition", example: "let cond = {|x| $x > 0 }; [-2 0 2 -1] | skip until $cond", result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(-1), ])), }, Example { description: "Skip until the field value is positive", example: "[{a: -2} {a: 0} {a: 2} {a: -1}] | skip until {|x| $x.a > 0 }", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(2), }), Value::test_record(record! { "a" => Value::test_int(-1), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let mut closure = ClosureEval::new(engine_state, stack, closure); let metadata = input.metadata(); Ok(input .into_iter_strict(head)? .skip_while(move |value| { closure .run_with_value(value.clone()) .and_then(|data| data.into_value(head)) .map(|cond| cond.is_false()) .unwrap_or(false) }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), metadata)) } } #[cfg(test)] mod tests { use crate::SkipUntil; #[test] fn test_examples() { use crate::test_examples; test_examples(SkipUntil) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/merge/merge_.rs
crates/nu-command/src/filters/merge/merge_.rs
use super::common::{MergeStrategy, do_merge, typecheck_merge}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Merge; impl Command for Merge { fn name(&self) -> &str { "merge" } fn description(&self) -> &str { "Merge the input with a record or table, overwriting values in matching columns." } fn extra_description(&self) -> &str { r#"You may provide a column structure to merge When merging tables, row 0 of the input table is overwritten with values from row 0 of the provided table, then repeating this process with row 1, and so on."# } fn signature(&self) -> nu_protocol::Signature { Signature::build("merge") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ]) .required( "value", SyntaxShape::OneOf(vec![ SyntaxShape::Record(vec![]), SyntaxShape::Table(vec![]), ]), "The new value to merge with.", ) .category(Category::Filters) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "[a b c] | wrap name | merge ( [47 512 618] | wrap id )", description: "Add an 'id' column to the input table", result: Some(Value::list( vec![ Value::test_record(record! { "name" => Value::test_string("a"), "id" => Value::test_int(47), }), Value::test_record(record! { "name" => Value::test_string("b"), "id" => Value::test_int(512), }), Value::test_record(record! { "name" => Value::test_string("c"), "id" => Value::test_int(618), }), ], Span::test_data(), )), }, Example { example: "{a: 1, b: 2} | merge {c: 3}", description: "Merge two records", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), "c" => Value::test_int(3), })), }, Example { example: "[{columnA: A0 columnB: B0}] | merge [{columnA: 'A0*'}]", description: "Merge two tables, overwriting overlapping columns", result: Some(Value::test_list(vec![Value::test_record(record! { "columnA" => Value::test_string("A0*"), "columnB" => Value::test_string("B0"), })])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let merge_value: Value = call.req(engine_state, stack, 0)?; let metadata = input.metadata(); // collect input before typechecking, so tables are detected as such let input_span = input.span().unwrap_or(head); let input = input.into_value(input_span)?; typecheck_merge(&input, &merge_value, head)?; let merged = do_merge(input, merge_value, MergeStrategy::Shallow, head)?; Ok(merged.into_pipeline_data_with_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Merge {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/merge/deep.rs
crates/nu-command/src/filters/merge/deep.rs
use super::common::{ListMerge, MergeStrategy, do_merge, typecheck_merge}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct MergeDeep; impl Command for MergeDeep { fn name(&self) -> &str { "merge deep" } fn description(&self) -> &str { "Merge the input with a record or table, recursively merging values in matching columns." } fn extra_description(&self) -> &str { r#"The way that key-value pairs which exist in both the input and the argument are merged depends on their types. Scalar values (like numbers and strings) in the input are overwritten by the corresponding value from the argument. Records in the input are merged similarly to the merge command, but recursing rather than overwriting inner records. The way lists and tables are merged is controlled by the `--strategy` flag: - table: Merges tables element-wise, similarly to the merge command. Non-table lists are overwritten. - overwrite: Lists and tables are overwritten with their corresponding value from the argument, similarly to scalars. - append: Lists and tables in the input are appended with the corresponding list from the argument. - prepend: Lists and tables in the input are prepended with the corresponding list from the argument."# } fn signature(&self) -> nu_protocol::Signature { Signature::build("merge deep") .input_output_types(vec![ (Type::record(), Type::record()), (Type::table(), Type::table()), ]) .required( "value", SyntaxShape::OneOf(vec![ SyntaxShape::Record(vec![]), SyntaxShape::Table(vec![]), SyntaxShape::List(SyntaxShape::Any.into()), ]), "The new value to merge with.", ) .category(Category::Filters) .param( Flag::new("strategy") .short('s') .arg(SyntaxShape::String) .desc( "The list merging strategy to use. One of: table (default), overwrite, \ append, prepend", ) .completion(Completion::new_list(&[ "table", "overwrite", "append", "prepend", ])), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "{a: 1, b: {c: 2, d: 3}} | merge deep {b: {d: 4, e: 5}}", description: "Merge two records recursively", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_record(record! { "c" => Value::test_int(2), "d" => Value::test_int(4), "e" => Value::test_int(5), }) })), }, Example { example: r#"[{columnA: 0, columnB: [{B1: 1}]}] | merge deep [{columnB: [{B2: 2}]}]"#, description: "Merge two tables", result: Some(Value::test_list(vec![Value::test_record(record! { "columnA" => Value::test_int(0), "columnB" => Value::test_list(vec![ Value::test_record(record! { "B1" => Value::test_int(1), "B2" => Value::test_int(2), }) ]), })])), }, Example { example: r#"{inner: [{a: 1}, {b: 2}]} | merge deep {inner: [{c: 3}]}"#, description: "Merge two records and their inner tables", result: Some(Value::test_record(record! { "inner" => Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(1), "c" => Value::test_int(3), }), Value::test_record(record! { "b" => Value::test_int(2), }) ]) })), }, Example { example: r#"{inner: [{a: 1}, {b: 2}]} | merge deep {inner: [{c: 3}]} --strategy=append"#, description: "Merge two records, appending their inner tables", result: Some(Value::test_record(record! { "inner" => Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(1), }), Value::test_record(record! { "b" => Value::test_int(2), }), Value::test_record(record! { "c" => Value::test_int(3), }), ]) })), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let merge_value: Value = call.req(engine_state, stack, 0)?; let strategy_flag: Option<String> = call.get_flag(engine_state, stack, "strategy")?; let metadata = input.metadata(); // collect input before typechecking, so tables are detected as such let input_span = input.span().unwrap_or(head); let input = input.into_value(input_span)?; let strategy = match strategy_flag.as_deref() { None | Some("table") => MergeStrategy::Deep(ListMerge::Elementwise), Some("append") => MergeStrategy::Deep(ListMerge::Append), Some("prepend") => MergeStrategy::Deep(ListMerge::Prepend), Some("overwrite") => MergeStrategy::Deep(ListMerge::Overwrite), Some(_) => { return Err(ShellError::IncorrectValue { msg: "The list merging strategy must be one one of: table, overwrite, append, prepend".to_string(), val_span: call.get_flag_span(stack, "strategy").unwrap_or(head), call_span: head, }) } }; typecheck_merge(&input, &merge_value, head)?; let merged = do_merge(input, merge_value, strategy, head)?; Ok(merged.into_pipeline_data_with_metadata(metadata)) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(MergeDeep {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/merge/mod.rs
crates/nu-command/src/filters/merge/mod.rs
mod common; pub mod deep; pub mod merge_; pub use deep::MergeDeep; pub use merge_::Merge;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filters/merge/common.rs
crates/nu-command/src/filters/merge/common.rs
use nu_engine::command_prelude::*; #[derive(Copy, Clone)] pub(crate) enum MergeStrategy { /// Key-value pairs present in lhs and rhs are overwritten by values in rhs Shallow, /// Records are merged recursively, otherwise same behavior as shallow Deep(ListMerge), } #[derive(Copy, Clone)] pub(crate) enum ListMerge { /// Lists in lhs are overwritten by lists in rhs Overwrite, /// Lists of records are merged element-wise, other lists are overwritten by rhs Elementwise, /// All lists are concatenated together, lhs ++ rhs Append, /// All lists are concatenated together, rhs ++ lhs Prepend, } /// Test whether a value is a list of records. /// /// This includes tables and non-tables. fn is_list_of_records(val: &Value) -> bool { match val { list @ Value::List { .. } if matches!(list.get_type(), Type::Table { .. }) => true, // we want to include lists of records, but not lists of mixed types Value::List { vals, .. } => vals .iter() .map(Value::get_type) .all(|val| matches!(val, Type::Record { .. })), _ => false, } } /// Typecheck a merge operation. /// /// Ensures that both arguments are records, tables, or lists of non-matching records. pub(crate) fn typecheck_merge(lhs: &Value, rhs: &Value, head: Span) -> Result<(), ShellError> { match (lhs.get_type(), rhs.get_type()) { (Type::Record { .. }, Type::Record { .. }) => Ok(()), (_, _) if is_list_of_records(lhs) && is_list_of_records(rhs) => Ok(()), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "input and argument to be both record or both table".to_string(), wrong_type: format!("{} and {}", other.0, other.1).to_string(), dst_span: head, src_span: lhs.span(), }), } } pub(crate) fn do_merge( lhs: Value, rhs: Value, strategy: MergeStrategy, span: Span, ) -> Result<Value, ShellError> { match (strategy, lhs, rhs) { // Propagate errors (_, Value::Error { error, .. }, _) | (_, _, Value::Error { error, .. }) => Err(*error), // Shallow merge records ( MergeStrategy::Shallow, Value::Record { val: lhs, .. }, Value::Record { val: rhs, .. }, ) => Ok(Value::record( merge_records(lhs.into_owned(), rhs.into_owned(), strategy, span)?, span, )), // Deep merge records ( MergeStrategy::Deep(_), Value::Record { val: lhs, .. }, Value::Record { val: rhs, .. }, ) => Ok(Value::record( merge_records(lhs.into_owned(), rhs.into_owned(), strategy, span)?, span, )), // Merge lists by appending ( MergeStrategy::Deep(ListMerge::Append), Value::List { vals: lhs, .. }, Value::List { vals: rhs, .. }, ) => Ok(Value::list(lhs.into_iter().chain(rhs).collect(), span)), // Merge lists by prepending ( MergeStrategy::Deep(ListMerge::Prepend), Value::List { vals: lhs, .. }, Value::List { vals: rhs, .. }, ) => Ok(Value::list(rhs.into_iter().chain(lhs).collect(), span)), // Merge lists of records elementwise (tables and non-tables) // Match on shallow since this might be a top-level table ( MergeStrategy::Shallow | MergeStrategy::Deep(ListMerge::Elementwise), lhs_list @ Value::List { .. }, rhs_list @ Value::List { .. }, ) if is_list_of_records(&lhs_list) && is_list_of_records(&rhs_list) => { let lhs = lhs_list .into_list() .expect("Value matched as list above, but is not a list"); let rhs = rhs_list .into_list() .expect("Value matched as list above, but is not a list"); Ok(Value::list(merge_tables(lhs, rhs, strategy, span)?, span)) } // Use rhs value (shallow record merge, overwrite list merge, and general scalar merge) (_, _, val) => Ok(val), } } /// Merge right-hand table into left-hand table, element-wise /// /// For example: /// lhs = [{a: 12, b: 34}] /// rhs = [{a: 56, c: 78}] /// output = [{a: 56, b: 34, c: 78}] fn merge_tables( lhs: Vec<Value>, rhs: Vec<Value>, strategy: MergeStrategy, span: Span, ) -> Result<Vec<Value>, ShellError> { let mut table_iter = rhs.into_iter(); lhs.into_iter() .map(move |inp| match (inp.into_record(), table_iter.next()) { (Ok(rec), Some(to_merge)) => match to_merge.into_record() { Ok(to_merge) => Ok(Value::record( merge_records(rec.to_owned(), to_merge.to_owned(), strategy, span)?, span, )), Err(error) => Ok(Value::error(error, span)), }, (Ok(rec), None) => Ok(Value::record(rec, span)), (Err(error), _) => Ok(Value::error(error, span)), }) .collect() } fn merge_records( mut lhs: Record, rhs: Record, strategy: MergeStrategy, span: Span, ) -> Result<Record, ShellError> { match strategy { MergeStrategy::Shallow => { for (col, rval) in rhs.into_iter() { lhs.insert(col, rval); } } strategy => { for (col, rval) in rhs.into_iter() { // in order to both avoid cloning (possibly nested) record values and maintain the ordering of record keys, we can swap a temporary value into the source record. // if we were to remove the value, the ordering would be messed up as we might not insert back into the original index // it's okay to swap a temporary value in, since we know it will be replaced by the end of the function call // // use an error here instead of something like null so if this somehow makes it into the output, the bug will be immediately obvious let failed_error = ShellError::NushellFailed { msg: "Merge failed to properly replace internal temporary value".to_owned(), }; let value = match lhs.insert(&col, Value::error(failed_error, span)) { Some(lval) => do_merge(lval, rval, strategy, span)?, None => rval, }; lhs.insert(col, value); } } } Ok(lhs) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/starts_with.rs
crates/nu-command/src/bytes/starts_with.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::shell_error::io::IoError; use std::io::Read; struct Arguments { pattern: Vec<u8>, cell_paths: Option<Vec<CellPath>>, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct BytesStartsWith; impl Command for BytesStartsWith { fn name(&self) -> &str { "bytes starts-with" } fn signature(&self) -> Signature { Signature::build("bytes starts-with") .input_output_types(vec![ (Type::Binary, Type::Bool), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("pattern", SyntaxShape::Binary, "The pattern to match.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, check if bytes at the given cell paths start with the pattern.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Check if bytes starts with a pattern." } fn search_terms(&self) -> Vec<&str> { vec!["pattern", "match", "find", "search"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let pattern: Vec<u8> = call.req(engine_state, stack, 0)?; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); if let PipelineData::ByteStream(stream, ..) = input { let span = stream.span(); if pattern.is_empty() { return Ok(Value::bool(true, head).into_pipeline_data()); } let Some(reader) = stream.reader() else { return Ok(Value::bool(false, head).into_pipeline_data()); }; let mut start = Vec::with_capacity(pattern.len()); reader .take(pattern.len() as u64) .read_to_end(&mut start) .map_err(|err| IoError::new(err, span, None))?; Ok(Value::bool(start == pattern, head).into_pipeline_data()) } else { let arg = Arguments { pattern, cell_paths, }; operate(starts_with, arg, input, head, engine_state.signals()) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Checks if binary starts with `0x[1F FF AA]`", example: "0x[1F FF AA AA] | bytes starts-with 0x[1F FF AA]", result: Some(Value::test_bool(true)), }, Example { description: "Checks if binary starts with `0x[1F]`", example: "0x[1F FF AA AA] | bytes starts-with 0x[1F]", result: Some(Value::test_bool(true)), }, Example { description: "Checks if binary starts with `0x[1F]`", example: "0x[1F FF AA AA] | bytes starts-with 0x[11]", result: Some(Value::test_bool(false)), }, ] } } fn starts_with(val: &Value, args: &Arguments, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => Value::bool(val.starts_with(&args.pattern), val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesStartsWith {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/reverse.rs
crates/nu-command/src/bytes/reverse.rs
use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BytesReverse; impl Command for BytesReverse { fn name(&self) -> &str { "bytes reverse" } fn signature(&self) -> Signature { Signature::build("bytes reverse") .input_output_types(vec![ (Type::Binary, Type::Binary), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, reverse data at the given cell paths.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Reverse the bytes in the pipeline." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "inverse", "flip"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let arg = CellPathOnlyArgs::from(cell_paths); operate(reverse, arg, input, call.head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Reverse bytes `0x[1F FF AA AA]`", example: "0x[1F FF AA AA] | bytes reverse", result: Some(Value::binary( vec![0xAA, 0xAA, 0xFF, 0x1F], Span::test_data(), )), }, Example { description: "Reverse bytes `0x[FF AA AA]`", example: "0x[FF AA AA] | bytes reverse", result: Some(Value::binary(vec![0xAA, 0xAA, 0xFF], Span::test_data())), }, ] } } fn reverse(val: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => { let mut reversed_input = val.to_vec(); reversed_input.reverse(); Value::binary(reversed_input, val_span) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesReverse {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/bytes_.rs
crates/nu-command/src/bytes/bytes_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Bytes; impl Command for Bytes { fn name(&self) -> &str { "bytes" } fn signature(&self) -> Signature { Signature::build("bytes") .category(Category::Bytes) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for working with byte data." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/collect.rs
crates/nu-command/src/bytes/collect.rs
use itertools::Itertools; use nu_engine::command_prelude::*; #[derive(Clone, Copy)] pub struct BytesCollect; impl Command for BytesCollect { fn name(&self) -> &str { "bytes collect" } fn signature(&self) -> Signature { Signature::build("bytes collect") .input_output_types(vec![(Type::List(Box::new(Type::Binary)), Type::Binary)]) .optional( "separator", SyntaxShape::Binary, "Optional separator to use when creating binary.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Concatenate multiple binary into a single binary, with an optional separator between each." } fn search_terms(&self) -> Vec<&str> { vec!["join", "concatenate"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Option<Vec<u8>> = call.opt(engine_state, stack, 0)?; let span = call.head; // input should be a list of binary data. let metadata = input.metadata(); let iter = Itertools::intersperse( input.into_iter_strict(span)?.map(move |value| { // Everything is wrapped in Some in case there's a separator, so we can flatten Some(match value { // Explicitly propagate errors instead of dropping them. Value::Error { error, .. } => Err(*error), Value::Binary { val, .. } => Ok(val), other => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }), }) }), Ok(separator).transpose(), ) .flatten(); let output = ByteStream::from_result_iter( iter, span, engine_state.signals().clone(), ByteStreamType::Binary, ); Ok(PipelineData::byte_stream(output, metadata)) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a byte array from input", example: "[0x[11] 0x[13 15]] | bytes collect", result: Some(Value::binary(vec![0x11, 0x13, 0x15], Span::test_data())), }, Example { description: "Create a byte array from input with a separator", example: "[0x[11] 0x[33] 0x[44]] | bytes collect 0x[01]", result: Some(Value::binary( vec![0x11, 0x01, 0x33, 0x01, 0x44], Span::test_data(), )), }, ] } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesCollect {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/index_of.rs
crates/nu-command/src/bytes/index_of.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { pattern: Vec<u8>, end: bool, all: bool, cell_paths: Option<Vec<CellPath>>, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct BytesIndexOf; impl Command for BytesIndexOf { fn name(&self) -> &str { "bytes index-of" } fn signature(&self) -> Signature { Signature::build("bytes index-of") .input_output_types(vec![ (Type::Binary, Type::Any), // FIXME: this shouldn't be needed, cell paths should work with the two // above (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required( "pattern", SyntaxShape::Binary, "The pattern to find index of.", ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, find the indexes at the given cell paths.", ) .switch("all", "returns all matched index", Some('a')) .switch("end", "search from the end of the binary", Some('e')) .category(Category::Bytes) } fn description(&self) -> &str { "Returns start index of first occurrence of pattern in bytes, or -1 if no match." } fn search_terms(&self) -> Vec<&str> { vec!["pattern", "match", "find", "search"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let pattern: Vec<u8> = call.req(engine_state, stack, 0)?; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let arg = Arguments { pattern, end: call.has_flag(engine_state, stack, "end")?, all: call.has_flag(engine_state, stack, "all")?, cell_paths, }; operate(index_of, arg, input, call.head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns index of pattern in bytes", example: " 0x[33 44 55 10 01 13 44 55] | bytes index-of 0x[44 55]", result: Some(Value::test_int(1)), }, Example { description: "Returns index of pattern, search from end", example: " 0x[33 44 55 10 01 13 44 55] | bytes index-of --end 0x[44 55]", result: Some(Value::test_int(6)), }, Example { description: "Returns all matched index", example: " 0x[33 44 55 10 01 33 44 33 44] | bytes index-of --all 0x[33 44]", result: Some(Value::test_list(vec![ Value::test_int(0), Value::test_int(5), Value::test_int(7), ])), }, Example { description: "Returns all matched index, searching from end", example: " 0x[33 44 55 10 01 33 44 33 44] | bytes index-of --all --end 0x[33 44]", result: Some(Value::test_list(vec![ Value::test_int(7), Value::test_int(5), Value::test_int(0), ])), }, Example { description: "Returns index of pattern for specific column", example: r#" [[ColA ColB ColC]; [0x[11 12 13] 0x[14 15 16] 0x[17 18 19]]] | bytes index-of 0x[11] ColA ColC"#, result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_int(0), "ColB" => Value::binary(vec![0x14, 0x15, 0x16], Span::test_data()), "ColC" => Value::test_int(-1), })])), }, ] } } fn index_of(val: &Value, args: &Arguments, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => index_of_impl(val, args, val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn index_of_impl(input: &[u8], arg: &Arguments, span: Span) -> Value { if arg.all { search_all_index(input, &arg.pattern, arg.end, span) } else { let mut iter = input.windows(arg.pattern.len()); if arg.end { Value::int( iter.rev() .position(|sub_bytes| sub_bytes == arg.pattern) .map(|x| (input.len() - arg.pattern.len() - x) as i64) .unwrap_or(-1), span, ) } else { Value::int( iter.position(|sub_bytes| sub_bytes == arg.pattern) .map(|x| x as i64) .unwrap_or(-1), span, ) } } } fn search_all_index(input: &[u8], pattern: &[u8], from_end: bool, span: Span) -> Value { let mut result = vec![]; if from_end { let (mut left, mut right) = ( input.len() as isize - pattern.len() as isize, input.len() as isize, ); while left >= 0 { if &input[left as usize..right as usize] == pattern { result.push(Value::int(left as i64, span)); left -= pattern.len() as isize; right -= pattern.len() as isize; } else { left -= 1; right -= 1; } } Value::list(result, span) } else { // doing find stuff. let (mut left, mut right) = (0, pattern.len()); let input_len = input.len(); let pattern_len = pattern.len(); while right <= input_len { if &input[left..right] == pattern { result.push(Value::int(left as i64, span)); left += pattern_len; right += pattern_len; } else { left += 1; right += 1; } } Value::list(result, span) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesIndexOf {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/replace.rs
crates/nu-command/src/bytes/replace.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { find: Vec<u8>, replace: Vec<u8>, cell_paths: Option<Vec<CellPath>>, all: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct BytesReplace; impl Command for BytesReplace { fn name(&self) -> &str { "bytes replace" } fn signature(&self) -> Signature { Signature::build("bytes replace") .input_output_types(vec![ (Type::Binary, Type::Binary), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("find", SyntaxShape::Binary, "The pattern to find.") .required("replace", SyntaxShape::Binary, "The replacement pattern.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, replace bytes in data at the given cell paths.", ) .switch("all", "replace all occurrences of find binary", Some('a')) .category(Category::Bytes) } fn description(&self) -> &str { "Find and replace binary." } fn search_terms(&self) -> Vec<&str> { vec!["search", "shift", "switch"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 2)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let find = call.req::<Spanned<Vec<u8>>>(engine_state, stack, 0)?; if find.item.is_empty() { return Err(ShellError::TypeMismatch { err_message: "the pattern to find cannot be empty".to_string(), span: find.span, }); } let arg = Arguments { find: find.item, replace: call.req::<Vec<u8>>(engine_state, stack, 1)?, cell_paths, all: call.has_flag(engine_state, stack, "all")?, }; operate(replace, arg, input, call.head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Find and replace contents", example: "0x[10 AA FF AA FF] | bytes replace 0x[10 AA] 0x[FF]", result: Some(Value::test_binary(vec![0xFF, 0xFF, 0xAA, 0xFF])), }, Example { description: "Find and replace all occurrences of find binary", example: "0x[10 AA 10 BB 10] | bytes replace --all 0x[10] 0x[A0]", result: Some(Value::test_binary(vec![0xA0, 0xAA, 0xA0, 0xBB, 0xA0])), }, Example { description: "Find and replace all occurrences of find binary in table", example: "[[ColA ColB ColC]; [0x[11 12 13] 0x[14 15 16] 0x[17 18 19]]] | bytes replace --all 0x[11] 0x[13] ColA ColC", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_binary(vec![0x13, 0x12, 0x13]), "ColB" => Value::test_binary(vec![0x14, 0x15, 0x16]), "ColC" => Value::test_binary(vec![0x17, 0x18, 0x19]), })])), }, ] } } fn replace(val: &Value, args: &Arguments, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => replace_impl(val, args, val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn replace_impl(input: &[u8], arg: &Arguments, span: Span) -> Value { let mut replaced = vec![]; let replace_all = arg.all; // doing find-and-replace stuff. let (mut left, mut right) = (0, arg.find.len()); let input_len = input.len(); let pattern_len = arg.find.len(); while right <= input_len { if input[left..right] == arg.find { let mut to_replace = arg.replace.clone(); replaced.append(&mut to_replace); left += pattern_len; right += pattern_len; if !replace_all { break; } } else { replaced.push(input[left]); left += 1; right += 1; } } let mut remain = input[left..].to_vec(); replaced.append(&mut remain); Value::binary(replaced, span) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesReplace {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/mod.rs
crates/nu-command/src/bytes/mod.rs
mod add; mod at; mod build_; mod bytes_; mod collect; mod ends_with; mod index_of; mod length; mod remove; mod replace; mod reverse; mod split; mod starts_with; pub use add::BytesAdd; pub use at::BytesAt; pub use build_::BytesBuild; pub use bytes_::Bytes; pub use collect::BytesCollect; pub use ends_with::BytesEndsWith; pub use index_of::BytesIndexOf; pub use length::BytesLen; pub use remove::BytesRemove; pub use replace::BytesReplace; pub use reverse::BytesReverse; pub use split::BytesSplit; pub use starts_with::BytesStartsWith;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/ends_with.rs
crates/nu-command/src/bytes/ends_with.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::shell_error::io::IoError; use std::{ collections::VecDeque, io::{self, BufRead}, }; struct Arguments { pattern: Vec<u8>, cell_paths: Option<Vec<CellPath>>, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct BytesEndsWith; impl Command for BytesEndsWith { fn name(&self) -> &str { "bytes ends-with" } fn signature(&self) -> Signature { Signature::build("bytes ends-with") .input_output_types(vec![(Type::Binary, Type::Bool), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("pattern", SyntaxShape::Binary, "The pattern to match.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, check if bytes at the given cell paths end with the pattern.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Check if bytes ends with a pattern." } fn search_terms(&self) -> Vec<&str> { vec!["pattern", "match", "find", "search"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let pattern: Vec<u8> = call.req(engine_state, stack, 0)?; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); if let PipelineData::ByteStream(stream, ..) = input { let span = stream.span(); if pattern.is_empty() { return Ok(Value::bool(true, head).into_pipeline_data()); } let Some(mut reader) = stream.reader() else { return Ok(Value::bool(false, head).into_pipeline_data()); }; let cap = pattern.len(); let mut end = VecDeque::<u8>::with_capacity(cap); loop { let buf = match reader.fill_buf() { Ok(&[]) => break, Ok(buf) => buf, Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => return Err(IoError::new(e, span, None).into()), }; let len = buf.len(); if len >= cap { end.clear(); end.extend(&buf[(len - cap)..]) } else { let new_len = len + end.len(); if new_len > cap { // The `drain` below will panic if `(new_len - cap) > end.len()`. // But this cannot happen since we know `len < cap` (as checked above): // (len + end.len() - cap) > end.len() // => (len - cap) > 0 // => len > cap end.drain(..(new_len - cap)); } end.extend(buf); } reader.consume(len); } Ok(Value::bool(end == pattern, head).into_pipeline_data()) } else { let arg = Arguments { pattern, cell_paths, }; operate(ends_with, arg, input, head, engine_state.signals()) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Checks if binary ends with `0x[AA]`", example: "0x[1F FF AA AA] | bytes ends-with 0x[AA]", result: Some(Value::test_bool(true)), }, Example { description: "Checks if binary ends with `0x[FF AA AA]`", example: "0x[1F FF AA AA] | bytes ends-with 0x[FF AA AA]", result: Some(Value::test_bool(true)), }, Example { description: "Checks if binary ends with `0x[11]`", example: "0x[1F FF AA AA] | bytes ends-with 0x[11]", result: Some(Value::test_bool(false)), }, ] } } fn ends_with(val: &Value, args: &Arguments, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => Value::bool(val.ends_with(&args.pattern), val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesEndsWith {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/at.rs
crates/nu-command/src/bytes/at.rs
use std::ops::Bound; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::{IntRange, Range}; #[derive(Clone)] pub struct BytesAt; struct Arguments { range: IntRange, cell_paths: Option<Vec<CellPath>>, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } impl Command for BytesAt { fn name(&self) -> &str { "bytes at" } fn signature(&self) -> Signature { Signature::build("bytes at") .input_output_types(vec![ (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("range", SyntaxShape::Range, "The range to get bytes.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, get bytes from data at the given cell paths.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Get bytes defined by a range." } fn search_terms(&self) -> Vec<&str> { vec!["slice"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let range = match call.req(engine_state, stack, 0)? { Range::IntRange(range) => range, _ => { return Err(ShellError::UnsupportedInput { msg: "Float ranges are not supported for byte streams".into(), input: "value originates from here".into(), msg_span: call.head, input_span: call.head, }); } }; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); if let PipelineData::ByteStream(stream, metadata) = input { let stream = stream.slice(call.head, call.arguments_span(), range)?; // bytes 3..5 of an image/png stream are not image/png themselves let metadata = metadata.map(|m| m.with_content_type(None)); Ok(PipelineData::byte_stream(stream, metadata)) } else { operate( map_value, Arguments { range, cell_paths }, input, call.head, engine_state.signals(), ) .map(|pipeline| { // bytes 3..5 of an image/png stream are not image/png themselves let metadata = pipeline.metadata().map(|m| m.with_content_type(None)); pipeline.set_metadata(metadata) }) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Extract bytes starting from a specific index", example: "{ data: 0x[33 44 55 10 01 13 10] } | bytes at 3.. data", result: Some(Value::test_record(record! { "data" => Value::test_binary(vec![0x10, 0x01, 0x13, 0x10]), })), }, Example { description: "Slice out `0x[10 01 13]` from `0x[33 44 55 10 01 13]`", example: "0x[33 44 55 10 01 13] | bytes at 3..5", result: Some(Value::test_binary(vec![0x10, 0x01, 0x13])), }, Example { description: "Extract bytes from the start up to a specific index", example: "0x[33 44 55 10 01 13 10] | bytes at ..4", result: Some(Value::test_binary(vec![0x33, 0x44, 0x55, 0x10, 0x01])), }, Example { description: "Extract byte `0x[10]` using an exclusive end index", example: "0x[33 44 55 10 01 13 10] | bytes at 3..<4", result: Some(Value::test_binary(vec![0x10])), }, Example { description: "Extract bytes up to a negative index (inclusive)", example: "0x[33 44 55 10 01 13 10] | bytes at ..-4", result: Some(Value::test_binary(vec![0x33, 0x44, 0x55, 0x10])), }, Example { description: "Slice bytes across multiple table columns", example: r#"[[ColA ColB ColC]; [0x[11 12 13] 0x[14 15 16] 0x[17 18 19]]] | bytes at 1.. ColB ColC"#, result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_binary(vec![0x11, 0x12, 0x13]), "ColB" => Value::test_binary(vec![0x15, 0x16]), "ColC" => Value::test_binary(vec![0x18, 0x19]), })])), }, Example { description: "Extract the last three bytes using a negative start index", example: "0x[33 44 55 10 01 13 10] | bytes at (-3)..", result: Some(Value::test_binary(vec![0x01, 0x13, 0x10])), }, ] } } fn map_value(input: &Value, args: &Arguments, head: Span) -> Value { let range = &args.range; match input { Value::Binary { val, .. } => { let len = val.len() as u64; let start: u64 = range.absolute_start(len); let _start: usize = match start.try_into() { Ok(start) => start, Err(_) => { let span = input.span(); return Value::error( ShellError::UnsupportedInput { msg: format!( "Absolute start position {start} was too large for your system arch." ), input: args.range.to_string(), msg_span: span, input_span: span, }, head, ); } }; let (start, end) = range.absolute_bounds(val.len()); let bytes: Vec<u8> = match end { Bound::Unbounded => val[start..].into(), Bound::Included(end) => val[start..=end].into(), Bound::Excluded(end) => val[start..end].into(), }; Value::binary(bytes, head) } Value::Error { .. } => input.clone(), other => Value::error( ShellError::UnsupportedInput { msg: "Only binary values are supported".into(), input: format!("input type: {:?}", other.get_type()), msg_span: head, input_span: other.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesAt {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/build_.rs
crates/nu-command/src/bytes/build_.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BytesBuild; impl Command for BytesBuild { fn name(&self) -> &str { "bytes build" } fn description(&self) -> &str { "Create bytes from the arguments." } fn search_terms(&self) -> Vec<&str> { vec!["concatenate", "join"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("bytes build") .input_output_types(vec![(Type::Nothing, Type::Binary)]) .rest("rest", SyntaxShape::Any, "List of bytes.") .category(Category::Bytes) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "bytes build 0x[01 02] 0x[03] 0x[04]", description: "Builds binary data from 0x[01 02], 0x[03], 0x[04]", result: Some(Value::binary( vec![0x01, 0x02, 0x03, 0x04], Span::test_data(), )), }, Example { example: "bytes build 255 254 253 252", description: "Builds binary data from byte numbers", result: Some(Value::test_binary(vec![0xff, 0xfe, 0xfd, 0xfc])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let mut output = vec![]; for val in call.rest::<Value>(engine_state, stack, 0)? { let val_span = val.span(); match val { Value::Binary { mut val, .. } => output.append(&mut val), Value::Int { val, .. } => { let byte: u8 = val.try_into().map_err(|_| ShellError::IncorrectValue { msg: format!("{val} is out of range for byte"), val_span, call_span: call.head, })?; output.push(byte); } // Explicitly propagate errors instead of dropping them. Value::Error { error, .. } => return Err(*error), other => { return Err(ShellError::TypeMismatch { err_message: "only binary data arguments are supported".to_string(), span: other.span(), }); } } } Ok(Value::binary(output, call.head).into_pipeline_data()) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesBuild {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/length.rs
crates/nu-command/src/bytes/length.rs
use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BytesLen; impl Command for BytesLen { fn name(&self) -> &str { "bytes length" } fn signature(&self) -> Signature { Signature::build("bytes length") .input_output_types(vec![ (Type::Binary, Type::Int), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Int)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, find the length of data at the given cell paths.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Output the length of any bytes in the pipeline." } fn search_terms(&self) -> Vec<&str> { vec!["size", "count"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let arg = CellPathOnlyArgs::from(cell_paths); operate(length, arg, input, call.head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return the length of a binary", example: "0x[1F FF AA AB] | bytes length", result: Some(Value::test_int(4)), }, Example { description: "Return the lengths of multiple binaries", example: "[0x[1F FF AA AB] 0x[1F]] | bytes length", result: Some(Value::list( vec![Value::test_int(4), Value::test_int(1)], Span::test_data(), )), }, ] } fn is_const(&self) -> bool { true } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest_const(working_set, 0)?; let arg = CellPathOnlyArgs::from(cell_paths); operate( length, arg, input, call.head, working_set.permanent().signals(), ) } } fn length(val: &Value, _args: &CellPathOnlyArgs, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => Value::int(val.len() as i64, val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesLen {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/add.rs
crates/nu-command/src/bytes/add.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { added_data: Vec<u8>, index: Option<usize>, end: bool, cell_paths: Option<Vec<CellPath>>, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct BytesAdd; impl Command for BytesAdd { fn name(&self) -> &str { "bytes add" } fn signature(&self) -> Signature { Signature::build("bytes add") .input_output_types(vec![ (Type::Binary, Type::Binary), ( Type::List(Box::new(Type::Binary)), Type::List(Box::new(Type::Binary)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("data", SyntaxShape::Binary, "The binary to add.") .named( "index", SyntaxShape::Int, "index to insert binary data", Some('i'), ) .switch("end", "add to the end of binary", Some('e')) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, add bytes to the data at the given cell paths.", ) .category(Category::Bytes) } fn description(&self) -> &str { "Add specified bytes to the input." } fn search_terms(&self) -> Vec<&str> { vec!["append", "truncate", "padding"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let added_data: Vec<u8> = call.req(engine_state, stack, 0)?; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let index: Option<usize> = call.get_flag(engine_state, stack, "index")?; let end = call.has_flag(engine_state, stack, "end")?; let arg = Arguments { added_data, index, end, cell_paths, }; operate(add, arg, input, call.head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Add bytes `0x[AA]` to `0x[1F FF AA AA]`", example: "0x[1F FF AA AA] | bytes add 0x[AA]", result: Some(Value::binary( vec![0xAA, 0x1F, 0xFF, 0xAA, 0xAA], Span::test_data(), )), }, Example { description: "Add bytes `0x[AA BB]` to `0x[1F FF AA AA]` at index 1", example: "0x[1F FF AA AA] | bytes add 0x[AA BB] --index 1", result: Some(Value::binary( vec![0x1F, 0xAA, 0xBB, 0xFF, 0xAA, 0xAA], Span::test_data(), )), }, Example { description: "Add bytes `0x[11]` to `0x[FF AA AA]` at the end", example: "0x[FF AA AA] | bytes add 0x[11] --end", result: Some(Value::binary( vec![0xFF, 0xAA, 0xAA, 0x11], Span::test_data(), )), }, Example { description: "Add bytes `0x[11 22 33]` to `0x[FF AA AA]` at the end, at index 1(the index is start from end)", example: "0x[FF AA BB] | bytes add 0x[11 22 33] --end --index 1", result: Some(Value::binary( vec![0xFF, 0xAA, 0x11, 0x22, 0x33, 0xBB], Span::test_data(), )), }, ] } } fn add(val: &Value, args: &Arguments, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => add_impl(val, args, val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn add_impl(input: &[u8], args: &Arguments, span: Span) -> Value { match args.index { None => { if args.end { let mut added_data = args.added_data.clone(); let mut result = input.to_vec(); result.append(&mut added_data); Value::binary(result, span) } else { let mut result = args.added_data.clone(); let mut input = input.to_vec(); result.append(&mut input); Value::binary(result, span) } } Some(mut index) => { let inserted_index = if args.end { input.len().saturating_sub(index) } else { if index > input.len() { index = input.len() } index }; let mut result = vec![]; let mut prev_data = input[..inserted_index].to_vec(); result.append(&mut prev_data); let mut added_data = args.added_data.clone(); result.append(&mut added_data); let mut after_data = input[inserted_index..].to_vec(); result.append(&mut after_data); Value::binary(result, span) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesAdd {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/remove.rs
crates/nu-command/src/bytes/remove.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; struct Arguments { pattern: Vec<u8>, end: bool, cell_paths: Option<Vec<CellPath>>, all: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct BytesRemove; impl Command for BytesRemove { fn name(&self) -> &str { "bytes remove" } fn signature(&self) -> Signature { Signature::build("bytes remove") .input_output_types(vec![ (Type::Binary, Type::Binary), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .required("pattern", SyntaxShape::Binary, "The pattern to find.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, remove bytes from data at the given cell paths.", ) .switch("end", "remove from end of binary", Some('e')) .switch("all", "remove occurrences of finding binary", Some('a')) .category(Category::Bytes) } fn description(&self) -> &str { "Remove bytes." } fn search_terms(&self) -> Vec<&str> { vec!["search", "shift", "switch"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let pattern_to_remove = call.req::<Spanned<Vec<u8>>>(engine_state, stack, 0)?; if pattern_to_remove.item.is_empty() { return Err(ShellError::TypeMismatch { err_message: "the pattern to remove cannot be empty".to_string(), span: pattern_to_remove.span, }); } let pattern_to_remove: Vec<u8> = pattern_to_remove.item; let arg = Arguments { pattern: pattern_to_remove, end: call.has_flag(engine_state, stack, "end")?, cell_paths, all: call.has_flag(engine_state, stack, "all")?, }; operate(remove, arg, input, call.head, engine_state.signals()).map(|pipeline| { // image/png with some bytes removed is likely not a valid image/png anymore let metadata = pipeline.metadata().map(|m| m.with_content_type(None)); pipeline.set_metadata(metadata) }) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Remove contents", example: "0x[10 AA FF AA FF] | bytes remove 0x[10 AA]", result: Some(Value::test_binary(vec![0xFF, 0xAA, 0xFF])), }, Example { description: "Remove all occurrences of find binary in record field", example: "{ data: 0x[10 AA 10 BB 10] } | bytes remove --all 0x[10] data", result: Some(Value::test_record(record! { "data" => Value::test_binary(vec![0xAA, 0xBB]) })), }, Example { description: "Remove occurrences of find binary from end", example: "0x[10 AA 10 BB CC AA 10] | bytes remove --end 0x[10]", result: Some(Value::test_binary(vec![0x10, 0xAA, 0x10, 0xBB, 0xCC, 0xAA])), }, Example { description: "Remove find binary from end not found", example: "0x[10 AA 10 BB CC AA 10] | bytes remove --end 0x[11]", result: Some(Value::test_binary(vec![ 0x10, 0xAA, 0x10, 0xBB, 0xCC, 0xAA, 0x10, ])), }, Example { description: "Remove all occurrences of find binary in table", example: "[[ColA ColB ColC]; [0x[11 12 13] 0x[14 15 16] 0x[17 18 19]]] | bytes remove 0x[11] ColA ColC", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_binary ( vec![0x12, 0x13],), "ColB" => Value::test_binary ( vec![0x14, 0x15, 0x16],), "ColC" => Value::test_binary ( vec![0x17, 0x18, 0x19],), })])), }, ] } } fn remove(val: &Value, args: &Arguments, span: Span) -> Value { let val_span = val.span(); match val { Value::Binary { val, .. } => remove_impl(val, args, val_span), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => val.clone(), other => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: other.get_type().to_string(), dst_span: span, src_span: other.span(), }, span, ), } } fn remove_impl(input: &[u8], arg: &Arguments, span: Span) -> Value { let mut result = vec![]; let remove_all = arg.all; let input_len = input.len(); let pattern_len = arg.pattern.len(); // Note: // remove_all from start and end will generate the same result. // so we'll put `remove_all` relative logic into else clause. if arg.end && !remove_all { let (mut left, mut right) = ( input.len() as isize - arg.pattern.len() as isize, input.len() as isize, ); while left >= 0 && input[left as usize..right as usize] != arg.pattern { result.push(input[right as usize - 1]); left -= 1; right -= 1; } // append the remaining thing to result, this can be happening when // we have something to remove and remove_all is False. // check if the left is positive, if it is not, we don't need to append anything. if left > 0 { let mut remain = input[..left as usize].iter().copied().rev().collect(); result.append(&mut remain); } result = result.into_iter().rev().collect(); Value::binary(result, span) } else { let (mut left, mut right) = (0, arg.pattern.len()); while right <= input_len { if input[left..right] == arg.pattern { left += pattern_len; right += pattern_len; if !remove_all { break; } } else { result.push(input[left]); left += 1; right += 1; } } // append the remaining thing to result, this can happened when // we have something to remove and remove_all is False. let mut remain = input[left..].to_vec(); result.append(&mut remain); Value::binary(result, span) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesRemove {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/bytes/split.rs
crates/nu-command/src/bytes/split.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct BytesSplit; impl Command for BytesSplit { fn name(&self) -> &str { "bytes split" } fn signature(&self) -> Signature { Signature::build("bytes split") .input_output_types(vec![(Type::Binary, Type::list(Type::Binary))]) .required( "separator", SyntaxShape::OneOf(vec![SyntaxShape::Binary, SyntaxShape::String]), "Bytes or string that the input will be split on (must be non-empty).", ) .category(Category::Bytes) } fn description(&self) -> &str { "Split input into multiple items using a separator." } fn search_terms(&self) -> Vec<&str> { vec!["separate", "stream"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: r#"0x[66 6F 6F 20 62 61 72 20 62 61 7A 20] | bytes split 0x[20]"#, description: "Split a binary value using a binary separator", result: Some(Value::test_list(vec![ Value::test_binary("foo"), Value::test_binary("bar"), Value::test_binary("baz"), Value::test_binary(""), ])), }, Example { example: r#"0x[61 2D 2D 62 2D 2D 63] | bytes split "--""#, description: "Split a binary value using a string separator", result: Some(Value::test_list(vec![ Value::test_binary("a"), Value::test_binary("b"), Value::test_binary("c"), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let Spanned { item: separator, span, }: Spanned<Vec<u8>> = call.req(engine_state, stack, 0)?; if separator.is_empty() { return Err(ShellError::IncorrectValue { msg: "Separator can't be empty".into(), val_span: span, call_span: call.head, }); } let (split_read, md) = match input { PipelineData::Value(Value::Binary { val, .. }, md) => ( ByteStream::read_binary(val, head, engine_state.signals().clone()).split(separator), md, ), PipelineData::ByteStream(stream, md) => (stream.split(separator), md), input => { let span = input.span().unwrap_or(head); return Err(input.unsupported_input_error("bytes", span)); } }; if let Some(split) = split_read { Ok(split .map(move |part| match part { Ok(val) => Value::binary(val, head), Err(err) => Value::error(err, head), }) .into_pipeline_data_with_metadata(head, engine_state.signals().clone(), md)) } else { Ok(PipelineData::empty()) } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(BytesSplit {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_id.rs
crates/nu-command/src/experimental/job_id.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct JobId; impl Command for JobId { fn name(&self) -> &str { "job id" } fn description(&self) -> &str { "Get id of current job." } fn extra_description(&self) -> &str { "This command returns the job id for the current background job. The special id 0 indicates that this command was not called from a background job thread, and was instead spawned by main nushell execution thread." } fn signature(&self) -> nu_protocol::Signature { Signature::build("job id") .category(Category::Experimental) .input_output_types(vec![(Type::Nothing, Type::Int)]) } fn search_terms(&self) -> Vec<&str> { vec!["self", "this", "my-id", "this-id"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; Ok(Value::int(engine_state.current_job.id.get() as i64, head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "job id", description: "Get id of current job", result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_recv.rs
crates/nu-command/src/experimental/job_recv.rs
use std::{ sync::mpsc::{RecvTimeoutError, TryRecvError}, time::{Duration, Instant}, }; use nu_engine::command_prelude::*; use nu_protocol::{ Signals, engine::{FilterTag, Mailbox}, }; #[derive(Clone)] pub struct JobRecv; const CTRL_C_CHECK_INTERVAL: Duration = Duration::from_millis(100); impl Command for JobRecv { fn name(&self) -> &str { "job recv" } fn description(&self) -> &str { "Read a message from the mailbox." } fn extra_description(&self) -> &str { r#"When messages are sent to the current process, they get stored in what is called the "mailbox". This commands reads and returns a message from the mailbox, in a first-in-first-out fashion. Messages may have numeric flags attached to them. This commands supports filtering out messages that do not satisfy a given tag, by using the `tag` flag. If no tag is specified, this command will accept any message. If no message with the specified tag (if any) is available in the mailbox, this command will block the current thread until one arrives. By default this command block indefinitely until a matching message arrives, but a timeout duration can be specified. If a timeout duration of zero is specified, it will succeed only if there already is a message in the mailbox. Note: When using par-each, only one thread at a time can utilize this command. In the case of two or more threads running this command, they will wait until other threads are done using it, in no particular order, regardless of the specified timeout parameter. "# } fn signature(&self) -> nu_protocol::Signature { Signature::build("job recv") .category(Category::Experimental) .named("tag", SyntaxShape::Int, "A tag for the message", None) .named( "timeout", SyntaxShape::Duration, "The maximum time duration to wait for.", None, ) .input_output_types(vec![(Type::Nothing, Type::Any)]) .allow_variants_without_examples(true) } fn search_terms(&self) -> Vec<&str> { vec!["receive"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let tag_arg: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "tag")?; if let Some(tag) = tag_arg && tag.item < 0 { return Err(ShellError::NeedsPositiveValue { span: tag.span }); } let tag = tag_arg.map(|it| it.item as FilterTag); let timeout: Option<Duration> = call.get_flag(engine_state, stack, "timeout")?; let mut mailbox = engine_state .current_job .mailbox .lock() .expect("failed to acquire lock"); if let Some(timeout) = timeout { if timeout == Duration::ZERO { recv_instantly(&mut mailbox, tag, head) } else { recv_with_time_limit(&mut mailbox, tag, engine_state.signals(), head, timeout) } } else { recv_without_time_limit(&mut mailbox, tag, engine_state.signals(), head) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "job recv", description: "Block the current thread while no message arrives", result: None, }, Example { example: "job recv --timeout 10sec", description: "Receive a message, wait for at most 10 seconds.", result: None, }, Example { example: "job recv --timeout 0sec", description: "Get a message or fail if no message is available immediately", result: None, }, Example { example: "job spawn { sleep 1sec; 'hi' | job send 0 }; job recv", description: "Receive a message from a newly-spawned job", result: None, }, ] } } fn recv_without_time_limit( mailbox: &mut Mailbox, tag: Option<FilterTag>, signals: &Signals, span: Span, ) -> Result<PipelineData, ShellError> { loop { if signals.interrupted() { return Err(ShellError::Interrupted { span }); } match mailbox.recv_timeout(tag, CTRL_C_CHECK_INTERVAL) { Ok(value) => return Ok(value), Err(RecvTimeoutError::Timeout) => {} // try again Err(RecvTimeoutError::Disconnected) => return Err(ShellError::Interrupted { span }), } } } fn recv_instantly( mailbox: &mut Mailbox, tag: Option<FilterTag>, span: Span, ) -> Result<PipelineData, ShellError> { match mailbox.try_recv(tag) { Ok(value) => Ok(value), Err(TryRecvError::Empty) => Err(JobError::RecvTimeout { span }.into()), Err(TryRecvError::Disconnected) => Err(ShellError::Interrupted { span }), } } fn recv_with_time_limit( mailbox: &mut Mailbox, tag: Option<FilterTag>, signals: &Signals, span: Span, timeout: Duration, ) -> Result<PipelineData, ShellError> { let deadline = Instant::now() + timeout; loop { if signals.interrupted() { return Err(ShellError::Interrupted { span }); } let time_until_deadline = deadline.saturating_duration_since(Instant::now()); let time_to_sleep = time_until_deadline.min(CTRL_C_CHECK_INTERVAL); match mailbox.recv_timeout(tag, time_to_sleep) { Ok(value) => return Ok(value), Err(RecvTimeoutError::Timeout) => {} // try again Err(RecvTimeoutError::Disconnected) => return Err(ShellError::Interrupted { span }), } if time_until_deadline.is_zero() { return Err(JobError::RecvTimeout { span }.into()); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_kill.rs
crates/nu-command/src/experimental/job_kill.rs
use nu_engine::command_prelude::*; use nu_protocol::JobId; #[derive(Clone)] pub struct JobKill; impl Command for JobKill { fn name(&self) -> &str { "job kill" } fn description(&self) -> &str { "Kill a background job." } fn signature(&self) -> nu_protocol::Signature { Signature::build("job kill") .category(Category::Experimental) .required("id", SyntaxShape::Int, "The id of the job to kill.") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) } fn search_terms(&self) -> Vec<&str> { vec!["halt", "stop", "end", "close"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let id_arg: Spanned<usize> = call.req(engine_state, stack, 0)?; let id = JobId::new(id_arg.item); let mut jobs = engine_state.jobs.lock().expect("jobs lock is poisoned!"); if jobs.lookup(id).is_none() { return Err(JobError::NotFound { span: head, id }.into()); } jobs.kill_and_remove(id).map_err(|err| { ShellError::Io(IoError::new_internal( err, "Failed to kill the requested job", nu_protocol::location!(), )) })?; Ok(Value::nothing(head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "let id = job spawn { sleep 10sec }; job kill $id", description: "Kill a newly spawned job", result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_unfreeze.rs
crates/nu-command/src/experimental/job_unfreeze.rs
use nu_engine::command_prelude::*; use nu_protocol::{ JobId, engine::{FrozenJob, Job, ThreadJob}, process::check_ok, }; use nu_system::{ForegroundWaitStatus, kill_by_pid}; #[derive(Clone)] pub struct JobUnfreeze; impl Command for JobUnfreeze { fn name(&self) -> &str { "job unfreeze" } fn description(&self) -> &str { "Unfreeze a frozen process job in foreground." } fn signature(&self) -> nu_protocol::Signature { Signature::build("job unfreeze") .category(Category::Experimental) .optional("id", SyntaxShape::Int, "The process id to unfreeze.") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) } fn search_terms(&self) -> Vec<&str> { vec!["fg"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let mut jobs = engine_state.jobs.lock().expect("jobs lock is poisoned!"); let id: Option<usize> = call.opt(engine_state, stack, 0)?; let id = id .map(JobId::new) .or_else(|| jobs.most_recent_frozen_job_id()) .ok_or(JobError::NoneToUnfreeze { span: head })?; let job = match jobs.lookup(id) { None => return Err(JobError::NotFound { span: head, id }.into()), Some(Job::Thread(ThreadJob { .. })) => { return Err(JobError::CannotUnfreeze { span: head, id }.into()); } Some(Job::Frozen(FrozenJob { .. })) => jobs .remove_job(id) .expect("job was supposed to be in job list"), }; drop(jobs); unfreeze_job(engine_state, id, job, head)?; Ok(Value::nothing(head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "job unfreeze", description: "Unfreeze the latest frozen job", result: None, }, Example { example: "job unfreeze 4", description: "Unfreeze a specific frozen job by its PID", result: None, }, ] } fn extra_description(&self) -> &str { r#"When a running process is frozen (with the SIGTSTP signal or with the Ctrl-Z key on unix), a background job gets registered for this process, which can then be resumed using this command."# } } fn unfreeze_job( state: &EngineState, old_id: JobId, job: Job, span: Span, ) -> Result<(), ShellError> { match job { Job::Thread(ThreadJob { .. }) => Err(JobError::CannotUnfreeze { span, id: old_id }.into()), Job::Frozen(FrozenJob { unfreeze: handle, tag, }) => { let pid = handle.pid(); if let Some(thread_job) = &state.current_thread_job() && !thread_job.try_add_pid(pid) { kill_by_pid(pid.into()).map_err(|err| { ShellError::Io(IoError::new_internal( err, "job was interrupted; could not kill foreground process", nu_protocol::location!(), )) })?; } let result = handle.unfreeze( state .is_interactive .then(|| state.pipeline_externals_state.clone()), ); if let Some(thread_job) = &state.current_thread_job() { thread_job.remove_pid(pid); } match result { Ok(ForegroundWaitStatus::Frozen(handle)) => { let mut jobs = state.jobs.lock().expect("jobs lock is poisoned!"); jobs.add_job_with_id( old_id, Job::Frozen(FrozenJob { unfreeze: handle, tag, }), ) .expect("job was supposed to be removed"); if state.is_interactive { println!("\nJob {} is re-frozen", old_id.get()); } Ok(()) } Ok(ForegroundWaitStatus::Finished(status)) => check_ok(status, false, span), Err(err) => Err(ShellError::Io(IoError::new_internal( err, "Failed to unfreeze foreground process", nu_protocol::location!(), ))), } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_tag.rs
crates/nu-command/src/experimental/job_tag.rs
use nu_engine::command_prelude::*; use nu_protocol::JobId; #[derive(Clone)] pub struct JobTag; impl Command for JobTag { fn name(&self) -> &str { "job tag" } fn description(&self) -> &str { "Add a description tag to a background job." } fn signature(&self) -> nu_protocol::Signature { Signature::build("job tag") .category(Category::Experimental) .required("id", SyntaxShape::Int, "The id of the job to tag.") .required( "tag", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), "The tag to assign to the job.", ) .input_output_types(vec![(Type::Nothing, Type::Nothing)]) } fn search_terms(&self) -> Vec<&str> { vec!["describe", "desc"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let id_arg: Spanned<usize> = call.req(engine_state, stack, 0)?; let id = JobId::new(id_arg.item); let tag: Option<String> = call.req(engine_state, stack, 1)?; let mut jobs = engine_state.jobs.lock().expect("jobs lock is poisoned!"); match jobs.lookup_mut(id) { None => return Err(JobError::NotFound { span: head, id }.into()), Some(job) => job.assign_tag(tag), } Ok(Value::nothing(head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "let id = job spawn { sleep 10sec }; job tag $id abc ", description: "Tag a newly spawned job", result: None, }, Example { example: "let id = job spawn { sleep 10sec }; job tag $id abc; job tag $id null", description: "Remove the tag of a job", result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/mod.rs
crates/nu-command/src/experimental/mod.rs
mod is_admin; mod job; mod job_id; mod job_kill; mod job_list; mod job_spawn; mod job_tag; #[cfg(all(unix, feature = "os"))] mod job_unfreeze; #[cfg(not(target_family = "wasm"))] mod job_flush; #[cfg(not(target_family = "wasm"))] mod job_recv; #[cfg(not(target_family = "wasm"))] mod job_send; pub use is_admin::IsAdmin; pub use job::Job; pub use job_id::JobId; pub use job_kill::JobKill; pub use job_list::JobList; pub use job_spawn::JobSpawn; pub use job_tag::JobTag; #[cfg(not(target_family = "wasm"))] pub use job_flush::JobFlush; #[cfg(not(target_family = "wasm"))] pub use job_recv::JobRecv; #[cfg(not(target_family = "wasm"))] pub use job_send::JobSend; #[cfg(all(unix, feature = "os"))] pub use job_unfreeze::JobUnfreeze;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_flush.rs
crates/nu-command/src/experimental/job_flush.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::FilterTag; #[derive(Clone)] pub struct JobFlush; impl Command for JobFlush { fn name(&self) -> &str { "job flush" } fn description(&self) -> &str { "Clear this job's mailbox." } fn extra_description(&self) -> &str { r#" This command removes all messages in the mailbox of the current job. If a message is received while this command is executing, it may also be discarded. "# } fn signature(&self) -> nu_protocol::Signature { Signature::build("job flush") .category(Category::Experimental) .named( "tag", SyntaxShape::Int, "Clear messages with this tag", None, ) .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) } fn search_terms(&self) -> Vec<&str> { vec![] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let tag_arg: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "tag")?; if let Some(tag) = tag_arg && tag.item < 0 { return Err(ShellError::NeedsPositiveValue { span: tag.span }); } let tag_arg = tag_arg.map(|it| it.item as FilterTag); let mut mailbox = engine_state .current_job .mailbox .lock() .expect("failed to acquire lock"); if tag_arg.is_some() { while mailbox.try_recv(tag_arg).is_ok() {} } else { mailbox.clear(); } Ok(Value::nothing(call.head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "job flush", description: "Clear the mailbox of the current job.", result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_send.rs
crates/nu-command/src/experimental/job_send.rs
use nu_engine::command_prelude::*; use nu_protocol::{JobId, engine::FilterTag}; #[derive(Clone)] pub struct JobSend; impl Command for JobSend { fn name(&self) -> &str { "job send" } fn description(&self) -> &str { "Send a message to the mailbox of a job." } fn extra_description(&self) -> &str { r#" This command sends a message to a background job, which can then read sent messages in a first-in-first-out fashion with `job recv`. When it does so, it may additionally specify a numeric filter tag, in which case it will only read messages sent with the exact same filter tag. In particular, the id 0 refers to the main/initial nushell thread. A message can be any nushell value, and streams are always collected before being sent. This command never blocks. "# } fn signature(&self) -> nu_protocol::Signature { Signature::build("job send") .category(Category::Experimental) .required( "id", SyntaxShape::Int, "The id of the job to send the message to.", ) .named("tag", SyntaxShape::Int, "A tag for the message", None) .input_output_types(vec![(Type::Any, Type::Nothing)]) .allow_variants_without_examples(true) } fn search_terms(&self) -> Vec<&str> { vec![] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let id_arg: Spanned<usize> = call.req(engine_state, stack, 0)?; let tag_arg: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "tag")?; let id = JobId::new(id_arg.item); if let Some(tag) = tag_arg && tag.item < 0 { return Err(ShellError::NeedsPositiveValue { span: tag.span }); } let tag = tag_arg.map(|it| it.item as FilterTag); if id == JobId::ZERO { engine_state .root_job_sender .send((tag, input)) .expect("this should NEVER happen."); } else { let jobs = engine_state.jobs.lock().expect("failed to acquire lock"); if let Some(job) = jobs.lookup(id) { match job { nu_protocol::engine::Job::Thread(thread_job) => { // it is ok to send this value while holding the lock, because // mail channels are always unbounded, so this send never blocks let _ = thread_job.sender.send((tag, input)); } nu_protocol::engine::Job::Frozen(_) => { return Err(JobError::AlreadyFrozen { span: id_arg.span, id, } .into()); } } } else { return Err(JobError::NotFound { span: id_arg.span, id, } .into()); } } Ok(Value::nothing(head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "let id = job spawn { job recv | save sent.txt }; 'hi' | job send $id", description: "Send a message from the main thread to a newly-spawned job", result: None, }, Example { example: "job spawn { sleep 1sec; 'hi' | job send 0 }; job recv", description: "Send a message from a newly-spawned job to the main thread (which always has an ID of 0)", result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_spawn.rs
crates/nu-command/src/experimental/job_spawn.rs
use std::{ sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU32}, mpsc, }, thread, }; use nu_engine::{ClosureEvalOnce, command_prelude::*}; use nu_protocol::{ OutDest, Signals, engine::{Closure, CurrentJob, Job, Mailbox, Redirection, ThreadJob}, report_shell_error, }; #[derive(Clone)] pub struct JobSpawn; impl Command for JobSpawn { fn name(&self) -> &str { "job spawn" } fn description(&self) -> &str { "Spawn a background job and retrieve its ID." } fn signature(&self) -> nu_protocol::Signature { Signature::build("job spawn") .category(Category::Experimental) .input_output_types(vec![(Type::Nothing, Type::Int)]) .named( "tag", SyntaxShape::String, "An optional description tag for this job", Some('t'), ) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run in another thread.", ) } fn search_terms(&self) -> Vec<&str> { vec!["background", "bg", "&"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let closure: Closure = call.req(engine_state, stack, 0)?; let tag: Option<String> = call.get_flag(engine_state, stack, "tag")?; let job_stack = stack.clone(); let mut job_state = engine_state.clone(); job_state.is_interactive = false; // the new job should have its ctrl-c independent of foreground let job_signals = Signals::new(Arc::new(AtomicBool::new(false))); job_state.set_signals(job_signals.clone()); // the new job has a separate process group state for its processes job_state.pipeline_externals_state = Arc::new((AtomicU32::new(0), AtomicU32::new(0))); job_state.exit_warning_given = Arc::new(AtomicBool::new(false)); let jobs = job_state.jobs.clone(); let mut jobs = jobs.lock().expect("jobs lock is poisoned!"); let (send, recv) = mpsc::channel(); let id = { let thread_job = ThreadJob::new(job_signals, tag, send); let id = jobs.add_job(Job::Thread(thread_job.clone())); job_state.current_job = CurrentJob { id, background_thread_job: Some(thread_job), mailbox: Arc::new(Mutex::new(Mailbox::new(recv))), }; id }; let result = thread::Builder::new() .name(format!("background job {}", id.get())) .spawn(move || { let mut stack = job_stack.reset_pipes(); let stack = stack.push_redirection( Some(Redirection::Pipe(OutDest::Null)), Some(Redirection::Pipe(OutDest::Null)), ); ClosureEvalOnce::new_preserve_out_dest(&job_state, &stack, closure) .run_with_input(Value::nothing(head).into_pipeline_data()) .and_then(|data| data.drain()) .unwrap_or_else(|err| { if !job_state.signals().interrupted() { report_shell_error(None, &job_state, &err); } }); { let mut jobs = job_state.jobs.lock().expect("jobs lock is poisoned!"); jobs.remove_job(id); } }); match result { Ok(_) => Ok(Value::int(id.get() as i64, head).into_pipeline_data()), Err(err) => { jobs.remove_job(id); Err(ShellError::Io(IoError::new_with_additional_context( err, call.head, None, "Failed to spawn thread for job", ))) } } } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "job spawn { sleep 5sec; rm evidence.pdf }", description: "Spawn a background job to do some time consuming work", result: None, }] } fn extra_description(&self) -> &str { r#"Executes the provided closure in a background thread and registers this task in the background job table, which can be retrieved with `job list`. This command returns the job id of the newly created job. "# } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job.rs
crates/nu-command/src/experimental/job.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Job; impl Command for Job { fn name(&self) -> &str { "job" } fn signature(&self) -> Signature { Signature::build("job") .category(Category::Experimental) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for working with background jobs." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/job_list.rs
crates/nu-command/src/experimental/job_list.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::{FrozenJob, Job}; #[derive(Clone)] pub struct JobList; impl Command for JobList { fn name(&self) -> &str { "job list" } fn description(&self) -> &str { "List background jobs." } fn signature(&self) -> nu_protocol::Signature { Signature::build("job list") .category(Category::Experimental) .input_output_types(vec![(Type::Nothing, Type::table())]) } fn search_terms(&self) -> Vec<&str> { vec!["background", "jobs"] } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let jobs = engine_state.jobs.lock().expect("jobs lock is poisoned!"); let values = jobs .iter() .map(|(id, job)| { let mut record = record! { "id" => Value::int(id.get() as i64, head), "type" => match job { Job::Thread(_) => Value::string("thread", head), Job::Frozen(_) => Value::string("frozen", head), }, "pids" => match job { Job::Thread(job) => Value::list( job.collect_pids() .into_iter() .map(|it| Value::int(it as i64, head)) .collect::<Vec<Value>>(), head, ), Job::Frozen(FrozenJob { unfreeze, .. }) => { Value::list(vec![ Value::int(unfreeze.pid() as i64, head) ], head) } }, }; if let Some(tag) = job.tag() { record.push("tag", Value::string(tag, head)); } Value::record(record, head) }) .collect::<Vec<Value>>(); Ok(Value::list(values, head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "job list", description: "List all background jobs", result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/experimental/is_admin.rs
crates/nu-command/src/experimental/is_admin.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct IsAdmin; impl Command for IsAdmin { fn name(&self) -> &str { "is-admin" } fn description(&self) -> &str { "Check if nushell is running with administrator or root privileges." } fn signature(&self) -> nu_protocol::Signature { Signature::build("is-admin") .category(Category::Core) .input_output_types(vec![(Type::Nothing, Type::Bool)]) .allow_variants_without_examples(true) } fn search_terms(&self) -> Vec<&str> { vec!["root", "administrator", "superuser", "supervisor"] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::bool(is_root(), call.head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Return 'iamroot' if nushell is running with admin/root privileges, and 'iamnotroot' if not.", example: r#"if (is-admin) { "iamroot" } else { "iamnotroot" }"#, result: Some(Value::test_string("iamnotroot")), }] } } /// Returns `true` if user is root; `false` otherwise fn is_root() -> bool { is_root_impl() } #[cfg(unix)] fn is_root_impl() -> bool { nix::unistd::Uid::current().is_root() } #[cfg(windows)] fn is_root_impl() -> bool { use windows::Win32::{ Foundation::{CloseHandle, HANDLE}, Security::{GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation}, System::Threading::{GetCurrentProcess, OpenProcessToken}, }; let mut elevated = false; // Checks whether the access token associated with the current process has elevated privileges. // SAFETY: `elevated` only touched by safe code. // `handle` lives long enough, initialized, mutated, used and closed with validity check. // `elevation` only read on success and passed with correct `size`. unsafe { let mut handle = HANDLE::default(); // Opens the access token associated with the current process. if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle).is_ok() { let mut elevation = TOKEN_ELEVATION::default(); let mut size = std::mem::size_of::<TOKEN_ELEVATION>() as u32; // Retrieves elevation token information about the access token associated with the current process. // Call available since XP // https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation if GetTokenInformation( handle, TokenElevation, Some(&mut elevation as *mut TOKEN_ELEVATION as *mut _), size, &mut size, ) .is_ok() { // Whether the token has elevated privileges. // Safe to read as `GetTokenInformation` will not write outside `elevation` and it succeeded // See: https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation#parameters elevated = elevation.TokenIsElevated != 0; } } if !handle.is_invalid() { // Closes the object handle. let _ = CloseHandle(handle); } } elevated } #[cfg(target_arch = "wasm32")] fn is_root_impl() -> bool { // in wasm we don't have a user system, so technically we are never root false }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/network/version_check.rs
crates/nu-command/src/network/version_check.rs
use nu_engine::command_prelude::*; use serde::Deserialize; use update_informer::{ Check, Package, Registry, Result as UpdateResult, http_client::{GenericHttpClient, HttpClient}, registry, }; #[derive(Clone)] pub struct VersionCheck; impl Command for VersionCheck { fn name(&self) -> &str { "version check" } fn description(&self) -> &str { "Checks to see if you have the latest version of nushell." } fn extra_description(&self) -> &str { "If you're running nushell nightly, `version check` will check to see if you are running the latest nightly version. If you are running the nushell release, `version check` will check to see if you're running the latest release version." } fn signature(&self) -> Signature { Signature::build("version check") .category(Category::Platform) .input_output_types(vec![(Type::Nothing, Type::record())]) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Check if you have the latest version of nushell", example: "version check", result: None, }] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let version_check = check_for_latest_nushell_version(); Ok(version_check.into_pipeline_data()) } } pub struct NuShellNightly; impl Registry for NuShellNightly { const NAME: &'static str = "nushell/nightly"; fn get_latest_version<T: HttpClient>( http_client: GenericHttpClient<T>, pkg: &Package, ) -> UpdateResult<Option<String>> { #[derive(Deserialize, Debug)] struct Response { tag_name: String, } let url = format!("https://api.github.com/repos/{pkg}/releases"); let versions = http_client .add_header("Accept", "application/vnd.github.v3+json") .add_header("User-Agent", "update-informer") .get::<Vec<Response>>(&url)?; if let Some(v) = versions.first() { // The nightly repo tags look like "0.102.0-nightly.4+23dc1b6" // We want to return the "0.102.0-nightly.4" part because hustcer // is changing the cargo.toml package.version to be that syntax let up_through_plus = match v.tag_name.split('+').next() { Some(v) => v, None => &v.tag_name, }; return Ok(Some(up_through_plus.to_string())); } Ok(None) } } pub fn check_for_latest_nushell_version() -> Value { let current_version = env!("CARGO_PKG_VERSION").to_string(); let mut rec = Record::new(); if current_version.contains("nightly") { rec.push("channel", Value::test_string("nightly")); let nightly_pkg_name = "nushell/nightly"; // The .interval() determines how long the cached check lives. Setting it to std::time::Duration::ZERO // means that there is essentially no cache and it will check for a new version each time you run nushell. // Since this is run on demand, there isn't really a need to cache the check. let informer = update_informer::new(NuShellNightly, nightly_pkg_name, current_version.clone()) .interval(std::time::Duration::ZERO); if let Ok(Some(new_version)) = informer.check_version() { rec.push("current", Value::test_bool(false)); rec.push("latest", Value::test_string(format!("{new_version}"))); Value::test_record(rec) } else { rec.push("current", Value::test_bool(true)); rec.push("latest", Value::test_string(current_version.clone())); Value::test_record(rec) } } else { rec.push("channel", Value::test_string("release")); let normal_pkg_name = "nushell/nushell"; // By default, this update request is cached for 24 hours so it won't check for a new version // each time you run nushell. Since this is run on demand, there isn't really a need to cache the check which // is why we set the interval to std::time::Duration::ZERO. let informer = update_informer::new(registry::GitHub, normal_pkg_name, current_version.clone()) .interval(std::time::Duration::ZERO); if let Ok(Some(new_version)) = informer.check_version() { rec.push("current", Value::test_bool(false)); rec.push("latest", Value::test_string(format!("{new_version}"))); Value::test_record(rec) } else { rec.push("current", Value::test_bool(true)); rec.push("latest", Value::test_string(current_version.clone())); Value::test_record(rec) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false