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/strings/parse.rs
crates/nu-command/src/strings/parse.rs
use fancy_regex::{Captures, Regex, RegexBuilder}; use nu_engine::command_prelude::*; use nu_protocol::{ListStream, Signals, engine::StateWorkingSet}; use std::collections::VecDeque; #[derive(Clone)] pub struct Parse; impl Command for Parse { fn name(&self) -> &str { "parse" } fn description(&self) -> &str { "Parse columns from string data using a simple pattern or a supplied regular expression." } fn search_terms(&self) -> Vec<&str> { vec!["pattern", "match", "regex", "str extract"] } fn extra_description(&self) -> &str { "The parse command always uses regular expressions even when you use a simple pattern. If a simple pattern is supplied, parse will transform that pattern into a regular expression." } fn signature(&self) -> nu_protocol::Signature { Signature::build("parse") .required("pattern", SyntaxShape::String, "The pattern to match.") .input_output_types(vec![ (Type::String, Type::table()), (Type::List(Box::new(Type::Any)), Type::table()), ]) .switch("regex", "use full regex syntax for patterns", Some('r')) .named( "backtrack", SyntaxShape::Int, "set the max backtrack limit for regex", Some('b'), ) .allow_variants_without_examples(true) .category(Category::Strings) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Parse a string into two named columns", example: "\"hi there\" | parse \"{foo} {bar}\"", result: Some(Value::test_list(vec![Value::test_record(record! { "foo" => Value::test_string("hi"), "bar" => Value::test_string("there"), })])), }, Example { description: "Parse a string, ignoring a column with _", example: "\"hello world\" | parse \"{foo} {_}\"", result: Some(Value::test_list(vec![Value::test_record(record! { "foo" => Value::test_string("hello"), })])), }, Example { description: "This is how the first example is interpreted in the source code", example: "\"hi there\" | parse --regex '(?s)\\A(?P<foo>.*?) (?P<bar>.*?)\\z'", result: Some(Value::test_list(vec![Value::test_record(record! { "foo" => Value::test_string("hi"), "bar" => Value::test_string("there"), })])), }, Example { description: "Parse a string using fancy-regex named capture group pattern", example: "\"foo bar.\" | parse --regex '\\s*(?<name>\\w+)(?=\\.)'", result: Some(Value::test_list(vec![Value::test_record(record! { "name" => Value::test_string("bar"), })])), }, Example { description: "Parse a string using fancy-regex capture group pattern", example: "\"foo! bar.\" | parse --regex '(\\w+)(?=\\.)|(\\w+)(?=!)'", result: Some(Value::test_list(vec![ Value::test_record(record! { "capture0" => Value::test_nothing(), "capture1" => Value::test_string("foo"), }), Value::test_record(record! { "capture0" => Value::test_string("bar"), "capture1" => Value::test_nothing(), }), ])), }, Example { description: "Parse a string using fancy-regex look behind pattern", example: "\" @another(foo bar) \" | parse --regex '\\s*(?<=[() ])(@\\w+)(\\([^)]*\\))?\\s*'", result: Some(Value::test_list(vec![Value::test_record(record! { "capture0" => Value::test_string("@another"), "capture1" => Value::test_string("(foo bar)"), })])), }, Example { description: "Parse a string using fancy-regex look ahead atomic group pattern", example: "\"abcd\" | parse --regex '^a(bc(?=d)|b)cd$'", result: Some(Value::test_list(vec![Value::test_record(record! { "capture0" => Value::test_string("b"), })])), }, Example { description: "Parse a string with a manually set fancy-regex backtrack limit", example: "\"hi there\" | parse --backtrack 1500000 \"{foo} {bar}\"", result: Some(Value::test_list(vec![Value::test_record(record! { "foo" => Value::test_string("hi"), "bar" => Value::test_string("there"), })])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let pattern: Spanned<String> = call.req(engine_state, stack, 0)?; let regex: bool = call.has_flag(engine_state, stack, "regex")?; let backtrack_limit: usize = call .get_flag(engine_state, stack, "backtrack")? .unwrap_or(1_000_000); // 1_000_000 is fancy_regex default operate(engine_state, pattern, regex, backtrack_limit, call, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let pattern: Spanned<String> = call.req_const(working_set, 0)?; let regex: bool = call.has_flag_const(working_set, "regex")?; let backtrack_limit: usize = call .get_flag_const(working_set, "backtrack")? .unwrap_or(1_000_000); operate( working_set.permanent(), pattern, regex, backtrack_limit, call, input, ) } } fn operate( engine_state: &EngineState, pattern: Spanned<String>, regex: bool, backtrack_limit: usize, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let pattern_item = pattern.item; let pattern_span = pattern.span; let item_to_parse = if regex { pattern_item } else { build_regex(&pattern_item, pattern_span)? }; let regex = RegexBuilder::new(&item_to_parse) .backtrack_limit(backtrack_limit) .build() .map_err(|e| ShellError::GenericError { error: "Error with regular expression".into(), msg: e.to_string(), span: Some(pattern_span), help: None, inner: vec![], })?; let columns = regex .capture_names() .skip(1) .enumerate() .map(|(i, name)| { name.map(String::from) .unwrap_or_else(|| format!("capture{i}")) }) .collect::<Vec<_>>(); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(value, ..) => match value { Value::String { val, .. } => { let captures = regex .captures_iter(&val) .map(|captures| captures_to_value(captures, &columns, head)) .collect::<Result<_, _>>()?; Ok(Value::list(captures, head).into_pipeline_data()) } Value::List { vals, .. } => { let iter = vals.into_iter().map(move |val| { let span = val.span(); let type_ = val.get_type(); val.into_string() .map_err(|_| ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: type_.to_string(), dst_span: head, src_span: span, }) }); let iter = ParseIter { captures: VecDeque::new(), regex, columns, iter, span: head, signals: engine_state.signals().clone(), }; Ok(ListStream::new(iter, head, Signals::empty()).into()) } value => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: value.get_type().to_string(), dst_span: head, src_span: value.span(), }), }, PipelineData::ListStream(stream, ..) => Ok(stream .modify(|stream| { let iter = stream.map(move |val| { let span = val.span(); val.into_string().map_err(|_| ShellError::PipelineMismatch { exp_input_type: "string".into(), dst_span: head, src_span: span, }) }); ParseIter { captures: VecDeque::new(), regex, columns, iter, span: head, signals: engine_state.signals().clone(), } }) .into()), PipelineData::ByteStream(stream, ..) => { if let Some(lines) = stream.lines() { let iter = ParseIter { captures: VecDeque::new(), regex, columns, iter: lines, span: head, signals: engine_state.signals().clone(), }; Ok(ListStream::new(iter, head, Signals::empty()).into()) } else { Ok(PipelineData::empty()) } } } } fn build_regex(input: &str, span: Span) -> Result<String, ShellError> { let mut output = "(?s)\\A".to_string(); let mut loop_input = input.chars().peekable(); loop { let mut before = String::new(); while let Some(c) = loop_input.next() { if c == '{' { // If '{{', still creating a plaintext parse command, but just for a single '{' char if loop_input.peek() == Some(&'{') { let _ = loop_input.next(); } else { break; } } before.push(c); } if !before.is_empty() { output.push_str(&fancy_regex::escape(&before)); } // Look for column as we're now at one let mut column = String::new(); while let Some(c) = loop_input.next() { if c == '}' { break; } column.push(c); if loop_input.peek().is_none() { return Err(ShellError::DelimiterError { msg: "Found opening `{` without an associated closing `}`".to_owned(), span, }); } } if !column.is_empty() { output.push_str("(?"); if column == "_" { // discard placeholder column(s) output.push(':'); } else { // create capture group for column output.push_str("P<"); output.push_str(&column); output.push('>'); } output.push_str(".*?)"); } if before.is_empty() && column.is_empty() { break; } } output.push_str("\\z"); Ok(output) } struct ParseIter<I: Iterator<Item = Result<String, ShellError>>> { captures: VecDeque<Value>, regex: Regex, columns: Vec<String>, iter: I, span: Span, signals: Signals, } impl<I: Iterator<Item = Result<String, ShellError>>> ParseIter<I> { fn populate_captures(&mut self, str: &str) -> Result<(), ShellError> { for captures in self.regex.captures_iter(str) { self.captures .push_back(captures_to_value(captures, &self.columns, self.span)?); } Ok(()) } } impl<I: Iterator<Item = Result<String, ShellError>>> Iterator for ParseIter<I> { type Item = Value; fn next(&mut self) -> Option<Value> { loop { if self.signals.interrupted() { return None; } if let Some(val) = self.captures.pop_front() { return Some(val); } let result = self .iter .next()? .and_then(|str| self.populate_captures(&str)); if let Err(err) = result { return Some(Value::error(err, self.span)); } } } } fn captures_to_value( captures: Result<Captures, fancy_regex::Error>, columns: &[String], span: Span, ) -> Result<Value, ShellError> { let captures = captures.map_err(|err| ShellError::GenericError { error: "Error with regular expression captures".into(), msg: err.to_string(), span: Some(span), help: None, inner: vec![], })?; let record = columns .iter() .zip(captures.iter().skip(1)) .map(|(column, match_)| { let match_value = match_ .map(|m| Value::string(m.as_str(), span)) .unwrap_or(Value::nothing(span)); (column.clone(), match_value) }) .collect(); Ok(Value::record(record, span)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { crate::test_examples(Parse) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/mod.rs
crates/nu-command/src/strings/mod.rs
mod ansi; mod base; mod char_; mod detect; mod detect_columns; mod detect_type; mod encode_decode; mod format; mod guess_width; mod parse; mod split; mod str_; pub use ansi::{Ansi, AnsiLink, AnsiStrip}; pub use base::{ DecodeBase32, DecodeBase32Hex, DecodeBase64, DecodeHex, EncodeBase32, EncodeBase32Hex, EncodeBase64, EncodeHex, }; pub use char_::Char; pub use detect::Detect; pub use detect_columns::*; pub use detect_type::*; pub use encode_decode::*; pub use format::*; pub use parse::*; pub use split::*; pub use str_::*; use nu_engine::CallExt; use nu_protocol::{ ShellError, engine::{Call, EngineState, Stack, StateWorkingSet}, }; // For handling the grapheme_cluster related flags on some commands. // This ensures the error messages are consistent. pub fn grapheme_flags( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<bool, ShellError> { let g_flag = call.has_flag(engine_state, stack, "grapheme-clusters")?; // Check for the other flags and produce errors if they exist. // Note that Nushell already prevents nonexistent flags from being used with commands, // so this function can be reused for both the --utf-8-bytes commands and the --code-points commands. if g_flag && call.has_flag(engine_state, stack, "utf-8-bytes")? { Err(ShellError::IncompatibleParametersSingle { msg: "Incompatible flags: --grapheme-clusters (-g) and --utf-8-bytes (-b)".to_string(), span: call.head, })? } if g_flag && call.has_flag(engine_state, stack, "code-points")? { Err(ShellError::IncompatibleParametersSingle { msg: "Incompatible flags: --grapheme-clusters (-g) and --code-points (-c)".to_string(), span: call.head, })? } if g_flag && call.has_flag(engine_state, stack, "chars")? { Err(ShellError::IncompatibleParametersSingle { msg: "Incompatible flags: --grapheme-clusters (-g) and --chars (-c)".to_string(), span: call.head, })? } // Grapheme cluster usage is decided by the non-default -g flag Ok(g_flag) } // Const version of grapheme_flags pub fn grapheme_flags_const( working_set: &StateWorkingSet, call: &Call, ) -> Result<bool, ShellError> { let g_flag = call.has_flag_const(working_set, "grapheme-clusters")?; if g_flag && call.has_flag_const(working_set, "utf-8-bytes")? { Err(ShellError::IncompatibleParametersSingle { msg: "Incompatible flags: --grapheme-clusters (-g) and --utf-8-bytes (-b)".to_string(), span: call.head, })? } if g_flag && call.has_flag_const(working_set, "code-points")? { Err(ShellError::IncompatibleParametersSingle { msg: "Incompatible flags: --grapheme-clusters (-g) and --utf-8-bytes (-b)".to_string(), span: call.head, })? } Ok(g_flag) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/guess_width.rs
crates/nu-command/src/strings/guess_width.rs
/// Attribution: https://github.com/noborus/guesswidth/blob/main/guesswidth.go /// The MIT License (MIT) as of 2024-03-22 /// /// GuessWidth handles the format as formatted by printf. /// Spaces exist as delimiters, but spaces are not always delimiters. /// The width seems to be a fixed length, but it doesn't always fit. /// GuessWidth finds the column separation position /// from the reference line(header) and multiple lines(body). /// /// Briefly, the algorithm uses a histogram of spaces to find widths. /// blanks, lines, and pos are variables used in the algorithm. The other /// items names below are just for reference. /// blanks = 0000003000113333111100003000 /// lines = " PID TTY TIME CMD" /// "302965 pts/3 00:00:11 zsh" /// "709737 pts/3 00:00:00 ps" /// /// measure= "012345678901234567890123456789" /// spaces = " ^ ^ ^" /// pos = 6 15 24 <- the carets show these positions /// the items in pos map to 3's in the blanks array /// /// Now that we have pos, we can let split() use this pos array to figure out /// how to split all lines by comparing each index to see if there's a space. /// So, it looks at position 6, 15, 24 and sees if it has a space in those /// positions. If it does, it splits the line there. If it doesn't, it wiggles /// around the position to find the next space and splits there. use std::io::{self, BufRead}; use unicode_width::UnicodeWidthStr; /// the number to scan to analyze. const SCAN_NUM: u8 = 128; /// the minimum number of lines to recognize as a separator. /// 1 if only the header, 2 or more if there is a blank in the body. const MIN_LINES: usize = 2; /// whether to trim the space in the value. const TRIM_SPACE: bool = true; /// the base line number. It starts from 0. const HEADER: usize = 0; /// GuessWidth reads records from printf-like output. pub struct GuessWidth { pub(crate) reader: io::BufReader<Box<dyn io::Read>>, // a list of separator positions. pub(crate) pos: Vec<usize>, // stores the lines read for scan. pub(crate) pre_lines: Vec<String>, // the number returned by read. pub(crate) pre_count: usize, // the maximum number of columns to split. pub(crate) limit_split: usize, } impl GuessWidth { pub fn new_reader(r: Box<dyn io::Read>) -> GuessWidth { let reader = io::BufReader::new(r); GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, } } /// read_all reads all rows /// and returns a two-dimensional slice of rows and columns. pub fn read_all(&mut self) -> Vec<Vec<String>> { if self.pre_lines.is_empty() { self.scan(SCAN_NUM); } let mut rows = Vec::new(); while let Ok(columns) = self.read() { if !columns.is_empty() { rows.push(columns); } } rows } /// scan preReads and parses the lines. fn scan(&mut self, num: u8) { for _ in 0..num { let mut buf = String::new(); if self.reader.read_line(&mut buf).unwrap_or(0) == 0 { break; } let line = buf.trim_end().to_string(); self.pre_lines.push(line); } self.pos = positions(&self.pre_lines, HEADER, MIN_LINES); if self.limit_split > 0 && self.pos.len() > self.limit_split { self.pos.truncate(self.limit_split); } } /// read reads one row and returns a slice of columns. /// scan is executed first if it is not preRead. fn read(&mut self) -> Result<Vec<String>, io::Error> { if self.pre_lines.is_empty() { self.scan(SCAN_NUM); } if self.pre_count < self.pre_lines.len() { let line = &self.pre_lines[self.pre_count]; self.pre_count += 1; Ok(split(line, &self.pos, TRIM_SPACE)) } else { let mut buf = String::new(); if self.reader.read_line(&mut buf)? == 0 { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "End of file")); } let line = buf.trim_end().to_string(); Ok(split(&line, &self.pos, TRIM_SPACE)) } } } // positions returns separator positions // from multiple lines and header line number. // Lines before the header line are ignored. fn positions(lines: &[String], header: usize, min_lines: usize) -> Vec<usize> { let mut blanks = Vec::new(); for (n, line) in lines.iter().enumerate() { if n < header { continue; } if n == header { blanks = lookup_blanks(line.trim_end_matches(' ')); continue; } count_blanks(&mut blanks, line.trim_end_matches(' ')); } positions_helper(&blanks, min_lines) } fn separator_position(lr: &[char], p: usize, pos: &[usize], n: usize) -> usize { if lr[p].is_whitespace() { return p; } let mut f = p; while f < lr.len() && !lr[f].is_whitespace() { f += 1; } let mut b = p; while b > 0 && !lr[b].is_whitespace() { b -= 1; } if b == pos[n] { return f; } if n < pos.len() - 1 { if f == pos[n + 1] { return b; } if b == pos[n] { return f; } if b > pos[n] && b < pos[n + 1] { return b; } } f } fn split(line: &str, pos: &[usize], trim_space: bool) -> Vec<String> { let mut n = 0; let mut start_char = 0; let mut columns = Vec::with_capacity(pos.len() + 1); let (line_char_boundaries, line_chars): (Vec<usize>, Vec<char>) = line.char_indices().unzip(); let mut w = 0; if line_chars.is_empty() || line_chars.iter().all(|&c| c.is_whitespace()) { // current line is completely empty, or only filled with whitespace return Vec::new(); } else if !pos.is_empty() && line_chars.iter().all(|&c| !c.is_whitespace()) && pos[0] < UnicodeWidthStr::width(line) { // we have more than 1 column in the input, but the current line has no whitespace, // and it is longer than the first detected column separation position // this indicates some kind of decoration line. let's skip it return Vec::new(); } for p in 0..line_char_boundaries.len() { if pos.is_empty() || n > pos.len() - 1 { start_char = p; break; } if pos[n] <= w { let end_char = separator_position(&line_chars, p, pos, n); if start_char > end_char || end_char >= line_char_boundaries.len() { break; } let col = &line[line_char_boundaries[start_char]..line_char_boundaries[end_char]]; let col = if trim_space { col.trim() } else { col }; columns.push(col.to_string()); n += 1; start_char = end_char; } w += UnicodeWidthStr::width(line_chars[p].to_string().as_str()); } // add last part. let col = &line[line_char_boundaries[start_char]..]; let col = if trim_space { col.trim() } else { col }; columns.push(col.to_string()); columns } // Creates a blank(1) and non-blank(0) slice. // Execute for the base line (header line). fn lookup_blanks(line: &str) -> Vec<usize> { let mut blanks = Vec::new(); let mut first = true; for c in line.chars() { if c == ' ' { if first { blanks.push(0); continue; } blanks.push(1); continue; } first = false; blanks.push(0); if UnicodeWidthStr::width(c.to_string().as_str()) == 2 { blanks.push(0); } } blanks } // count up if the line is blank where the reference line was blank. fn count_blanks(blanks: &mut [usize], line: &str) { let mut n = 0; for c in line.chars() { if n >= blanks.len() { break; } if c == ' ' && blanks[n] > 0 { blanks[n] += 1; } n += 1; if UnicodeWidthStr::width(c.to_string().as_str()) == 2 { n += 1; } } } // Generates a list of separator positions from a blank slice. fn positions_helper(blanks: &[usize], min_lines: usize) -> Vec<usize> { let mut max = min_lines; let mut p = 0; let mut pos = Vec::new(); for (n, v) in blanks.iter().enumerate() { if *v >= max { max = *v; p = n; } if *v == 0 { max = min_lines; if p > 0 { pos.push(p); p = 0; } } } pos } #[cfg(test)] mod tests { use super::*; /// to_rows returns rows separated by columns. fn to_rows(lines: Vec<String>, pos: Vec<usize>, trim_space: bool) -> Vec<Vec<String>> { let mut rows: Vec<Vec<String>> = Vec::with_capacity(lines.len()); for line in lines { let columns = split(&line, &pos, trim_space); rows.push(columns); } rows } /// to_table parses a slice of lines and returns a table. pub fn to_table(lines: Vec<String>, header: usize, trim_space: bool) -> Vec<Vec<String>> { let pos = positions(&lines, header, 2); to_rows(lines, pos, trim_space) } /// to_table_n parses a slice of lines and returns a table, but limits the number of splits. pub fn to_table_n( lines: Vec<String>, header: usize, num_split: usize, trim_space: bool, ) -> Vec<Vec<String>> { let mut pos = positions(&lines, header, 2); if pos.len() > num_split { pos.truncate(num_split); } to_rows(lines, pos, trim_space) } #[test] fn test_guess_width_ps_trim() { let input = " PID TTY TIME CMD 302965 pts/3 00:00:11 zsh 709737 pts/3 00:00:00 ps"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; #[rustfmt::skip] let want = vec![ vec!["PID", "TTY", "TIME", "CMD"], vec!["302965", "pts/3", "00:00:11", "zsh"], vec!["709737", "pts/3", "00:00:00", "ps"], ]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_ps_overflow_trim() { let input = "USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 168576 13788 ? Ss Mar11 0:49 /sbin/init splash noborus 703052 2.1 0.7 1184814400 230920 ? Sl 10:03 0:45 /opt/google/chrome/chrome noborus 721971 0.0 0.0 13716 3524 pts/3 R+ 10:39 0:00 ps aux"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; #[rustfmt::skip] let want = vec![ vec!["USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND"], vec!["root", "1", "0.0", "0.0", "168576", "13788", "?", "Ss", "Mar11", "0:49", "/sbin/init splash"], vec!["noborus", "703052", "2.1", "0.7", "1184814400", "230920", "?", "Sl", "10:03", "0:45", "/opt/google/chrome/chrome"], vec!["noborus", "721971", "0.0", "0.0", "13716", "3524", "pts/3", "R+", "10:39", "0:00", "ps aux"], ]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_ps_limit_trim() { let input = " PID TTY TIME CMD 302965 pts/3 00:00:11 zsh 709737 pts/3 00:00:00 ps"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 2, }; #[rustfmt::skip] let want = vec![ vec!["PID", "TTY", "TIME CMD"], vec!["302965", "pts/3", "00:00:11 zsh"], vec!["709737", "pts/3", "00:00:00 ps"], ]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_windows_df_trim() { let input = "Filesystem 1K-blocks Used Available Use% Mounted on C:/Apps/Git 998797308 869007000 129790308 88% / D: 104792064 17042676 87749388 17% /d"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; #[rustfmt::skip] let want = vec![ vec!["Filesystem","1K-blocks","Used","Available","Use%","Mounted on"], vec!["C:/Apps/Git","998797308","869007000","129790308","88%","/"], vec!["D:","104792064","17042676","87749388","17%","/d"], ]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_multibyte() { let input = "A… B\nC… D"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![vec!["A…", "B"], vec!["C…", "D"]]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_combining_diacritical_marks() { let input = "Name Surname Ștefan Țincu "; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![vec!["Name", "Surname"], vec!["Ștefan", "Țincu"]]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_single_column() { let input = "A B C"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![vec!["A"], vec!["B"], vec!["C"]]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_row_without_whitespace() { let input = "A B C D ------- E F G H"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![vec!["A", "B", "C", "D"], vec!["E", "F", "G", "H"]]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_row_with_single_column() { let input = "A B C D E F G H I"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![ vec!["A", "B", "C", "D"], vec!["E"], vec!["F", "G", "H", "I"], ]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_empty_row() { let input = "A B C D E F G H"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![vec!["A", "B", "C", "D"], vec!["E", "F", "G", "H"]]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_width_row_with_only_whitespace() { let input = "A B C D E F G H"; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let want = vec![vec!["A", "B", "C", "D"], vec!["E", "F", "G", "H"]]; let got = guess_width.read_all(); assert_eq!(got, want); } #[test] fn test_guess_no_panic_for_some_cases() { let input = r#"nu_plugin_highlight = '1.2.2+0.97.1' # A nushell plugin for syntax highlighting trace_nu_plugin = '0.3.1' # A wrapper to trace Nu plugins nu_plugin_bash_env = '0.13.0' # Nu plugin bash-env nu_plugin_from_sse = '0.4.0' # Nushell plugin to convert a HTTP server sent event stream to structured data ... and 90 crates more (use --limit N to see more)"#; let r = Box::new(std::io::BufReader::new(input.as_bytes())) as Box<dyn std::io::Read>; let reader = std::io::BufReader::new(r); let mut guess_width = GuessWidth { reader, pos: Vec::new(), pre_lines: Vec::new(), pre_count: 0, limit_split: 0, }; let first_column_want = [ "nu_plugin_highlight = '1.2.2+0.97.1'", "trace_nu_plugin = '0.3.1'", "nu_plugin_bash_env = '0.13.0'", "nu_plugin_from_sse = '0.4.0'", "... and 90 crates more (use --limit N", ]; let got = guess_width.read_all(); for (row_index, row) in got.into_iter().enumerate() { assert_eq!(row[0], first_column_want[row_index]); } } #[test] fn test_to_table() { let lines = vec![ " PID TTY TIME CMD".to_string(), "302965 pts/3 00:00:11 zsh".to_string(), "709737 pts/3 00:00:00 ps".to_string(), ]; let want = vec![ vec!["PID", "TTY", "TIME", "CMD"], vec!["302965", "pts/3", "00:00:11", "zsh"], vec!["709737", "pts/3", "00:00:00", "ps"], ]; let header = 0; let trim_space = true; let table = to_table(lines, header, trim_space); assert_eq!(table, want); } #[test] fn test_to_table_n() { let lines = vec![ "2022-12-21T09:50:16+0000 WARN A warning that should be ignored is usually at this level and should be actionable.".to_string(), "2022-12-21T09:50:17+0000 INFO This is less important than debug log and is often used to provide context in the current task.".to_string(), ]; let want = vec![ vec![ "2022-12-21T09:50:16+0000", "WARN", "A warning that should be ignored is usually at this level and should be actionable.", ], vec![ "2022-12-21T09:50:17+0000", "INFO", "This is less important than debug log and is often used to provide context in the current task.", ], ]; let header = 0; let trim_space = true; let num_split = 2; let table = to_table_n(lines, header, num_split, trim_space); assert_eq!(table, want); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/char_.rs
crates/nu-command/src/strings/char_.rs
use indexmap::{IndexMap, indexmap}; use nu_engine::command_prelude::*; use nu_protocol::Signals; use std::collections::HashSet; use std::sync::LazyLock; // Character used to separate directories in a Path Environment variable on windows is ";" #[cfg(target_family = "windows")] const ENV_PATH_SEPARATOR_CHAR: char = ';'; // Character used to separate directories in a Path Environment variable on linux/mac/unix is ":" #[cfg(not(target_family = "windows"))] const ENV_PATH_SEPARATOR_CHAR: char = ':'; // Character used to separate directories in a Path Environment variable on windows is ";" #[cfg(target_family = "windows")] const LINE_SEPARATOR_CHAR: &str = "\r\n"; // Character used to separate directories in a Path Environment variable on linux/mac/unix is ":" #[cfg(not(target_family = "windows"))] const LINE_SEPARATOR_CHAR: char = '\n'; #[derive(Clone)] pub struct Char; static CHAR_MAP: LazyLock<IndexMap<&'static str, String>> = LazyLock::new(|| { indexmap! { // These are some regular characters that either can't be used or // it's just easier to use them like this. "nul" => '\x00'.to_string(), // nul character, 0x00 "null_byte" => '\x00'.to_string(), // nul character, 0x00 "zero_byte" => '\x00'.to_string(), // nul character, 0x00 // This are the "normal" characters section "newline" => '\n'.to_string(), "enter" => '\n'.to_string(), "nl" => '\n'.to_string(), "line_feed" => '\n'.to_string(), "lf" => '\n'.to_string(), "carriage_return" => '\r'.to_string(), "cr" => '\r'.to_string(), "crlf" => "\r\n".to_string(), "tab" => '\t'.to_string(), "sp" => ' '.to_string(), "space" => ' '.to_string(), "pipe" => '|'.to_string(), "left_brace" => '{'.to_string(), "lbrace" => '{'.to_string(), "right_brace" => '}'.to_string(), "rbrace" => '}'.to_string(), "left_paren" => '('.to_string(), "lp" => '('.to_string(), "lparen" => '('.to_string(), "right_paren" => ')'.to_string(), "rparen" => ')'.to_string(), "rp" => ')'.to_string(), "left_bracket" => '['.to_string(), "lbracket" => '['.to_string(), "right_bracket" => ']'.to_string(), "rbracket" => ']'.to_string(), "single_quote" => '\''.to_string(), "squote" => '\''.to_string(), "sq" => '\''.to_string(), "double_quote" => '\"'.to_string(), "dquote" => '\"'.to_string(), "dq" => '\"'.to_string(), "path_sep" => std::path::MAIN_SEPARATOR.to_string(), "psep" => std::path::MAIN_SEPARATOR.to_string(), "separator" => std::path::MAIN_SEPARATOR.to_string(), "eol" => LINE_SEPARATOR_CHAR.to_string(), "lsep" => LINE_SEPARATOR_CHAR.to_string(), "line_sep" => LINE_SEPARATOR_CHAR.to_string(), "esep" => ENV_PATH_SEPARATOR_CHAR.to_string(), "env_sep" => ENV_PATH_SEPARATOR_CHAR.to_string(), "tilde" => '~'.to_string(), // ~ "twiddle" => '~'.to_string(), // ~ "squiggly" => '~'.to_string(), // ~ "home" => '~'.to_string(), // ~ "hash" => '#'.to_string(), // # "hashtag" => '#'.to_string(), // # "pound_sign" => '#'.to_string(), // # "sharp" => '#'.to_string(), // # "root" => '#'.to_string(), // # // This is the unicode section // Unicode names came from https://www.compart.com/en/unicode // Private Use Area (U+E000-U+F8FF) // Unicode can't be mixed with Ansi or it will break width calculation "nf_branch" => '\u{e0a0}'.to_string(), //  "nf_segment" => '\u{e0b0}'.to_string(), //  "nf_left_segment" => '\u{e0b0}'.to_string(), //  "nf_left_segment_thin" => '\u{e0b1}'.to_string(), //  "nf_right_segment" => '\u{e0b2}'.to_string(), //  "nf_right_segment_thin" => '\u{e0b3}'.to_string(), //  "nf_git" => '\u{f1d3}'.to_string(), //  "nf_git_branch" => "\u{e709}\u{e0a0}".to_string(), //  "nf_folder1" => '\u{f07c}'.to_string(), //  "nf_folder2" => '\u{f115}'.to_string(), //  "nf_house1" => '\u{f015}'.to_string(), //  "nf_house2" => '\u{f7db}'.to_string(), //  "identical_to" => '\u{2261}'.to_string(), // ≡ "hamburger" => '\u{2261}'.to_string(), // ≡ "not_identical_to" => '\u{2262}'.to_string(), // ≢ "branch_untracked" => '\u{2262}'.to_string(), // ≢ "strictly_equivalent_to" => '\u{2263}'.to_string(), // ≣ "branch_identical" => '\u{2263}'.to_string(), // ≣ "upwards_arrow" => '\u{2191}'.to_string(), // ↑ "branch_ahead" => '\u{2191}'.to_string(), // ↑ "downwards_arrow" => '\u{2193}'.to_string(), // ↓ "branch_behind" => '\u{2193}'.to_string(), // ↓ "up_down_arrow" => '\u{2195}'.to_string(), // ↕ "branch_ahead_behind" => '\u{2195}'.to_string(), // ↕ "black_right_pointing_triangle" => '\u{25b6}'.to_string(), // ▶ "prompt" => '\u{25b6}'.to_string(), // ▶ "vector_or_cross_product" => '\u{2a2f}'.to_string(), // ⨯ "failed" => '\u{2a2f}'.to_string(), // ⨯ "high_voltage_sign" => '\u{26a1}'.to_string(), // ⚡ "elevated" => '\u{26a1}'.to_string(), // ⚡ // This is the emoji section // Weather symbols // https://www.babelstone.co.uk/Unicode/whatisit.html "sun" => "☀️".to_string(), //2600 + fe0f "sunny" => "☀️".to_string(), //2600 + fe0f "sunrise" => "☀️".to_string(), //2600 + fe0f "moon" => "🌛".to_string(), //1f31b "cloudy" => "☁️".to_string(), //2601 + fe0f "cloud" => "☁️".to_string(), //2601 + fe0f "clouds" => "☁️".to_string(), //2601 + fe0f "rainy" => "🌦️".to_string(), //1f326 + fe0f "rain" => "🌦️".to_string(), //1f326 + fe0f "foggy" => "🌫️".to_string(), //1f32b + fe0f "fog" => "🌫️".to_string(), //1f32b + fe0f "mist" => '\u{2591}'.to_string(), //2591 "haze" => '\u{2591}'.to_string(), //2591 "snowy" => "❄️".to_string(), //2744 + fe0f "snow" => "❄️".to_string(), //2744 + fe0f "thunderstorm" => "🌩️".to_string(),//1f329 + fe0f "thunder" => "🌩️".to_string(), //1f329 + fe0f // This is the "other" section "bel" => '\x07'.to_string(), // Terminal Bell "backspace" => '\x08'.to_string(), // Backspace // separators "file_separator" => '\x1c'.to_string(), "file_sep" => '\x1c'.to_string(), "fs" => '\x1c'.to_string(), "group_separator" => '\x1d'.to_string(), "group_sep" => '\x1d'.to_string(), "gs" => '\x1d'.to_string(), "record_separator" => '\x1e'.to_string(), "record_sep" => '\x1e'.to_string(), "rs" => '\x1e'.to_string(), "unit_separator" => '\x1f'.to_string(), "unit_sep" => '\x1f'.to_string(), "us" => '\x1f'.to_string(), } }); static NO_OUTPUT_CHARS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| { [ // If the character is in the this set, we don't output it to prevent // the broken of `char --list` command table format and alignment. "nul", "null_byte", "zero_byte", "newline", "enter", "nl", "line_feed", "lf", "cr", "crlf", "bel", "backspace", "lsep", "line_sep", "eol", ] .into_iter() .collect() }); impl Command for Char { fn name(&self) -> &str { "char" } fn signature(&self) -> Signature { Signature::build("char") .input_output_types(vec![(Type::Nothing, Type::Any)]) .optional( "character", SyntaxShape::Any, "The name of the character to output.", ) .rest("rest", SyntaxShape::Any, "Multiple Unicode bytes.") .switch("list", "List all supported character names", Some('l')) .switch("unicode", "Unicode string i.e. 1f378", Some('u')) .switch("integer", "Create a codepoint from an integer", Some('i')) .allow_variants_without_examples(true) .category(Category::Strings) } fn is_const(&self) -> bool { true } fn description(&self) -> &str { "Output special characters (e.g., 'newline')." } fn search_terms(&self) -> Vec<&str> { vec!["line break", "newline", "Unicode"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Output newline", example: r#"char newline"#, result: Some(Value::test_string("\n")), }, Example { description: "List available characters", example: r#"char --list"#, result: None, }, Example { description: "Output prompt character, newline and a hamburger menu character", example: r#"(char prompt) + (char newline) + (char hamburger)"#, result: Some(Value::test_string("\u{25b6}\n\u{2261}")), }, Example { description: "Output Unicode character", example: r#"char --unicode 1f378"#, result: Some(Value::test_string("\u{1f378}")), }, Example { description: "Create Unicode from integer codepoint values", example: r#"char --integer (0x60 + 1) (0x60 + 2)"#, result: Some(Value::test_string("ab")), }, Example { description: "Output multi-byte Unicode character", example: r#"char --unicode 1F468 200D 1F466 200D 1F466"#, result: Some(Value::test_string( "\u{1F468}\u{200D}\u{1F466}\u{200D}\u{1F466}", )), }, ] } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let call_span = call.head; let list = call.has_flag_const(working_set, "list")?; let integer = call.has_flag_const(working_set, "integer")?; let unicode = call.has_flag_const(working_set, "unicode")?; // handle -l flag if list { return Ok(generate_character_list( working_set.permanent().signals().clone(), call.head, )); } // handle -i flag if integer { let int_args = call.rest_const(working_set, 0)?; handle_integer_flag(int_args, call_span) } // handle -u flag else if unicode { let string_args = call.rest_const(working_set, 0)?; handle_unicode_flag(string_args, call_span) } // handle the rest else { let string_args = call.rest_const(working_set, 0)?; handle_the_rest(string_args, call_span) } } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let call_span = call.head; let list = call.has_flag(engine_state, stack, "list")?; let integer = call.has_flag(engine_state, stack, "integer")?; let unicode = call.has_flag(engine_state, stack, "unicode")?; // handle -l flag if list { return Ok(generate_character_list( engine_state.signals().clone(), call_span, )); } // handle -i flag if integer { let int_args = call.rest(engine_state, stack, 0)?; handle_integer_flag(int_args, call_span) } // handle -u flag else if unicode { let string_args = call.rest(engine_state, stack, 0)?; handle_unicode_flag(string_args, call_span) } // handle the rest else { let string_args = call.rest(engine_state, stack, 0)?; handle_the_rest(string_args, call_span) } } } fn generate_character_list(signals: Signals, call_span: Span) -> PipelineData { CHAR_MAP .iter() .map(move |(name, s)| { let character = if NO_OUTPUT_CHARS.contains(name) { Value::string("", call_span) } else { Value::string(s, call_span) }; let unicode = Value::string( s.chars() .map(|c| format!("{:x}", c as u32)) .collect::<Vec<String>>() .join(" "), call_span, ); let record = record! { "name" => Value::string(*name, call_span), "character" => character, "unicode" => unicode, }; Value::record(record, call_span) }) .into_pipeline_data(call_span, signals) } fn handle_integer_flag( int_args: Vec<Spanned<i64>>, call_span: Span, ) -> Result<PipelineData, ShellError> { if int_args.is_empty() { return Err(ShellError::MissingParameter { param_name: "missing at least one unicode character".into(), span: call_span, }); } let str = int_args .into_iter() .map(integer_to_unicode_char) .collect::<Result<String, _>>()?; Ok(Value::string(str, call_span).into_pipeline_data()) } fn handle_unicode_flag( string_args: Vec<Spanned<String>>, call_span: Span, ) -> Result<PipelineData, ShellError> { if string_args.is_empty() { return Err(ShellError::MissingParameter { param_name: "missing at least one unicode character".into(), span: call_span, }); } let str = string_args .into_iter() .map(string_to_unicode_char) .collect::<Result<String, _>>()?; Ok(Value::string(str, call_span).into_pipeline_data()) } fn handle_the_rest( string_args: Vec<Spanned<String>>, call_span: Span, ) -> Result<PipelineData, ShellError> { let Some(s) = string_args.first() else { return Err(ShellError::MissingParameter { param_name: "missing name of the character".into(), span: call_span, }); }; let special_character = str_to_character(&s.item); if let Some(output) = special_character { Ok(Value::string(output, call_span).into_pipeline_data()) } else { Err(ShellError::TypeMismatch { err_message: "error finding named character".into(), span: s.span, }) } } fn integer_to_unicode_char(value: Spanned<i64>) -> Result<char, ShellError> { let decoded_char = value.item.try_into().ok().and_then(std::char::from_u32); if let Some(ch) = decoded_char { Ok(ch) } else { Err(ShellError::TypeMismatch { err_message: "not a valid Unicode codepoint".into(), span: value.span, }) } } fn string_to_unicode_char(s: Spanned<String>) -> Result<char, ShellError> { let decoded_char = u32::from_str_radix(&s.item, 16) .ok() .and_then(std::char::from_u32); if let Some(ch) = decoded_char { Ok(ch) } else { Err(ShellError::TypeMismatch { err_message: "error decoding Unicode character".into(), span: s.span, }) } } fn str_to_character(s: &str) -> Option<String> { CHAR_MAP.get(s).map(|s| s.into()) } #[cfg(test)] mod tests { use super::Char; #[test] fn examples_work_as_expected() { use crate::test_examples; test_examples(Char {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/detect_type.rs
crates/nu-command/src/strings/detect_type.rs
use crate::parse_date_from_string; use chrono::{Local, TimeZone, Utc}; use fancy_regex::{Regex, RegexBuilder}; use nu_engine::command_prelude::*; use std::sync::LazyLock; #[derive(Clone)] pub struct DetectType; impl Command for DetectType { fn name(&self) -> &str { "detect type" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::String, Type::Any), (Type::Any, Type::Any)]) .switch( "prefer-filesize", "For ints display them as human-readable file sizes", Some('f'), ) .category(Category::Strings) .allow_variants_without_examples(true) } fn description(&self) -> &str { "Infer Nushell datatype from a string." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "conversion"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Bool from string", example: "'true' | detect type", result: Some(Value::test_bool(true)), }, Example { description: "Bool is case insensitive", example: "'FALSE' | detect type", result: Some(Value::test_bool(false)), }, Example { description: "Int from plain digits", example: "'42' | detect type", result: Some(Value::test_int(42)), }, Example { description: "Int with underscores", example: "'1_000_000' | detect type", result: Some(Value::test_int(1_000_000)), }, Example { description: "Int with commas", example: "'1,234,567' | detect type", result: Some(Value::test_int(1_234_567)), }, #[allow(clippy::approx_constant, reason = "approx PI in examples is fine")] Example { description: "Float from decimal", example: "'3.14' | detect type", result: Some(Value::test_float(3.14)), }, Example { description: "Float in scientific notation", example: "'6.02e23' | detect type", result: Some(Value::test_float(6.02e23)), }, Example { description: "Prefer filesize for ints", example: "'1024' | detect type -f", result: Some(Value::test_filesize(1024)), }, Example { description: "Date Y-M-D", example: "'2022-01-01' | detect type", result: Some(Value::test_date( Local.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap().into(), )), }, Example { description: "Date with time and offset", example: "'2022-01-01T00:00:00Z' | detect type", result: Some(Value::test_date( Utc.with_ymd_and_hms(2022, 1, 1, 0, 0, 0).unwrap().into(), )), }, Example { description: "Date D-M-Y", example: "'31-12-2021' | detect type", result: Some(Value::test_date( Local .with_ymd_and_hms(2021, 12, 31, 0, 0, 0) .unwrap() .into(), )), }, Example { description: "Unknown stays a string", example: "'not-a-number' | detect type", result: Some(Value::test_string("not-a-number")), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input .metadata() .map(|metadata| metadata.with_content_type(None)); let span = call.head; let display_as_filesize = call.has_flag(engine_state, stack, "prefer-filesize")?; let val = input.into_value(call.head)?; let val = process(val, display_as_filesize, span)?; Ok(val.into_pipeline_data_with_metadata(metadata)) } } // This function will check if a value matches a regular expression for a particular datatype. // If it does, it will convert the value to that datatype. fn process(val: Value, display_as_filesize: bool, span: Span) -> Result<Value, ShellError> { // step 1: convert value to string let val_str = val.coerce_str().unwrap_or_default(); // step 2: bounce string up against regexes if BOOLEAN_RE.is_match(&val_str).unwrap_or(false) { let bval = val_str .to_lowercase() .parse::<bool>() .map_err(|_| ShellError::CantConvert { to_type: "string".to_string(), from_type: "bool".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid boolean value"# )), })?; Ok(Value::bool(bval, span)) } else if FLOAT_RE.is_match(&val_str).unwrap_or(false) { let fval = val_str .parse::<f64>() .map_err(|_| ShellError::CantConvert { to_type: "float".to_string(), from_type: "string".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid floating point value"# )), })?; Ok(Value::float(fval, span)) } else if INTEGER_RE.is_match(&val_str).unwrap_or(false) { let ival = val_str .parse::<i64>() .map_err(|_| ShellError::CantConvert { to_type: "int".to_string(), from_type: "string".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid integer value"# )), })?; if display_as_filesize { Ok(Value::filesize(ival, span)) } else { Ok(Value::int(ival, span)) } } else if INTEGER_WITH_DELIMS_RE.is_match(&val_str).unwrap_or(false) { let mut val_str = val_str.into_owned(); val_str.retain(|x| !['_', ','].contains(&x)); let ival = val_str .parse::<i64>() .map_err(|_| ShellError::CantConvert { to_type: "int".to_string(), from_type: "string".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid integer value"# )), })?; if display_as_filesize { Ok(Value::filesize(ival, span)) } else { Ok(Value::int(ival, span)) } } else if DATETIME_DMY_RE.is_match(&val_str).unwrap_or(false) { let dt = parse_date_from_string(&val_str, span).map_err(|_| ShellError::CantConvert { to_type: "datetime".to_string(), from_type: "string".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid DATETIME_MDY_RE value"# )), })?; Ok(Value::date(dt, span)) } else if DATETIME_YMD_RE.is_match(&val_str).unwrap_or(false) { let dt = parse_date_from_string(&val_str, span).map_err(|_| ShellError::CantConvert { to_type: "datetime".to_string(), from_type: "string".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid DATETIME_YMD_RE value"# )), })?; Ok(Value::date(dt, span)) } else if DATETIME_YMDZ_RE.is_match(&val_str).unwrap_or(false) { let dt = parse_date_from_string(&val_str, span).map_err(|_| ShellError::CantConvert { to_type: "datetime".to_string(), from_type: "string".to_string(), span, help: Some(format!( r#""{val_str}" does not represent a valid DATETIME_YMDZ_RE value"# )), })?; Ok(Value::date(dt, span)) } else { // If we don't know what it is, just return whatever it was passed in as Ok(val) } } // region: datatype regexes const DATETIME_DMY_PATTERN: &str = r#"(?x) ^ ['"]? # optional quotes (?:\d{1,2}) # day [-/] # separator (?P<month>[01]?\d{1}) # month [-/] # separator (?:\d{4,}) # year (?: [T\ ] # separator (?:\d{2}) # hour :? # separator (?:\d{2}) # minute (?: :? # separator (?:\d{2}) # second (?: \.(?:\d{1,9}) # subsecond )? )? )? ['"]? # optional quotes $ "#; static DATETIME_DMY_RE: LazyLock<Regex> = LazyLock::new(|| { Regex::new(DATETIME_DMY_PATTERN).expect("datetime_dmy_pattern should be valid") }); const DATETIME_YMD_PATTERN: &str = r#"(?x) ^ ['"]? # optional quotes (?:\d{4,}) # year [-/] # separator (?P<month>[01]?\d{1}) # month [-/] # separator (?:\d{1,2}) # day (?: [T\ ] # separator (?:\d{2}) # hour :? # separator (?:\d{2}) # minute (?: :? # separator (?:\d{2}) # seconds (?: \.(?:\d{1,9}) # subsecond )? )? )? ['"]? # optional quotes $ "#; static DATETIME_YMD_RE: LazyLock<Regex> = LazyLock::new(|| { Regex::new(DATETIME_YMD_PATTERN).expect("datetime_ymd_pattern should be valid") }); //2023-03-24 16:44:17.865147299 -05:00 const DATETIME_YMDZ_PATTERN: &str = r#"(?x) ^ ['"]? # optional quotes (?:\d{4,}) # year [-/] # separator (?P<month>[01]?\d{1}) # month [-/] # separator (?:\d{1,2}) # day [T\ ] # separator (?:\d{2}) # hour :? # separator (?:\d{2}) # minute (?: :? # separator (?:\d{2}) # second (?: \.(?:\d{1,9}) # subsecond )? )? \s? # optional space (?: # offset (e.g. +01:00) [+-](?:\d{2}) :? (?:\d{2}) # or Zulu suffix |Z ) ['"]? # optional quotes $ "#; static DATETIME_YMDZ_RE: LazyLock<Regex> = LazyLock::new(|| { Regex::new(DATETIME_YMDZ_PATTERN).expect("datetime_ymdz_pattern should be valid") }); static FLOAT_RE: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"^\s*[-+]?((\d*\.\d+)([eE][-+]?\d+)?|inf|NaN|(\d+)[eE][-+]?\d+|\d+\.)$") .expect("float pattern should be valid") }); static INTEGER_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*-?(\d+)$").expect("integer pattern should be valid")); static INTEGER_WITH_DELIMS_RE: LazyLock<Regex> = LazyLock::new(|| { Regex::new(r"^\s*-?(\d{1,3}([,_]\d{3})+)$") .expect("integer with delimiters pattern should be valid") }); static BOOLEAN_RE: LazyLock<Regex> = LazyLock::new(|| { RegexBuilder::new(r"^\s*(true)$|^(false)$") .case_insensitive(true) .build() .expect("boolean pattern should be valid") }); // endregion: #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(DetectType) } #[test] fn test_float_parse() { // The regex should work on all these but nushell's float parser is more strict assert!(FLOAT_RE.is_match("0.1").unwrap()); assert!(FLOAT_RE.is_match("3.0").unwrap()); assert!(FLOAT_RE.is_match("3.00001").unwrap()); assert!(FLOAT_RE.is_match("-9.9990e-003").unwrap()); assert!(FLOAT_RE.is_match("9.9990e+003").unwrap()); assert!(FLOAT_RE.is_match("9.9990E+003").unwrap()); assert!(FLOAT_RE.is_match("9.9990E+003").unwrap()); assert!(FLOAT_RE.is_match(".5").unwrap()); assert!(FLOAT_RE.is_match("2.5E-10").unwrap()); assert!(FLOAT_RE.is_match("2.5e10").unwrap()); assert!(FLOAT_RE.is_match("NaN").unwrap()); assert!(FLOAT_RE.is_match("-NaN").unwrap()); assert!(FLOAT_RE.is_match("-inf").unwrap()); assert!(FLOAT_RE.is_match("inf").unwrap()); assert!(FLOAT_RE.is_match("-7e-05").unwrap()); assert!(FLOAT_RE.is_match("7e-05").unwrap()); assert!(FLOAT_RE.is_match("+7e+05").unwrap()); } #[test] fn test_int_parse() { assert!(INTEGER_RE.is_match("0").unwrap()); assert!(INTEGER_RE.is_match("1").unwrap()); assert!(INTEGER_RE.is_match("10").unwrap()); assert!(INTEGER_RE.is_match("100").unwrap()); assert!(INTEGER_RE.is_match("1000").unwrap()); assert!(INTEGER_RE.is_match("10000").unwrap()); assert!(INTEGER_RE.is_match("100000").unwrap()); assert!(INTEGER_RE.is_match("1000000").unwrap()); assert!(INTEGER_RE.is_match("10000000").unwrap()); assert!(INTEGER_RE.is_match("100000000").unwrap()); assert!(INTEGER_RE.is_match("1000000000").unwrap()); assert!(INTEGER_RE.is_match("10000000000").unwrap()); assert!(INTEGER_RE.is_match("100000000000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("1_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("10_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("100_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("1_000_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("10_000_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("100_000_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("1_000_000_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("10_000_000_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("100_000_000_000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("1,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("10,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("100,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("1,000,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("10,000,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("100,000,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("1,000,000,000").unwrap()); assert!(INTEGER_WITH_DELIMS_RE.is_match("10,000,000,000").unwrap()); } #[test] fn test_bool_parse() { assert!(BOOLEAN_RE.is_match("true").unwrap()); assert!(BOOLEAN_RE.is_match("false").unwrap()); assert!(!BOOLEAN_RE.is_match("1").unwrap()); assert!(!BOOLEAN_RE.is_match("0").unwrap()); } #[test] fn test_datetime_ymdz_pattern() { assert!(DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00Z").unwrap()); assert!( DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789Z") .unwrap() ); assert!( DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00+01:00") .unwrap() ); assert!( DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789+01:00") .unwrap() ); assert!( DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00-01:00") .unwrap() ); assert!( DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789-01:00") .unwrap() ); assert!(DATETIME_YMDZ_RE.is_match("'2022-01-01T00:00:00Z'").unwrap()); assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00").unwrap()); assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00.").unwrap()); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789") .unwrap() ); assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00+01").unwrap()); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00+01:0") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00+1:00") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789+01") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789+01:0") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789+1:00") .unwrap() ); assert!(!DATETIME_YMDZ_RE.is_match("2022-01-01T00:00:00-01").unwrap()); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00-01:0") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00-1:00") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789-01") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789-01:0") .unwrap() ); assert!( !DATETIME_YMDZ_RE .is_match("2022-01-01T00:00:00.123456789-1:00") .unwrap() ); } #[test] fn test_datetime_ymd_pattern() { assert!(DATETIME_YMD_RE.is_match("2022-01-01").unwrap()); assert!(DATETIME_YMD_RE.is_match("2022/01/01").unwrap()); assert!(DATETIME_YMD_RE.is_match("2022-01-01T00:00:00").unwrap()); assert!( DATETIME_YMD_RE .is_match("2022-01-01T00:00:00.000000000") .unwrap() ); assert!(DATETIME_YMD_RE.is_match("'2022-01-01'").unwrap()); // The regex isn't this specific, but it would be nice if it were // assert!(!DATETIME_YMD_RE.is_match("2022-13-01").unwrap()); // assert!(!DATETIME_YMD_RE.is_match("2022-01-32").unwrap()); // assert!(!DATETIME_YMD_RE.is_match("2022-01-01T24:00:00").unwrap()); // assert!(!DATETIME_YMD_RE.is_match("2022-01-01T00:60:00").unwrap()); // assert!(!DATETIME_YMD_RE.is_match("2022-01-01T00:00:60").unwrap()); assert!( !DATETIME_YMD_RE .is_match("2022-01-01T00:00:00.0000000000") .unwrap() ); } #[test] fn test_datetime_dmy_pattern() { assert!(DATETIME_DMY_RE.is_match("31-12-2021").unwrap()); assert!(DATETIME_DMY_RE.is_match("01/01/2022").unwrap()); assert!(DATETIME_DMY_RE.is_match("15-06-2023 12:30").unwrap()); assert!(!DATETIME_DMY_RE.is_match("2022-13-01").unwrap()); assert!(!DATETIME_DMY_RE.is_match("2022-01-32").unwrap()); assert!(!DATETIME_DMY_RE.is_match("2022-01-01 24:00").unwrap()); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/detect_columns.rs
crates/nu-command/src/strings/detect_columns.rs
use itertools::Itertools; use nu_engine::command_prelude::*; use nu_protocol::{Config, Range}; use std::{io::Cursor, iter::Peekable, str::CharIndices, sync::Arc}; type Input<'t> = Peekable<CharIndices<'t>>; #[derive(Clone)] pub struct DetectColumns; impl Command for DetectColumns { fn name(&self) -> &str { "detect columns" } fn signature(&self) -> Signature { Signature::build("detect columns") .named( "skip", SyntaxShape::Int, "number of rows to skip before detecting", Some('s'), ) .input_output_types(vec![(Type::String, Type::table())]) .switch("no-headers", "don't detect headers", Some('n')) .named( "combine-columns", SyntaxShape::Range, "columns to be combined; listed as a range", Some('c'), ) .switch( "guess", "detect columns by guessing width, it may be useful if default one doesn't work", None, ) .category(Category::Strings) } fn description(&self) -> &str { "Attempt to automatically split text into multiple columns." } fn search_terms(&self) -> Vec<&str> { vec!["split", "tabular"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "use --guess if you find default algorithm not working", example: r" 'Filesystem 1K-blocks Used Available Use% Mounted on none 8150224 4 8150220 1% /mnt/c' | detect columns --guess", result: Some(Value::test_list(vec![Value::test_record(record! { "Filesystem" => Value::test_string("none"), "1K-blocks" => Value::test_string("8150224"), "Used" => Value::test_string("4"), "Available" => Value::test_string("8150220"), "Use%" => Value::test_string("1%"), "Mounted on" => Value::test_string("/mnt/c") })])), }, Example { description: "detect columns with no headers", example: "'a b c' | detect columns --no-headers", result: Some(Value::test_list(vec![Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_string("b"), "column2" => Value::test_string("c"), })])), }, Example { description: "", example: "$'c1 c2 c3 c4 c5(char nl)a b c d e' | detect columns --combine-columns 0..1 ", result: None, }, Example { description: "Splits a multi-line string into columns with headers detected", example: "$'c1 c2 c3 c4 c5(char nl)a b c d e' | detect columns --combine-columns -2..-1 ", result: None, }, Example { description: "Splits a multi-line string into columns with headers detected", example: "$'c1 c2 c3 c4 c5(char nl)a b c d e' | detect columns --combine-columns 2.. ", result: None, }, Example { description: "Parse external ls command and combine columns for datetime", example: "^ls -lh | detect columns --no-headers --skip 1 --combine-columns 5..7", result: None, }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let num_rows_to_skip: Option<usize> = call.get_flag(engine_state, stack, "skip")?; let noheader = call.has_flag(engine_state, stack, "no-headers")?; let range: Option<Range> = call.get_flag(engine_state, stack, "combine-columns")?; let config = stack.get_config(engine_state); let args = Arguments { noheader, num_rows_to_skip, range, config, }; if call.has_flag(engine_state, stack, "guess")? { guess_width(engine_state, call, input, args) } else { detect_columns(engine_state, call, input, args) } } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let num_rows_to_skip: Option<usize> = call.get_flag_const(working_set, "skip")?; let noheader = call.has_flag_const(working_set, "no-headers")?; let range: Option<Range> = call.get_flag_const(working_set, "combine-columns")?; let config = working_set.get_config().clone(); let args = Arguments { noheader, num_rows_to_skip, range, config, }; if call.has_flag_const(working_set, "guess")? { guess_width(working_set.permanent(), call, input, args) } else { detect_columns(working_set.permanent(), call, input, args) } } } struct Arguments { num_rows_to_skip: Option<usize>, noheader: bool, range: Option<Range>, config: Arc<Config>, } fn guess_width( engine_state: &EngineState, call: &Call, input: PipelineData, args: Arguments, ) -> Result<PipelineData, ShellError> { use super::guess_width::GuessWidth; let input_span = input.span().unwrap_or(call.head); let mut input = input.collect_string("", &args.config)?; if let Some(rows) = args.num_rows_to_skip { input = input.lines().skip(rows).map(|x| x.to_string()).join("\n"); } let mut guess_width = GuessWidth::new_reader(Box::new(Cursor::new(input))); let result = guess_width.read_all(); if result.is_empty() { return Ok(Value::nothing(input_span).into_pipeline_data()); } if !args.noheader { let columns = result[0].clone(); Ok(result .into_iter() .skip(1) .map(move |s| { let mut values: Vec<Value> = s .into_iter() .map(|v| Value::string(v, input_span)) .collect(); // some rows may has less columns, fill it with "" for _ in values.len()..columns.len() { values.push(Value::string("", input_span)); } let record = Record::from_raw_cols_vals(columns.clone(), values, input_span, input_span); match record { Ok(r) => match &args.range { Some(range) => merge_record(r, range, input_span), None => Value::record(r, input_span), }, Err(e) => Value::error(e, input_span), } }) .into_pipeline_data(input_span, engine_state.signals().clone())) } else { let length = result[0].len(); let columns: Vec<String> = (0..length).map(|n| format!("column{n}")).collect(); Ok(result .into_iter() .map(move |s| { let mut values: Vec<Value> = s .into_iter() .map(|v| Value::string(v, input_span)) .collect(); // some rows may has less columns, fill it with "" for _ in values.len()..columns.len() { values.push(Value::string("", input_span)); } let record = Record::from_raw_cols_vals(columns.clone(), values, input_span, input_span); match record { Ok(r) => match &args.range { Some(range) => merge_record(r, range, input_span), None => Value::record(r, input_span), }, Err(e) => Value::error(e, input_span), } }) .into_pipeline_data(input_span, engine_state.signals().clone())) } } fn detect_columns( engine_state: &EngineState, call: &Call, input: PipelineData, args: Arguments, ) -> Result<PipelineData, ShellError> { let name_span = call.head; let input_span = input.span().unwrap_or(Span::unknown()); let input = input.collect_string("", &args.config)?; let input: Vec<_> = input .lines() .skip(args.num_rows_to_skip.unwrap_or_default()) .map(|x| x.to_string()) .collect(); let mut input = input.into_iter(); let headers = input.next(); if let Some(orig_headers) = headers { let mut headers = find_columns(&orig_headers); if args.noheader { for header in headers.iter_mut().enumerate() { header.1.item = format!("column{}", header.0); } } Ok(args .noheader .then_some(orig_headers) .into_iter() .chain(input) .map(move |x| { let row = find_columns(&x); let mut record = Record::new(); if headers.len() == row.len() { for (header, val) in headers.iter().zip(row.iter()) { record.push(&header.item, Value::string(&val.item, name_span)); } } else { let mut pre_output = vec![]; // column counts don't line up, so see if we can figure out why for cell in row { for header in &headers { if cell.span.start <= header.span.end && cell.span.end > header.span.start { pre_output.push(( header.item.to_string(), Value::string(&cell.item, name_span), )); } } } for header in &headers { let mut found = false; for pre_o in &pre_output { if pre_o.0 == header.item { found = true; break; } } if !found { pre_output.push((header.item.to_string(), Value::nothing(name_span))); } } for header in &headers { for pre_o in &pre_output { if pre_o.0 == header.item { record.push(&header.item, pre_o.1.clone()); } } } } let has_column_duplicates = record.columns().duplicates().count() > 0; if has_column_duplicates { return Err(ShellError::ColumnDetectionFailure { bad_value: input_span, failure_site: name_span, }); } Ok(match &args.range { Some(range) => merge_record(record, range, name_span), None => Value::record(record, name_span), }) }) .collect::<Result<Vec<_>, _>>()? .into_pipeline_data(call.head, engine_state.signals().clone())) } else { Ok(PipelineData::empty()) } } pub fn find_columns(input: &str) -> Vec<Spanned<String>> { let mut chars = input.char_indices().peekable(); let mut output = vec![]; while let Some((_, c)) = chars.peek() { if c.is_whitespace() { // If the next character is non-newline whitespace, skip it. let _ = chars.next(); } else { // Otherwise, try to consume an unclassified token. let result = baseline(&mut chars); output.push(result); } } output } #[derive(Clone, Copy)] enum BlockKind { Parenthesis, Brace, Bracket, } fn baseline(src: &mut Input) -> Spanned<String> { let mut token_contents = String::new(); let start_offset = if let Some((pos, _)) = src.peek() { *pos } else { 0 }; // This variable tracks the starting character of a string literal, so that // we remain inside the string literal lexer mode until we encounter the // closing quote. let mut quote_start: Option<char> = None; // This Vec tracks paired delimiters let mut block_level: Vec<BlockKind> = vec![]; // A baseline token is terminated if it's not nested inside of a paired // delimiter and the next character is one of: `|`, `;`, `#` or any // whitespace. fn is_termination(block_level: &[BlockKind], c: char) -> bool { block_level.is_empty() && (c.is_whitespace()) } // The process of slurping up a baseline token repeats: // // - String literal, which begins with `'`, `"` or `\``, and continues until // the same character is encountered again. // - Delimiter pair, which begins with `[`, `(`, or `{`, and continues until // the matching closing delimiter is found, skipping comments and string // literals. // - When not nested inside of a delimiter pair, when a terminating // character (whitespace, `|`, `;` or `#`) is encountered, the baseline // token is done. // - Otherwise, accumulate the character into the current baseline token. while let Some((_, c)) = src.peek() { let c = *c; if quote_start.is_some() { // If we encountered the closing quote character for the current // string, we're done with the current string. if Some(c) == quote_start { quote_start = None; } } else if c == '\n' { if is_termination(&block_level, c) { break; } } else if c == '\'' || c == '"' || c == '`' { // We encountered the opening quote of a string literal. quote_start = Some(c); } else if c == '[' { // We encountered an opening `[` delimiter. block_level.push(BlockKind::Bracket); } else if c == ']' { // We encountered a closing `]` delimiter. Pop off the opening `[` // delimiter. if let Some(BlockKind::Bracket) = block_level.last() { let _ = block_level.pop(); } } else if c == '{' { // We encountered an opening `{` delimiter. block_level.push(BlockKind::Brace); } else if c == '}' { // We encountered a closing `}` delimiter. Pop off the opening `{`. if let Some(BlockKind::Brace) = block_level.last() { let _ = block_level.pop(); } } else if c == '(' { // We enceountered an opening `(` delimiter. block_level.push(BlockKind::Parenthesis); } else if c == ')' { // We encountered a closing `)` delimiter. Pop off the opening `(`. if let Some(BlockKind::Parenthesis) = block_level.last() { let _ = block_level.pop(); } } else if is_termination(&block_level, c) { break; } // Otherwise, accumulate the character into the current token. token_contents.push(c); // Consume the character. let _ = src.next(); } let span = Span::new(start_offset, start_offset + token_contents.len()); // If there is still unclosed opening delimiters, close them and add // synthetic closing characters to the accumulated token. if block_level.last().is_some() { // let delim: char = (*block).closing(); // let cause = ParseError::unexpected_eof(delim.to_string(), span); // while let Some(bk) = block_level.pop() { // token_contents.push(bk.closing()); // } return Spanned { item: token_contents, span, }; } if quote_start.is_some() { // The non-lite parse trims quotes on both sides, so we add the expected quote so that // anyone wanting to consume this partial parse (e.g., completions) will be able to get // correct information from the non-lite parse. // token_contents.push(delimiter); // return ( // token_contents.spanned(span), // Some(ParseError::unexpected_eof(delimiter.to_string(), span)), // ); return Spanned { item: token_contents, span, }; } Spanned { item: token_contents, span, } } fn merge_record(record: Record, range: &Range, input_span: Span) -> Value { let (start_index, end_index) = match process_range(range, record.len(), input_span) { Ok(Some((l_idx, r_idx))) => (l_idx, r_idx), Ok(None) => return Value::record(record, input_span), Err(e) => return Value::error(e, input_span), }; match merge_record_impl(record, start_index, end_index, input_span) { Ok(rec) => Value::record(rec, input_span), Err(err) => Value::error(err, input_span), } } fn process_range( range: &Range, length: usize, input_span: Span, ) -> Result<Option<(usize, usize)>, ShellError> { match nu_cmd_base::util::process_range(range) { Ok((l_idx, r_idx)) => { let l_idx = if l_idx < 0 { length as isize + l_idx } else { l_idx }; let r_idx = if r_idx < 0 { length as isize + r_idx } else { r_idx }; if !(l_idx <= r_idx && (r_idx >= 0 || l_idx < (length as isize))) { return Ok(None); } Ok(Some(( l_idx.max(0) as usize, (r_idx as usize + 1).min(length), ))) } Err(processing_error) => Err(processing_error("could not find range index", input_span)), } } fn merge_record_impl( record: Record, start_index: usize, end_index: usize, input_span: Span, ) -> Result<Record, ShellError> { let (mut cols, mut vals): (Vec<_>, Vec<_>) = record.into_iter().unzip(); // Merge Columns ((start_index + 1)..(cols.len() - end_index + start_index + 1)).for_each(|idx| { cols.swap(idx, end_index - start_index - 1 + idx); }); cols.truncate(cols.len() - end_index + start_index + 1); // Merge Values let combined = vals .iter() .take(end_index) .skip(start_index) .map(|v| v.coerce_str().unwrap_or_default()) .join(" "); let binding = Value::string(combined, Span::unknown()); let last_seg = vals.split_off(end_index); vals.truncate(start_index); vals.push(binding); vals.extend(last_seg); Record::from_raw_cols_vals(cols, vals, Span::unknown(), input_span) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { crate::test_examples(DetectColumns) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/expand.rs
crates/nu-command/src/strings/str_/expand.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrExpand; impl Command for StrExpand { fn name(&self) -> &str { "str expand" } fn description(&self) -> &str { "Generates all possible combinations defined in brace expansion syntax." } fn extra_description(&self) -> &str { "This syntax may seem familiar with `glob {A,B}.C`. The difference is glob relies on filesystem, but str expand is not. Inside braces, we put variants. Then basically we're creating all possible outcomes." } fn signature(&self) -> Signature { Signature::build("str expand") .input_output_types(vec![ (Type::String, Type::List(Box::new(Type::String))), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::List(Box::new(Type::String)))), ), ]) .switch( "path", "Replaces all backslashes with double backslashes, useful for Path.", None, ) .allow_variants_without_examples(true) .category(Category::Strings) } fn examples(&self) -> Vec<nu_protocol::Example<'_>> { vec![ Example { description: "Define a range inside braces to produce a list of string.", example: "\"{3..5}\" | str expand", result: Some(Value::list( vec![ Value::test_string("3"), Value::test_string("4"), Value::test_string("5"), ], Span::test_data(), )), }, Example { description: "Ignore the next character after the backslash ('\\')", example: "'A{B\\,,C}' | str expand", result: Some(Value::list( vec![Value::test_string("AB,"), Value::test_string("AC")], Span::test_data(), )), }, Example { description: "Commas that are not inside any braces need to be skipped.", example: "'Welcome\\, {home,mon ami}!' | str expand", result: Some(Value::list( vec![ Value::test_string("Welcome, home!"), Value::test_string("Welcome, mon ami!"), ], Span::test_data(), )), }, Example { description: "Use double backslashes to add a backslash.", example: "'A{B\\\\,C}' | str expand", result: Some(Value::list( vec![Value::test_string("AB\\"), Value::test_string("AC")], Span::test_data(), )), }, Example { description: "Export comma separated values inside braces (`{}`) to a string list.", example: "\"{apple,banana,cherry}\" | str expand", result: Some(Value::list( vec![ Value::test_string("apple"), Value::test_string("banana"), Value::test_string("cherry"), ], Span::test_data(), )), }, Example { description: "If the piped data is path, you may want to use --path flag, or else manually replace the backslashes with double backslashes.", example: "'C:\\{Users,Windows}' | str expand --path", result: Some(Value::list( vec![ Value::test_string("C:\\Users"), Value::test_string("C:\\Windows"), ], Span::test_data(), )), }, Example { description: "Brace expressions can be used one after another.", example: "\"A{b,c}D{e,f}G\" | str expand", result: Some(Value::list( vec![ Value::test_string("AbDeG"), Value::test_string("AbDfG"), Value::test_string("AcDeG"), Value::test_string("AcDfG"), ], Span::test_data(), )), }, Example { description: "Collection may include an empty item. It can be put at the start of the list.", example: "\"A{,B,C}\" | str expand", result: Some(Value::list( vec![ Value::test_string("A"), Value::test_string("AB"), Value::test_string("AC"), ], Span::test_data(), )), }, Example { description: "Empty item can be at the end of the collection.", example: "\"A{B,C,}\" | str expand", result: Some(Value::list( vec![ Value::test_string("AB"), Value::test_string("AC"), Value::test_string("A"), ], Span::test_data(), )), }, Example { description: "Empty item can be in the middle of the collection.", example: "\"A{B,,C}\" | str expand", result: Some(Value::list( vec![ Value::test_string("AB"), Value::test_string("A"), Value::test_string("AC"), ], Span::test_data(), )), }, Example { description: "Also, it is possible to use one inside another. Here is a real-world example, that creates files:", example: "\"A{B{1,3},C{2,5}}D\" | str expand", result: Some(Value::list( vec![ Value::test_string("AB1D"), Value::test_string("AB3D"), Value::test_string("AC2D"), Value::test_string("AC5D"), ], Span::test_data(), )), }, Example { description: "Supports zero padding in numeric ranges.", example: "\"A{08..10}B{11..013}C\" | str expand", result: Some(Value::list( vec![ Value::test_string("A08B011C"), Value::test_string("A08B012C"), Value::test_string("A08B013C"), Value::test_string("A09B011C"), Value::test_string("A09B012C"), Value::test_string("A09B013C"), Value::test_string("A10B011C"), Value::test_string("A10B012C"), Value::test_string("A10B013C"), ], Span::test_data(), )), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let is_path = call.has_flag(engine_state, stack, "path")?; run(call, input, is_path, engine_state) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let is_path = call.has_flag_const(working_set, "path")?; run(call, input, is_path, working_set.permanent()) } } fn run( call: &Call, input: PipelineData, is_path: bool, engine_state: &EngineState, ) -> Result<PipelineData, ShellError> { let span = call.head; if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: span }); } input.map( move |v| { let value_span = v.span(); let type_ = v.get_type(); match v.coerce_into_string() { Ok(s) => { let contents = if is_path { s.replace('\\', "\\\\") } else { s }; str_expand(&contents, span, value_span) } Err(_) => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: type_.to_string(), dst_span: span, src_span: value_span, }, span, ), } }, engine_state.signals(), ) } fn str_expand(contents: &str, span: Span, value_span: Span) -> Value { use bracoxide::{ expand, parser::{ParsingError, parse}, tokenizer::{TokenizationError, tokenize}, }; match tokenize(contents) { Ok(tokens) => { match parse(&tokens) { Ok(node) => { match expand(&node) { Ok(possibilities) => { Value::list(possibilities.iter().map(|e| Value::string(e,span)).collect::<Vec<Value>>(), span) }, Err(e) => match e { bracoxide::ExpansionError::NumConversionFailed(s) => Value::error( ShellError::GenericError{error: "Number Conversion Failed".into(), msg: format!("Number conversion failed at {s}."), span: Some(value_span), help: Some("Expected number, found text. Range format is `{M..N}`, where M and N are numeric values representing the starting and ending limits.".into()), inner: vec![]}, span, ), }, } }, Err(e) => Value::error( match e { ParsingError::NoTokens => ShellError::PipelineEmpty { dst_span: value_span }, ParsingError::OBraExpected(s) => ShellError::GenericError{ error: "Opening Brace Expected".into(), msg: format!("Opening brace is expected at {s}."), span: Some(value_span), help: Some("In brace syntax, we use equal amount of opening (`{`) and closing (`}`). Please, take a look at the examples.".into()), inner: vec![]}, ParsingError::CBraExpected(s) => ShellError::GenericError{ error: "Closing Brace Expected".into(), msg: format!("Closing brace is expected at {s}."), span: Some(value_span), help: Some("In brace syntax, we use equal amount of opening (`{`) and closing (`}`). Please, see the examples.".into()), inner: vec![]}, ParsingError::RangeStartLimitExpected(s) => ShellError::GenericError{error: "Range Start Expected".into(), msg: format!("Range start limit is missing, expected at {s}."), span: Some(value_span), help: Some("In brace syntax, Range is defined like `{X..Y}`, where X and Y are a number. X is the start, Y is the end. Please, inspect the examples for more information.".into()), inner: vec![]}, ParsingError::RangeEndLimitExpected(s) => ShellError::GenericError{ error: "Range Start Expected".into(), msg: format!("Range start limit is missing, expected at {s}."),span: Some(value_span), help: Some("In brace syntax, Range is defined like `{X..Y}`, where X and Y are a number. X is the start, Y is the end. Please see the examples, for more information.".into()), inner: vec![]}, ParsingError::ExpectedText(s) => ShellError::GenericError { error: "Expected Text".into(), msg: format!("Expected text at {s}."), span: Some(value_span), help: Some("Texts are only allowed before opening brace (`{`), after closing brace (`}`), or inside `{}`. Please take a look at the examples.".into()), inner: vec![] }, ParsingError::InvalidCommaUsage(s) => ShellError::GenericError { error: "Invalid Comma Usage".into(), msg: format!("Found comma at {s}. Commas are only valid inside collection (`{{X,Y}}`)."),span: Some(value_span), help: Some("To escape comma use backslash `\\,`.".into()), inner: vec![] }, ParsingError::RangeCantHaveText(s) => ShellError::GenericError { error: "Range Can not Have Text".into(), msg: format!("Expecting, brace, number, or range operator, but found text at {s}."), span: Some(value_span), help: Some("Please use the format {M..N} for ranges in brace expansion, where M and N are numeric values representing the starting and ending limits of the sequence, respectively.".into()), inner: vec![]}, ParsingError::ExtraRangeOperator(s) => ShellError::GenericError { error: "Extra Range Operator".into(), msg: format!("Found additional, range operator at {s}."), span: Some(value_span), help: Some("Please, use the format `{M..N}` where M and N are numeric values representing the starting and ending limits of the range.".into()), inner: vec![] }, ParsingError::ExtraCBra(s) => ShellError::GenericError { error: "Extra Closing Brace".into(), msg: format!("Used extra closing brace at {s}."), span: Some(value_span), help: Some("To escape closing brace use backslash, e.g. `\\}`".into()), inner: vec![] }, ParsingError::ExtraOBra(s) => ShellError::GenericError { error: "Extra Opening Brace".into(), msg: format!("Used extra opening brace at {s}."), span: Some(value_span), help: Some("To escape opening brace use backslash, e.g. `\\{`".into()), inner: vec![] }, ParsingError::NothingInBraces(s) => ShellError::GenericError { error: "Nothing In Braces".into(), msg: format!("Nothing found inside braces at {s}."), span: Some(value_span), help: Some("Please provide valid content within the braces. Additionally, you can safely remove it, not needed.".into()), inner: vec![] }, } , span, ) } }, Err(e) => match e { TokenizationError::EmptyContent => Value::error( ShellError::PipelineEmpty { dst_span: value_span }, value_span, ), TokenizationError::FormatNotSupported => Value::error( ShellError::GenericError { error: "Format Not Supported".into(), msg: "Usage of only `{` or `}`. Brace Expansion syntax, needs to have equal amount of opening (`{`) and closing (`}`)".into(), span: Some(value_span), help: Some("In brace expansion syntax, it is important to have an equal number of opening (`{`) and closing (`}`) braces. Please ensure that you provide a balanced pair of braces in your brace expansion pattern.".into()), inner: vec![] }, value_span, ), TokenizationError::NoBraces => Value::error( ShellError::GenericError { error: "No Braces".into(), msg: "At least one `{}` brace expansion expected.".into(), span: Some(value_span), help: Some("Please, examine the examples.".into()), inner: vec![] }, value_span, ) }, } } #[cfg(test)] mod tests { use super::*; #[test] fn test_double_dots_outside_curly() { assert_eq!( str_expand("..{a,b}..", Span::test_data(), Span::test_data()), Value::list( vec![ Value::string(String::from("..a.."), Span::test_data(),), Value::string(String::from("..b.."), Span::test_data(),) ], Span::test_data(), ) ); } #[test] fn test_outer_single_item() { assert_eq!( str_expand("{W{x,y}}", Span::test_data(), Span::test_data()), Value::list( vec![ Value::string(String::from("Wx"), Span::test_data(),), Value::string(String::from("Wy"), Span::test_data(),) ], Span::test_data(), ) ); } #[test] fn dots() { assert_eq!( str_expand("{a.b.c,d}", Span::test_data(), Span::test_data()), Value::list( vec![ Value::string(String::from("a.b.c"), Span::test_data(),), Value::string(String::from("d"), Span::test_data(),) ], Span::test_data(), ) ); assert_eq!( str_expand("{1.2.3,a}", Span::test_data(), Span::test_data()), Value::list( vec![ Value::string(String::from("1.2.3"), Span::test_data(),), Value::string(String::from("a"), Span::test_data(),) ], Span::test_data(), ) ); assert_eq!( str_expand("{a-1.2,b}", Span::test_data(), Span::test_data()), Value::list( vec![ Value::string(String::from("a-1.2"), Span::test_data(),), Value::string(String::from("b"), Span::test_data(),) ], Span::test_data(), ) ); } #[test] fn test_numbers_proceeding_escape_char_not_ignored() { assert_eq!( str_expand("1\\\\{a,b}", Span::test_data(), Span::test_data()), Value::list( vec![ Value::string(String::from("1\\a"), Span::test_data(),), Value::string(String::from("1\\b"), Span::test_data(),) ], Span::test_data(), ) ); } #[test] fn test_examples() { use crate::test_examples; test_examples(StrExpand {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/starts_with.rs
crates/nu-command/src/strings/str_/starts_with.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_utils::IgnoreCaseExt; struct Arguments { substring: String, cell_paths: Option<Vec<CellPath>>, case_insensitive: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct StrStartsWith; impl Command for StrStartsWith { fn name(&self) -> &str { "str starts-with" } fn signature(&self) -> Signature { Signature::build("str starts-with") .input_output_types(vec![ (Type::String, Type::Bool), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Bool))), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("string", SyntaxShape::String, "The string to match.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, check strings at the given cell paths, and replace with result.", ) .switch("ignore-case", "search is case insensitive", Some('i')) .category(Category::Strings) } fn description(&self) -> &str { "Check if an input starts with a string." } fn search_terms(&self) -> Vec<&str> { vec!["prefix", "match", "find", "search"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let substring: Spanned<String> = 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 args = Arguments { substring: substring.item, cell_paths, case_insensitive: call.has_flag(engine_state, stack, "ignore-case")?, }; operate(action, args, input, call.head, engine_state.signals()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let substring: Spanned<String> = call.req_const(working_set, 0)?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { substring: substring.item, cell_paths, case_insensitive: call.has_flag_const(working_set, "ignore-case")?, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Checks if input string starts with 'my'", example: "'my_library.rb' | str starts-with 'my'", result: Some(Value::test_bool(true)), }, Example { description: "Checks if input string starts with 'Car'", example: "'Cargo.toml' | str starts-with 'Car'", result: Some(Value::test_bool(true)), }, Example { description: "Checks if input string starts with '.toml'", example: "'Cargo.toml' | str starts-with '.toml'", result: Some(Value::test_bool(false)), }, Example { description: "Checks if input string starts with 'cargo', case-insensitive", example: "'Cargo.toml' | str starts-with --ignore-case 'cargo'", result: Some(Value::test_bool(true)), }, ] } } fn action( input: &Value, Arguments { substring, case_insensitive, .. }: &Arguments, head: Span, ) -> Value { match input { Value::String { val: s, .. } => { let starts_with = if *case_insensitive { s.to_folded_case().starts_with(&substring.to_folded_case()) } else { s.starts_with(substring) }; Value::bool(starts_with, head) } Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrStartsWith {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/distance.rs
crates/nu-command/src/strings/str_/distance.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::{engine::StateWorkingSet, levenshtein_distance}; #[derive(Clone)] pub struct StrDistance; struct Arguments { compare_string: String, 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 StrDistance { fn name(&self) -> &str { "str distance" } fn signature(&self) -> Signature { Signature::build("str distance") .input_output_types(vec![ (Type::String, Type::Int), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .required( "compare-string", SyntaxShape::String, "The first string to compare.", ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, check strings at the given cell paths, and replace with result.", ) .category(Category::Strings) } fn description(&self) -> &str { "Compare two strings and return the edit distance/Levenshtein distance." } fn search_terms(&self) -> Vec<&str> { vec!["edit", "levenshtein"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let compare_string: String = 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 args = Arguments { compare_string, cell_paths, }; operate(action, args, input, call.head, engine_state.signals()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let compare_string: String = call.req_const(working_set, 0)?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { compare_string, cell_paths, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "get the edit distance between two strings", example: "'nushell' | str distance 'nutshell'", result: Some(Value::test_int(1)), }, Example { description: "Compute edit distance between strings in table and another string, using cell paths", example: "[{a: 'nutshell' b: 'numetal'}] | str distance 'nushell' 'a' 'b'", result: Some(Value::test_list(vec![Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(4), })])), }, Example { description: "Compute edit distance between strings in record and another string, using cell paths", example: "{a: 'nutshell' b: 'numetal'} | str distance 'nushell' a b", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(4), })), }, ] } } fn action(input: &Value, args: &Arguments, head: Span) -> Value { let compare_string = &args.compare_string; match input { Value::String { val, .. } => { let distance = levenshtein_distance(val, compare_string); Value::int(distance as i64, head) } Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrDistance {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/reverse.rs
crates/nu-command/src/strings/str_/reverse.rs
use nu_cmd_base::input_handler::{CellPathOnlyArgs, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrReverse; impl Command for StrReverse { fn name(&self) -> &str { "str reverse" } fn signature(&self) -> Signature { Signature::build("str reverse") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, reverse strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Reverse every string in the pipeline." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "inverse", "flip"] } fn is_const(&self) -> bool { true } 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 args = CellPathOnlyArgs::from(cell_paths); operate(action, args, input, call.head, engine_state.signals()) } 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 args = CellPathOnlyArgs::from(cell_paths); operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Reverse a single string", example: "'Nushell' | str reverse", result: Some(Value::test_string("llehsuN")), }, Example { description: "Reverse multiple strings in a list", example: "['Nushell' 'is' 'cool'] | str reverse", result: Some(Value::list( vec![ Value::test_string("llehsuN"), Value::test_string("si"), Value::test_string("looc"), ], Span::test_data(), )), }, ] } } fn action(input: &Value, _arg: &CellPathOnlyArgs, head: Span) -> Value { match input { Value::String { val, .. } => Value::string(val.chars().rev().collect::<String>(), head), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrReverse {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/stats.rs
crates/nu-command/src/strings/str_/stats.rs
use fancy_regex::Regex; use nu_engine::command_prelude::*; use std::collections::BTreeMap; use std::{fmt, str}; use unicode_segmentation::UnicodeSegmentation; // borrowed liberally from here https://github.com/dead10ck/uwc pub type Counted = BTreeMap<Counter, usize>; #[derive(Clone)] pub struct StrStats; impl Command for StrStats { fn name(&self) -> &str { "str stats" } fn signature(&self) -> Signature { Signature::build("str stats") .category(Category::Strings) .input_output_types(vec![(Type::String, Type::record())]) } fn description(&self) -> &str { "Gather word count statistics on the text." } fn search_terms(&self) -> Vec<&str> { vec!["count", "word", "character", "unicode", "wc"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { stats(engine_state, call, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { stats(working_set.permanent(), call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Count the number of words in a string", example: r#""There are seven words in this sentence" | str stats"#, result: Some(Value::test_record(record! { "lines" => Value::test_int(1), "words" => Value::test_int(7), "bytes" => Value::test_int(38), "chars" => Value::test_int(38), "graphemes" => Value::test_int(38), "unicode-width" => Value::test_int(38), })), }, Example { description: "Counts unicode characters", example: r#"'今天天气真好' | str stats"#, result: Some(Value::test_record(record! { "lines" => Value::test_int(1), "words" => Value::test_int(6), "bytes" => Value::test_int(18), "chars" => Value::test_int(6), "graphemes" => Value::test_int(6), "unicode-width" => Value::test_int(12), })), }, Example { description: "Counts Unicode characters correctly in a string", example: r#""Amélie Amelie" | str stats"#, result: Some(Value::test_record(record! { "lines" => Value::test_int(1), "words" => Value::test_int(2), "bytes" => Value::test_int(15), "chars" => Value::test_int(14), "graphemes" => Value::test_int(13), "unicode-width" => Value::test_int(13), })), }, ] } } fn stats( engine_state: &EngineState, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: span }); } input.map( move |v| { let value_span = v.span(); let type_ = v.get_type(); // First, obtain the span. If this fails, propagate the error that results. if let Value::Error { error, .. } = v { return Value::error(*error, span); } // Now, check if it's a string. match v.coerce_into_string() { Ok(s) => counter(&s, span), Err(_) => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: type_.to_string(), dst_span: span, src_span: value_span, }, span, ), } }, engine_state.signals(), ) } fn counter(contents: &str, span: Span) -> Value { let counts = uwc_count(&ALL_COUNTERS[..], contents); fn get_count(counts: &BTreeMap<Counter, usize>, counter: Counter, span: Span) -> Value { Value::int(counts.get(&counter).copied().unwrap_or(0) as i64, span) } let record = record! { "lines" => get_count(&counts, Counter::Lines, span), "words" => get_count(&counts, Counter::Words, span), "bytes" => get_count(&counts, Counter::Bytes, span), "chars" => get_count(&counts, Counter::CodePoints, span), "graphemes" => get_count(&counts, Counter::GraphemeClusters, span), "unicode-width" => get_count(&counts, Counter::UnicodeWidth, span), }; Value::record(record, span) } // /// Take all the counts in `other_counts` and sum them into `accum`. // pub fn sum_counts(accum: &mut Counted, other_counts: &Counted) { // for (counter, count) in other_counts { // let entry = accum.entry(*counter).or_insert(0); // *entry += count; // } // } // /// Sums all the `Counted` instances into a new one. // pub fn sum_all_counts<'a, I>(counts: I) -> Counted // where // I: IntoIterator<Item = &'a Counted>, // { // let mut totals = BTreeMap::new(); // for counts in counts { // sum_counts(&mut totals, counts); // } // totals // } /// Something that counts things in `&str`s. pub trait Count { /// Counts something in the given `&str`. fn count(&self, s: &str) -> usize; } impl Count for Counter { fn count(&self, s: &str) -> usize { match *self { Counter::GraphemeClusters => s.graphemes(true).count(), Counter::Bytes => s.len(), Counter::Lines => { const LF: &str = "\n"; // 0xe0000a const CR: &str = "\r"; // 0xe0000d const CRLF: &str = "\r\n"; // 0xe00d0a const NEL: &str = "\u{0085}"; // 0x00c285 const FF: &str = "\u{000C}"; // 0x00000c const LS: &str = "\u{2028}"; // 0xe280a8 const PS: &str = "\u{2029}"; // 0xe280a9 // use regex here because it can search for CRLF first and not duplicate the count let line_ending_types = [CRLF, LF, CR, NEL, FF, LS, PS]; let pattern = &line_ending_types.join("|"); let newline_pattern = Regex::new(pattern).expect("Unable to create regex"); let line_endings = newline_pattern .find_iter(s) .map(|f| match f { Ok(mat) => mat.as_str().to_string(), Err(_) => "".to_string(), }) .collect::<Vec<String>>(); let has_line_ending_suffix = line_ending_types.iter().any(|&suffix| s.ends_with(suffix)); // eprintln!("suffix = {}", has_line_ending_suffix); if has_line_ending_suffix { line_endings.len() } else { line_endings.len() + 1 } } Counter::Words => s.unicode_words().count(), Counter::CodePoints => s.chars().count(), Counter::UnicodeWidth => unicode_width::UnicodeWidthStr::width(s), } } } /// Different types of counters. #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)] pub enum Counter { /// Counts lines. Lines, /// Counts words. Words, /// Counts the total number of bytes. Bytes, /// Counts grapheme clusters. The input is required to be valid UTF-8. GraphemeClusters, /// Counts unicode code points CodePoints, /// Counts the width of the string UnicodeWidth, } /// A convenience array of all counter types. pub const ALL_COUNTERS: [Counter; 6] = [ Counter::GraphemeClusters, Counter::Bytes, Counter::Lines, Counter::Words, Counter::CodePoints, Counter::UnicodeWidth, ]; impl fmt::Display for Counter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match *self { Counter::GraphemeClusters => "graphemes", Counter::Bytes => "bytes", Counter::Lines => "lines", Counter::Words => "words", Counter::CodePoints => "codepoints", Counter::UnicodeWidth => "unicode-width", }; write!(f, "{s}") } } /// Counts the given `Counter`s in the given `&str`. pub fn uwc_count<'a, I>(counters: I, s: &str) -> Counted where I: IntoIterator<Item = &'a Counter>, { let mut counts: Counted = counters.into_iter().map(|c| (*c, c.count(s))).collect(); if let Some(lines) = counts.get_mut(&Counter::Lines) { if s.is_empty() { // If s is empty, indeed, the count is 0 *lines = 0; } else if *lines == 0 && !s.is_empty() { // If s is not empty and the count is 0, it means there // is a line without a line ending, so let's make it 1 *lines = 1; } else { // no change, whatever the count is, is right } } counts } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrStats {}) } } #[test] fn test_one_newline() { let s = "\n".to_string(); let counts = uwc_count(&ALL_COUNTERS[..], &s); let mut correct_counts = BTreeMap::new(); correct_counts.insert(Counter::Lines, 1); correct_counts.insert(Counter::Words, 0); correct_counts.insert(Counter::GraphemeClusters, 1); correct_counts.insert(Counter::Bytes, 1); correct_counts.insert(Counter::CodePoints, 1); correct_counts.insert(Counter::UnicodeWidth, 1); assert_eq!(correct_counts, counts); } #[test] fn test_count_counts_lines() { // const LF: &str = "\n"; // 0xe0000a // const CR: &str = "\r"; // 0xe0000d // const CRLF: &str = "\r\n"; // 0xe00d0a const NEL: &str = "\u{0085}"; // 0x00c285 const FF: &str = "\u{000C}"; // 0x00000c const LS: &str = "\u{2028}"; // 0xe280a8 const PS: &str = "\u{2029}"; // 0xe280a9 // * \r\n is a single grapheme cluster // * trailing newlines are counted // * NEL is 2 bytes // * FF is 1 byte // * LS is 3 bytes // * PS is 3 bytes let mut s = String::from("foo\r\nbar\n\nbaz"); s += NEL; s += "quux"; s += FF; s += LS; s += "xi"; s += PS; s += "\n"; let counts = uwc_count(&ALL_COUNTERS[..], &s); let mut correct_counts = BTreeMap::new(); correct_counts.insert(Counter::Lines, 8); correct_counts.insert(Counter::Words, 5); correct_counts.insert(Counter::GraphemeClusters, 23); correct_counts.insert(Counter::Bytes, 29); // one more than grapheme clusters because of \r\n correct_counts.insert(Counter::CodePoints, 24); correct_counts.insert(Counter::UnicodeWidth, 23); assert_eq!(correct_counts, counts); } #[test] fn test_count_counts_words() { let i_can_eat_glass = "Μπορῶ νὰ φάω σπασμένα γυαλιὰ χωρὶς νὰ πάθω τίποτα."; let s = String::from(i_can_eat_glass); let counts = uwc_count(&ALL_COUNTERS[..], &s); let mut correct_counts = BTreeMap::new(); correct_counts.insert(Counter::GraphemeClusters, 50); correct_counts.insert(Counter::Lines, 1); correct_counts.insert(Counter::Bytes, i_can_eat_glass.len()); correct_counts.insert(Counter::Words, 9); correct_counts.insert(Counter::CodePoints, 50); correct_counts.insert(Counter::UnicodeWidth, 50); assert_eq!(correct_counts, counts); } #[test] fn test_count_counts_codepoints() { // these are NOT the same! One is e + ́́ , and one is é, a single codepoint let one = "é"; let two = "é"; let counters = [Counter::CodePoints]; let counts = uwc_count(&counters[..], one); let mut correct_counts = BTreeMap::new(); correct_counts.insert(Counter::CodePoints, 1); assert_eq!(correct_counts, counts); let counts = uwc_count(&counters[..], two); let mut correct_counts = BTreeMap::new(); correct_counts.insert(Counter::CodePoints, 2); assert_eq!(correct_counts, counts); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/index_of.rs
crates/nu-command/src/strings/str_/index_of.rs
use std::ops::Bound; use crate::{grapheme_flags, grapheme_flags_const}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::{IntRange, engine::StateWorkingSet}; use unicode_segmentation::UnicodeSegmentation; struct Arguments { end: bool, substring: String, range: Option<Spanned<IntRange>>, cell_paths: Option<Vec<CellPath>>, graphemes: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct StrIndexOf; impl Command for StrIndexOf { fn name(&self) -> &str { "str index-of" } fn signature(&self) -> Signature { Signature::build("str index-of") .input_output_types(vec![ (Type::String, Type::Int), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Int))), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("string", SyntaxShape::String, "The string to find in the input.") .switch( "grapheme-clusters", "count indexes using grapheme clusters (all visible chars have length 1)", Some('g'), ) .switch( "utf-8-bytes", "count indexes using UTF-8 bytes (default; non-ASCII chars have length 2+)", Some('b'), ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, search strings at the given cell paths, and replace with result.", ) .named( "range", SyntaxShape::Range, "optional start and/or end index", Some('r'), ) .switch("end", "search from the end of the input", Some('e')) .category(Category::Strings) } fn description(&self) -> &str { "Returns start index of first occurrence of string in input, or -1 if no match." } fn search_terms(&self) -> Vec<&str> { vec!["match", "find", "search"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let substring: Spanned<String> = 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 args = Arguments { substring: substring.item, range: call.get_flag(engine_state, stack, "range")?, end: call.has_flag(engine_state, stack, "end")?, cell_paths, graphemes: grapheme_flags(engine_state, stack, call)?, }; operate(action, args, input, call.head, engine_state.signals()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let substring: Spanned<String> = call.req_const(working_set, 0)?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { substring: substring.item, range: call.get_flag_const(working_set, "range")?, end: call.has_flag_const(working_set, "end")?, cell_paths, graphemes: grapheme_flags_const(working_set, call)?, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Returns index of string in input", example: " 'my_library.rb' | str index-of '.rb'", result: Some(Value::test_int(10)), }, Example { description: "Count length using grapheme clusters", example: "'🇯🇵ほげ ふが ぴよ' | str index-of --grapheme-clusters 'ふが'", result: Some(Value::test_int(4)), }, Example { description: "Returns index of string in input within a`rhs open range`", example: " '.rb.rb' | str index-of '.rb' --range 1..", result: Some(Value::test_int(3)), }, Example { description: "Returns index of string in input within a lhs open range", example: " '123456' | str index-of '6' --range ..4", result: Some(Value::test_int(-1)), }, Example { description: "Returns index of string in input within a range", example: " '123456' | str index-of '3' --range 1..4", result: Some(Value::test_int(2)), }, Example { description: "Returns index of string in input", example: " '/this/is/some/path/file.txt' | str index-of '/' -e", result: Some(Value::test_int(18)), }, ] } } fn action( input: &Value, Arguments { substring, range, end, graphemes, .. }: &Arguments, head: Span, ) -> Value { match input { Value::String { val: s, .. } => { let (search_str, start_index) = if let Some(spanned_range) = range { let range_span = spanned_range.span; let range = &spanned_range.item; let (start, end) = range.absolute_bounds(s.len()); let s = match end { Bound::Excluded(end) => s.get(start..end), Bound::Included(end) => s.get(start..=end), Bound::Unbounded => s.get(start..), }; let s = match s { Some(s) => s, None => { return Value::error( ShellError::OutOfBounds { left_flank: start.to_string(), right_flank: match range.end() { Bound::Unbounded => "".to_string(), Bound::Included(end) => format!("={end}"), Bound::Excluded(end) => format!("<{end}"), }, span: range_span, }, head, ); } }; (s, start) } else { (s.as_str(), 0) }; // When the -e flag is present, search using rfind instead of find.s if let Some(result) = if *end { search_str.rfind(&**substring) } else { search_str.find(&**substring) } { let result = result + start_index; Value::int( if *graphemes { // Having found the substring's byte index, convert to grapheme index. // grapheme_indices iterates graphemes alongside their UTF-8 byte indices, so .enumerate() // is used to get the grapheme index alongside it. s.grapheme_indices(true) .enumerate() .find(|e| e.1.0 >= result) .expect("No grapheme index for substring") .0 } else { result } as i64, head, ) } else { Value::int(-1, head) } } Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod tests { use nu_protocol::ast::RangeInclusion; use super::*; use super::{Arguments, StrIndexOf, action}; #[test] fn test_examples() { use crate::test_examples; test_examples(StrIndexOf {}) } #[test] fn returns_index_of_substring() { let word = Value::test_string("Cargo.tomL"); let options = Arguments { substring: String::from(".tomL"), range: None, cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(5)); } #[test] fn index_of_does_not_exist_in_string() { let word = Value::test_string("Cargo.tomL"); let options = Arguments { substring: String::from("Lm"), range: None, cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(-1)); } #[test] fn returns_index_of_next_substring() { let word = Value::test_string("Cargo.Cargo"); let range = IntRange::new( Value::int(1, Span::test_data()), Value::nothing(Span::test_data()), Value::nothing(Span::test_data()), RangeInclusion::Inclusive, Span::test_data(), ) .expect("valid range"); let spanned_range = Spanned { item: range, span: Span::test_data(), }; let options = Arguments { substring: String::from("Cargo"), range: Some(spanned_range), cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(6)); } #[test] fn index_does_not_exist_due_to_end_index() { let word = Value::test_string("Cargo.Banana"); let range = IntRange::new( Value::nothing(Span::test_data()), Value::nothing(Span::test_data()), Value::int(5, Span::test_data()), RangeInclusion::Inclusive, Span::test_data(), ) .expect("valid range"); let spanned_range = Spanned { item: range, span: Span::test_data(), }; let options = Arguments { substring: String::from("Banana"), range: Some(spanned_range), cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(-1)); } #[test] fn returns_index_of_nums_in_middle_due_to_index_limit_from_both_ends() { let word = Value::test_string("123123123"); let range = IntRange::new( Value::int(2, Span::test_data()), Value::nothing(Span::test_data()), Value::int(6, Span::test_data()), RangeInclusion::Inclusive, Span::test_data(), ) .expect("valid range"); let spanned_range = Spanned { item: range, span: Span::test_data(), }; let options = Arguments { substring: String::from("123"), range: Some(spanned_range), cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(3)); } #[test] fn index_does_not_exists_due_to_strict_bounds() { let word = Value::test_string("123456"); let range = IntRange::new( Value::int(2, Span::test_data()), Value::nothing(Span::test_data()), Value::int(5, Span::test_data()), RangeInclusion::RightExclusive, Span::test_data(), ) .expect("valid range"); let spanned_range = Spanned { item: range, span: Span::test_data(), }; let options = Arguments { substring: String::from("1"), range: Some(spanned_range), cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(-1)); } #[test] fn use_utf8_bytes() { let word = Value::string(String::from("🇯🇵ほげ ふが ぴよ"), Span::test_data()); let options = Arguments { substring: String::from("ふが"), range: None, cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(15)); } #[test] fn index_is_not_a_char_boundary() { let word = Value::string(String::from("💛"), Span::test_data()); let range = IntRange::new( Value::int(0, Span::test_data()), Value::int(1, Span::test_data()), Value::int(2, Span::test_data()), RangeInclusion::Inclusive, Span::test_data(), ) .expect("valid range"); let spanned_range = Spanned { item: range, span: Span::test_data(), }; let options = Arguments { substring: String::new(), range: Some(spanned_range), cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert!(actual.is_error()); } #[test] fn index_is_out_of_bounds() { let word = Value::string(String::from("hello"), Span::test_data()); let range = IntRange::new( Value::int(-1, Span::test_data()), Value::int(1, Span::test_data()), Value::int(3, Span::test_data()), RangeInclusion::Inclusive, Span::test_data(), ) .expect("valid range"); let spanned_range = Spanned { item: range, span: Span::test_data(), }; let options = Arguments { substring: String::from("h"), range: Some(spanned_range), cell_paths: None, end: false, graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(-1)); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/contains.rs
crates/nu-command/src/strings/str_/contains.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_utils::IgnoreCaseExt; #[derive(Clone)] pub struct StrContains; struct Arguments { substring: String, cell_paths: Option<Vec<CellPath>>, case_insensitive: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } impl Command for StrContains { fn name(&self) -> &str { "str contains" } fn signature(&self) -> Signature { Signature::build("str contains") .input_output_types(vec![ (Type::String, Type::Bool), // TODO figure out cell-path type behavior (Type::table(), Type::table()), (Type::record(), Type::record()), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Bool))) ]) .required("string", SyntaxShape::String, "The substring to find.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, check strings at the given cell paths, and replace with result.", ) .switch("ignore-case", "search is case insensitive", Some('i')) .category(Category::Strings) } fn description(&self) -> &str { "Checks if string input contains a substring." } fn search_terms(&self) -> Vec<&str> { vec!["substring", "match", "find", "search"] } fn is_const(&self) -> bool { true } 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 args = Arguments { substring: call.req::<String>(engine_state, stack, 0)?, cell_paths, case_insensitive: call.has_flag(engine_state, stack, "ignore-case")?, }; operate(action, args, input, call.head, engine_state.signals()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { substring: call.req_const::<String>(working_set, 0)?, cell_paths, case_insensitive: call.has_flag_const(working_set, "ignore-case")?, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Check if input contains string", example: "'my_library.rb' | str contains '.rb'", result: Some(Value::test_bool(true)), }, Example { description: "Check if input contains string case insensitive", example: "'my_library.rb' | str contains --ignore-case '.RB'", result: Some(Value::test_bool(true)), }, Example { description: "Check if input contains string in a record", example: "{ ColA: test, ColB: 100 } | str contains 'e' ColA", result: Some(Value::test_record(record! { "ColA" => Value::test_bool(true), "ColB" => Value::test_int(100), })), }, Example { description: "Check if input contains string in a table", example: " [[ColA ColB]; [test 100]] | str contains --ignore-case 'E' ColA", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_bool(true), "ColB" => Value::test_int(100), })])), }, Example { description: "Check if input contains string in a table", example: " [[ColA ColB]; [test hello]] | str contains 'e' ColA ColB", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_bool(true), "ColB" => Value::test_bool(true), })])), }, Example { description: "Check if input string contains 'banana'", example: "'hello' | str contains 'banana'", result: Some(Value::test_bool(false)), }, Example { description: "Check if list contains string", example: "[one two three] | str contains o", result: Some(Value::test_list(vec![ Value::test_bool(true), Value::test_bool(true), Value::test_bool(false), ])), }, ] } } fn action( input: &Value, Arguments { case_insensitive, substring, .. }: &Arguments, head: Span, ) -> Value { match input { Value::String { val, .. } => Value::bool( if *case_insensitive { val.to_folded_case() .contains(substring.to_folded_case().as_str()) } else { val.contains(substring) }, head, ), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrContains {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/substring.rs
crates/nu-command/src/strings/str_/substring.rs
use std::ops::Bound; use crate::{grapheme_flags, grapheme_flags_const}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::{IntRange, engine::StateWorkingSet}; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone)] pub struct StrSubstring; struct Arguments { range: IntRange, cell_paths: Option<Vec<CellPath>>, graphemes: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } impl Command for StrSubstring { fn name(&self) -> &str { "str substring" } fn signature(&self) -> Signature { Signature::build("str substring") .input_output_types(vec![ (Type::String, Type::String), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String))), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .switch( "grapheme-clusters", "count indexes and split using grapheme clusters (all visible chars have length 1)", Some('g'), ) .switch( "utf-8-bytes", "count indexes and split using UTF-8 bytes (default; non-ASCII chars have length 2+)", Some('b'), ) .required( "range", SyntaxShape::Any, "The indexes to substring [start end].", ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, turn strings at the given cell paths into substrings.", ) .category(Category::Strings) } fn description(&self) -> &str { "Get part of a string. Note that the first character of a string is index 0." } fn search_terms(&self) -> Vec<&str> { vec!["slice"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let range: IntRange = 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 args = Arguments { range, cell_paths, graphemes: grapheme_flags(engine_state, stack, call)?, }; operate(action, args, input, call.head, engine_state.signals()).map(|pipeline| { // a substring of text/json is not necessarily text/json itself let metadata = pipeline.metadata().map(|m| m.with_content_type(None)); pipeline.set_metadata(metadata) }) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let range: IntRange = call.req_const(working_set, 0)?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { range, cell_paths, graphemes: grapheme_flags_const(working_set, call)?, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) .map(|pipeline| { // a substring of text/json is not necessarily text/json itself let metadata = pipeline.metadata().map(|m| m.with_content_type(None)); pipeline.set_metadata(metadata) }) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Get a substring \"nushell\" from the text \"good nushell\" using a range", example: " 'good nushell' | str substring 5..11", result: Some(Value::test_string("nushell")), }, Example { description: "Count indexes and split using grapheme clusters", example: " '🇯🇵ほげ ふが ぴよ' | str substring --grapheme-clusters 4..5", result: Some(Value::test_string("ふが")), }, Example { description: "sub string by negative index", example: " 'good nushell' | str substring 5..-2", result: Some(Value::test_string("nushel")), }, ] } } fn action(input: &Value, args: &Arguments, head: Span) -> Value { match input { Value::String { val: s, .. } => { let s = if args.graphemes { let indices = s .grapheme_indices(true) .map(|(idx, s)| (idx, s.len())) .collect::<Vec<_>>(); let (idx_start, idx_end) = args.range.absolute_bounds(indices.len()); let idx_range = match idx_end { Bound::Excluded(end) => &indices[idx_start..end], Bound::Included(end) => &indices[idx_start..=end], Bound::Unbounded => &indices[idx_start..], }; if let Some((start, end)) = idx_range.first().zip(idx_range.last()) { let start = start.0; let end = end.0 + end.1; s[start..end].to_owned() } else { String::new() } } else { let (start, end) = args.range.absolute_bounds(s.len()); let s = match end { Bound::Excluded(end) => &s.as_bytes()[start..end], Bound::Included(end) => &s.as_bytes()[start..=end], Bound::Unbounded => &s.as_bytes()[start..], }; String::from_utf8_lossy(s).into_owned() }; Value::string(s, head) } // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => Value::error( ShellError::UnsupportedInput { msg: "Only string values are supported".into(), input: format!("input type: {:?}", other.get_type()), msg_span: head, input_span: other.span(), }, head, ), } } #[cfg(test)] #[allow(clippy::reversed_empty_ranges)] mod tests { use nu_protocol::IntRange; use super::{Arguments, Span, StrSubstring, Value, action}; #[test] fn test_examples() { use crate::test_examples; test_examples(StrSubstring {}) } #[derive(Clone, Copy, Debug)] struct RangeHelper { start: i64, end: i64, inclusion: nu_protocol::ast::RangeInclusion, } #[derive(Debug)] struct Expectation<'a> { range: RangeHelper, expected: &'a str, } impl From<std::ops::RangeInclusive<i64>> for RangeHelper { fn from(value: std::ops::RangeInclusive<i64>) -> Self { RangeHelper { start: *value.start(), end: *value.end(), inclusion: nu_protocol::ast::RangeInclusion::Inclusive, } } } impl From<std::ops::Range<i64>> for RangeHelper { fn from(value: std::ops::Range<i64>) -> Self { RangeHelper { start: value.start, end: value.end, inclusion: nu_protocol::ast::RangeInclusion::RightExclusive, } } } impl From<RangeHelper> for IntRange { fn from(value: RangeHelper) -> Self { match IntRange::new( Value::test_int(value.start), Value::test_int(value.start + (if value.start <= value.end { 1 } else { -1 })), Value::test_int(value.end), value.inclusion, Span::test_data(), ) { Ok(val) => val, Err(e) => { panic!("{value:?}: {e:?}") } } } } impl Expectation<'_> { fn range(&self) -> IntRange { self.range.into() } } fn expectation(word: &str, range: impl Into<RangeHelper>) -> Expectation<'_> { Expectation { range: range.into(), expected: word, } } #[test] fn substrings_indexes() { let word = Value::test_string("andres"); let cases = vec![ expectation("", 0..0), expectation("a", 0..=0), expectation("an", 0..=1), expectation("and", 0..=2), expectation("andr", 0..=3), expectation("andre", 0..=4), expectation("andres", 0..=5), expectation("andres", 0..=6), expectation("a", 0..=-6), expectation("an", 0..=-5), expectation("and", 0..=-4), expectation("andr", 0..=-3), expectation("andre", 0..=-2), expectation("andres", 0..=-1), // str substring [ -4 , _ ] // str substring -4 , expectation("dres", -4..=i64::MAX), expectation("", 0..=-110), expectation("", 6..=0), expectation("", 6..=-1), expectation("", 6..=-2), expectation("", 6..=-3), expectation("", 6..=-4), expectation("", 6..=-5), expectation("", 6..=-6), ]; for expectation in &cases { println!("{expectation:?}"); let expected = expectation.expected; let actual = action( &word, &Arguments { range: expectation.range(), cell_paths: None, graphemes: false, }, Span::test_data(), ); assert_eq!(actual, Value::test_string(expected)); } } #[test] fn use_utf8_bytes() { let word = Value::string(String::from("🇯🇵ほげ ふが ぴよ"), Span::test_data()); let range: RangeHelper = (4..=5).into(); let options = Arguments { cell_paths: None, range: range.into(), graphemes: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_string("�")); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/replace.rs
crates/nu-command/src/strings/str_/replace.rs
use fancy_regex::{Captures, NoExpand, Regex}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::{ClosureEval, command_prelude::*}; use std::sync::Arc; enum ReplacementValue { String(Arc<Spanned<String>>), Closure(Box<Spanned<ClosureEval>>), } struct Arguments { all: bool, find: Spanned<String>, replace: ReplacementValue, cell_paths: Option<Vec<CellPath>>, literal_replace: bool, no_regex: bool, multiline: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct StrReplace; impl Command for StrReplace { fn name(&self) -> &str { "str replace" } fn signature(&self) -> Signature { Signature::build("str replace") .input_output_types(vec![ (Type::String, Type::String), // TODO: clarify behavior with cell-path-rest argument (Type::table(), Type::table()), (Type::record(), Type::record()), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), ]) .required("find", SyntaxShape::String, "The pattern to find.") .required("replace", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Closure(None)]), "The replacement string, or a closure that generates it." ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, operate on strings at the given cell paths.", ) .switch("all", "replace all occurrences of the pattern", Some('a')) .switch( "no-expand", "do not expand capture groups (like $name) in the replacement string", Some('n'), ) .switch( "regex", "match the pattern as a regular expression in the input, instead of a substring", Some('r'), ) .switch( "multiline", "multi-line regex mode (implies --regex): ^ and $ match begin/end of line; equivalent to (?m)", Some('m'), ) .allow_variants_without_examples(true) .category(Category::Strings) } fn description(&self) -> &str { "Find and replace text." } fn extra_description(&self) -> &str { r#"The pattern to find can be a substring (default) or a regular expression (with `--regex`). The replacement can be a a string, possibly containing references to numbered (`$1` etc) or named capture groups (`$name`), or it can be closure that is invoked for each match. In the latter case, the closure is invoked with the entire match as its input and any capture groups as its argument. It must return a string that will be used as a replacement for the match. "# } fn search_terms(&self) -> Vec<&str> { vec!["search", "shift", "switch", "regex"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let find: Spanned<String> = call.req(engine_state, stack, 0)?; let replace = match call.req(engine_state, stack, 1)? { Value::Closure { val, internal_span, .. } => Ok(ReplacementValue::Closure(Box::new( ClosureEval::new(engine_state, stack, *val).into_spanned(internal_span), ))), Value::String { val, internal_span, .. } => Ok(ReplacementValue::String(Arc::new( val.into_spanned(internal_span), ))), val => Err(ShellError::TypeMismatch { err_message: "unsupported replacement value type".to_string(), span: val.span(), }), }?; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 2)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let literal_replace = call.has_flag(engine_state, stack, "no-expand")?; let no_regex = !call.has_flag(engine_state, stack, "regex")? && !call.has_flag(engine_state, stack, "multiline")?; let multiline = call.has_flag(engine_state, stack, "multiline")?; let args = Arguments { all: call.has_flag(engine_state, stack, "all")?, find, replace, cell_paths, literal_replace, no_regex, multiline, }; operate(action, args, input, call.head, engine_state.signals()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let find: Spanned<String> = call.req_const(working_set, 0)?; let replace: Spanned<String> = call.req_const(working_set, 1)?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 2)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let literal_replace = call.has_flag_const(working_set, "no-expand")?; let no_regex = !call.has_flag_const(working_set, "regex")? && !call.has_flag_const(working_set, "multiline")?; let multiline = call.has_flag_const(working_set, "multiline")?; let args = Arguments { all: call.has_flag_const(working_set, "all")?, find, replace: ReplacementValue::String(Arc::new(replace)), cell_paths, literal_replace, no_regex, multiline, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Find and replace the first occurrence of a substring", example: r"'c:\some\cool\path' | str replace 'c:\some\cool' '~'", result: Some(Value::test_string("~\\path")), }, Example { description: "Find and replace all occurrences of a substring", example: r#"'abc abc abc' | str replace --all 'b' 'z'"#, result: Some(Value::test_string("azc azc azc")), }, Example { description: "Find and replace contents with capture group using regular expression", example: "'my_library.rb' | str replace -r '(.+).rb' '$1.nu'", result: Some(Value::test_string("my_library.nu")), }, Example { description: "Find and replace contents with capture group using regular expression, with escapes", example: "'hello=world' | str replace -r '\\$?(?<varname>.*)=(?<value>.*)' '$$$varname = $value'", result: Some(Value::test_string("$hello = world")), }, Example { description: "Find and replace all occurrences of found string using regular expression", example: "'abc abc abc' | str replace --all --regex 'b' 'z'", result: Some(Value::test_string("azc azc azc")), }, Example { description: "Find and replace all occurrences of found string in table using regular expression", example: "[[ColA ColB ColC]; [abc abc ads]] | str replace --all --regex 'b' 'z' ColA ColC", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_string("azc"), "ColB" => Value::test_string("abc"), "ColC" => Value::test_string("ads"), })])), }, Example { description: "Find and replace all occurrences of found string in record using regular expression", example: "{ KeyA: abc, KeyB: abc, KeyC: ads } | str replace --all --regex 'b' 'z' KeyA KeyC", result: Some(Value::test_record(record! { "KeyA" => Value::test_string("azc"), "KeyB" => Value::test_string("abc"), "KeyC" => Value::test_string("ads"), })), }, Example { description: "Find and replace contents without using the replace parameter as a regular expression", example: r"'dogs_$1_cats' | str replace -r '\$1' '$2' -n", result: Some(Value::test_string("dogs_$2_cats")), }, Example { description: "Use captures to manipulate the input text using regular expression", example: r#""abc-def" | str replace -r "(.+)-(.+)" "${2}_${1}""#, result: Some(Value::test_string("def_abc")), }, Example { description: "Find and replace with fancy-regex using regular expression", example: r"'a successful b' | str replace -r '\b([sS])uc(?:cs|s?)e(ed(?:ed|ing|s?)|ss(?:es|ful(?:ly)?|i(?:ons?|ve(?:ly)?)|ors?)?)\b' '${1}ucce$2'", result: Some(Value::test_string("a successful b")), }, Example { description: "Find and replace with fancy-regex using regular expression", example: r#"'GHIKK-9+*' | str replace -r '[*[:xdigit:]+]' 'z'"#, result: Some(Value::test_string("GHIKK-z+*")), }, Example { description: "Find and replace on individual lines using multiline regular expression", example: r#""non-matching line\n123. one line\n124. another line\n" | str replace --all --multiline '^[0-9]+\. ' ''"#, result: Some(Value::test_string( "non-matching line\none line\nanother line\n", )), }, Example { description: "Find and replace backslash escape sequences using a closure", example: r#"'string: \"abc\" backslash: \\ newline:\nend' | str replace -a -r '\\(.)' {|char| if $char == "n" { "\n" } else { $char } }"#, result: Some(Value::test_string( "string: \"abc\" backslash: \\ newline:\nend", )), }, ] } } fn action( input: &Value, Arguments { find, replace, all, literal_replace, no_regex, multiline, .. }: &Arguments, head: Span, ) -> Value { match input { Value::String { val, .. } => { let find_str: &str = &find.item; if *no_regex { // just use regular string replacement vs regular expressions let replace_str: Result<Arc<Spanned<String>>, (ShellError, Span)> = match replace { ReplacementValue::String(replace_str) => Ok(replace_str.clone()), ReplacementValue::Closure(closure) => { // find_str is fixed, so we need to run the closure only once let mut closure_eval = closure.item.clone(); let span = closure.span; let result: Result<Value, ShellError> = closure_eval .run_with_value(Value::string(find.item.clone(), find.span)) .and_then(|result| result.into_value(span)); match result { Ok(Value::String { val, .. }) => Ok(Arc::new(val.into_spanned(span))), Ok(res) => Err(( ShellError::RuntimeTypeMismatch { expected: Type::String, actual: res.get_type(), span: res.span(), }, span, )), Err(error) => Err((error, span)), } } }; match replace_str { Ok(replace_str) => { if *all { Value::string(val.replace(find_str, &replace_str.item), head) } else { Value::string(val.replacen(find_str, &replace_str.item, 1), head) } } Err((error, span)) => Value::error(error, span), } } else { // use regular expressions to replace strings let flags = match multiline { true => "(?m)", false => "", }; let regex_string = flags.to_string() + find_str; let regex = Regex::new(&regex_string); match (regex, replace) { (Ok(re), ReplacementValue::String(replace_str)) => { if *all { Value::string( { if *literal_replace { re.replace_all(val, NoExpand(&replace_str.item)).to_string() } else { re.replace_all(val, &replace_str.item).to_string() } }, head, ) } else { Value::string( { if *literal_replace { re.replace(val, NoExpand(&replace_str.item)).to_string() } else { re.replace(val, &replace_str.item).to_string() } }, head, ) } } (Ok(re), ReplacementValue::Closure(closure)) => { let span = closure.span; // TODO: We only need to clone the evaluator here because // operate() doesn't allow us to have a mutable reference // to Arguments. Would it be worth the effort to change operate() // and all commands that use it? let mut closure_eval = closure.item.clone(); let mut first_error: Option<ShellError> = None; let replacer = |caps: &Captures| { for capture in caps.iter().skip(1) { let arg = match capture { Some(m) => Value::string(m.as_str().to_string(), head), None => Value::nothing(head), }; closure_eval.add_arg(arg); } let value = match caps.get(0) { Some(m) => Value::string(m.as_str().to_string(), head), None => Value::nothing(head), }; let result: Result<Value, ShellError> = closure_eval .run_with_input(PipelineData::value(value, None)) .and_then(|result| result.into_value(span)); match result { Ok(Value::String { val, .. }) => val.to_string(), Ok(res) => { first_error = Some(ShellError::RuntimeTypeMismatch { expected: Type::String, actual: res.get_type(), span: res.span(), }); "".to_string() } Err(e) => { first_error = Some(e); "".to_string() } } }; let result = if *all { Value::string(re.replace_all(val, replacer).to_string(), head) } else { Value::string(re.replace(val, replacer).to_string(), head) }; match first_error { None => result, Some(error) => Value::error(error, span), } } (Err(e), _) => Value::error( ShellError::IncorrectValue { msg: format!("Regex error: {e}"), val_span: find.span, call_span: head, }, find.span, ), } } } Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod tests { use super::*; use super::{Arguments, StrReplace, action}; fn test_spanned_string(val: &str) -> Spanned<String> { Spanned { item: String::from(val), span: Span::test_data(), } } #[test] fn test_examples() { use crate::test_examples; test_examples(StrReplace {}) } #[test] fn can_have_capture_groups() { let word = Value::test_string("Cargo.toml"); let options = Arguments { find: test_spanned_string("Cargo.(.+)"), replace: ReplacementValue::String(Arc::new(test_spanned_string("Carga.$1"))), cell_paths: None, literal_replace: false, all: false, no_regex: false, multiline: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_string("Carga.toml")); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/mod.rs
crates/nu-command/src/strings/str_/mod.rs
mod case; mod contains; mod distance; mod ends_with; mod expand; mod index_of; mod join; mod length; mod replace; mod reverse; mod starts_with; mod stats; mod substring; mod trim; pub use case::*; pub use contains::StrContains; pub use distance::StrDistance; pub use ends_with::StrEndswith; pub use expand::StrExpand; pub use index_of::StrIndexOf; pub use join::*; pub use length::StrLength; pub use replace::StrReplace; pub use reverse::StrReverse; pub use starts_with::StrStartsWith; pub use stats::StrStats; pub use substring::StrSubstring; pub use trim::StrTrim;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/join.rs
crates/nu-command/src/strings/str_/join.rs
use chrono::Datelike; use nu_engine::command_prelude::*; use nu_protocol::{Signals, shell_error::io::IoError}; use std::io::Write; #[derive(Clone)] pub struct StrJoin; impl Command for StrJoin { fn name(&self) -> &str { "str join" } fn signature(&self) -> Signature { Signature::build("str join") .input_output_types(vec![ (Type::List(Box::new(Type::Any)), Type::String), (Type::String, Type::String), ]) .optional( "separator", SyntaxShape::String, "Optional separator to use when creating string.", ) .allow_variants_without_examples(true) .category(Category::Strings) } fn description(&self) -> &str { "Concatenate multiple strings into a single string, with an optional separator between each." } fn search_terms(&self) -> Vec<&str> { vec!["collect", "concatenate"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Option<String> = call.opt(engine_state, stack, 0)?; run(engine_state, call, input, separator) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Option<String> = call.opt_const(working_set, 0)?; run(working_set.permanent(), call, input, separator) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a string from input", example: "['nu', 'shell'] | str join", result: Some(Value::test_string("nushell")), }, Example { description: "Create a string from input with a separator", example: "['nu', 'shell'] | str join '-'", result: Some(Value::test_string("nu-shell")), }, ] } } fn run( engine_state: &EngineState, call: &Call, input: PipelineData, separator: Option<String>, ) -> Result<PipelineData, ShellError> { let config = engine_state.config.clone(); let span = call.head; let metadata = input.metadata(); let mut iter = input.into_iter(); let mut first = true; let output = ByteStream::from_fn( span, Signals::empty(), ByteStreamType::String, move |buffer| { let from_io_error = IoError::factory(span, None); // Write each input to the buffer if let Some(value) = iter.next() { // Write the separator if this is not the first if first { first = false; } else if let Some(separator) = &separator { write!(buffer, "{separator}").map_err(&from_io_error)?; } match value { Value::Error { error, .. } => { return Err(*error); } Value::Date { val, .. } => { let date_str = if val.year() >= 0 { val.to_rfc2822() } else { val.to_rfc3339() }; write!(buffer, "{date_str}").map_err(&from_io_error)? } value => write!(buffer, "{}", value.to_expanded_string("\n", &config)) .map_err(&from_io_error)?, } Ok(true) } else { Ok(false) } }, ); Ok(PipelineData::byte_stream(output, metadata)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrJoin {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/ends_with.rs
crates/nu-command/src/strings/str_/ends_with.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_utils::IgnoreCaseExt; struct Arguments { substring: String, cell_paths: Option<Vec<CellPath>>, case_insensitive: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct StrEndswith; impl Command for StrEndswith { fn name(&self) -> &str { "str ends-with" } fn signature(&self) -> Signature { Signature::build("str ends-with") .input_output_types(vec![ (Type::String, Type::Bool), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Bool))), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required("string", SyntaxShape::String, "The string to match.") .rest( "rest", SyntaxShape::CellPath, "For a data structure input, check strings at the given cell paths, and replace with result.", ) .switch("ignore-case", "search is case insensitive", Some('i')) .category(Category::Strings) } fn description(&self) -> &str { "Check if an input ends with a string." } fn search_terms(&self) -> Vec<&str> { vec!["suffix", "match", "find", "search"] } fn is_const(&self) -> bool { true } 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 args = Arguments { substring: call.req::<String>(engine_state, stack, 0)?, cell_paths, case_insensitive: call.has_flag(engine_state, stack, "ignore-case")?, }; operate(action, args, input, call.head, engine_state.signals()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { substring: call.req_const::<String>(working_set, 0)?, cell_paths, case_insensitive: call.has_flag_const(working_set, "ignore-case")?, }; operate( action, args, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Checks if string ends with '.rb'", example: "'my_library.rb' | str ends-with '.rb'", result: Some(Value::test_bool(true)), }, Example { description: "Checks if strings end with '.txt'", example: "['my_library.rb', 'README.txt'] | str ends-with '.txt'", result: Some(Value::test_list(vec![ Value::test_bool(false), Value::test_bool(true), ])), }, Example { description: "Checks if string ends with '.RB', case-insensitive", example: "'my_library.rb' | str ends-with --ignore-case '.RB'", result: Some(Value::test_bool(true)), }, ] } } fn action(input: &Value, args: &Arguments, head: Span) -> Value { match input { Value::String { val: s, .. } => { let ends_with = if args.case_insensitive { s.to_folded_case() .ends_with(&args.substring.to_folded_case()) } else { s.ends_with(&args.substring) }; Value::bool(ends_with, head) } Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrEndswith {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/length.rs
crates/nu-command/src/strings/str_/length.rs
use crate::{grapheme_flags, grapheme_flags_const}; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use unicode_segmentation::UnicodeSegmentation; struct Arguments { cell_paths: Option<Vec<CellPath>>, graphemes: bool, chars: bool, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct StrLength; impl Command for StrLength { fn name(&self) -> &str { "str length" } fn signature(&self) -> Signature { Signature::build("str length") .input_output_types(vec![ (Type::String, Type::Int), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::Int))), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .switch( "grapheme-clusters", "count length in grapheme clusters (all visible chars have length 1)", Some('g'), ) .switch( "utf-8-bytes", "count length in UTF-8 bytes (default; all non-ASCII chars have length 2+)", Some('b'), ) .switch( "chars", "count length in chars", Some('c'), ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, replace strings at the given cell paths with their length.", ) .category(Category::Strings) } fn description(&self) -> &str { "Output the length of any strings in the pipeline." } fn search_terms(&self) -> Vec<&str> { vec!["size", "count"] } fn is_const(&self) -> bool { true } 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 chars = call.has_flag(engine_state, stack, "chars")?; run( cell_paths, engine_state, call, input, grapheme_flags(engine_state, stack, call)?, chars, ) } 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 chars = call.has_flag_const(working_set, "chars")?; run( cell_paths, working_set.permanent(), call, input, grapheme_flags_const(working_set, call)?, chars, ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return the lengths of a string in bytes", example: "'hello' | str length", result: Some(Value::test_int(5)), }, Example { description: "Count length of a string in grapheme clusters", example: "'🇯🇵ほげ ふが ぴよ' | str length --grapheme-clusters", result: Some(Value::test_int(9)), }, Example { description: "Return the lengths of multiple strings in bytes", example: "['hi' 'there'] | str length", result: Some(Value::list( vec![Value::test_int(2), Value::test_int(5)], Span::test_data(), )), }, Example { description: "Return the lengths of a string in chars", example: "'hällo' | str length --chars", result: Some(Value::test_int(5)), }, ] } } fn run( cell_paths: Vec<CellPath>, engine_state: &EngineState, call: &Call, input: PipelineData, graphemes: bool, chars: bool, ) -> Result<PipelineData, ShellError> { let args = Arguments { cell_paths: (!cell_paths.is_empty()).then_some(cell_paths), graphemes, chars, }; operate(action, args, input, call.head, engine_state.signals()) } fn action(input: &Value, arg: &Arguments, head: Span) -> Value { match input { Value::String { val, .. } => Value::int( if arg.graphemes { val.graphemes(true).count() } else if arg.chars { val.chars().count() } else { val.len() } as i64, head, ), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn use_utf8_bytes() { let word = Value::string(String::from("🇯🇵ほげ ふが ぴよ"), Span::test_data()); let options = Arguments { cell_paths: None, graphemes: false, chars: false, }; let actual = action(&word, &options, Span::test_data()); assert_eq!(actual, Value::test_int(28)); } #[test] fn test_examples() { use crate::test_examples; test_examples(StrLength {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/case/upcase.rs
crates/nu-command/src/strings/str_/case/upcase.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrUpcase; impl Command for StrUpcase { fn name(&self) -> &str { "str upcase" } fn signature(&self) -> Signature { Signature::build("str upcase") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Make text uppercase." } fn search_terms(&self) -> Vec<&str> { vec!["uppercase", "upper case"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; operate(engine_state, call, input, column_paths) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column_paths: Vec<CellPath> = call.rest_const(working_set, 0)?; operate(working_set.permanent(), call, input, column_paths) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Upcase contents", example: "'nu' | str upcase", result: Some(Value::test_string("NU")), }] } } fn operate( engine_state: &EngineState, call: &Call, input: PipelineData, column_paths: Vec<CellPath>, ) -> Result<PipelineData, ShellError> { let head = call.head; input.map( move |v| { if column_paths.is_empty() { action(&v, head) } else { let mut ret = v; for path in &column_paths { let r = ret.update_cell_path(&path.members, Box::new(move |old| action(old, head))); if let Err(error) = r { return Value::error(error, head); } } ret } }, engine_state.signals(), ) } fn action(input: &Value, head: Span) -> Value { match input { Value::String { val: s, .. } => Value::string(s.to_uppercase(), head), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod tests { use super::*; use super::{StrUpcase, action}; #[test] fn test_examples() { use crate::test_examples; test_examples(StrUpcase {}) } #[test] fn upcases() { let word = Value::test_string("andres"); let actual = action(&word, Span::test_data()); let expected = Value::test_string("ANDRES"); assert_eq!(actual, expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/case/capitalize.rs
crates/nu-command/src/strings/str_/case/capitalize.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrCapitalize; impl Command for StrCapitalize { fn name(&self) -> &str { "str capitalize" } fn signature(&self) -> Signature { Signature::build("str capitalize") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Capitalize first letter of text." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "style", "caps", "upper"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; operate(engine_state, call, input, column_paths) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column_paths: Vec<CellPath> = call.rest_const(working_set, 0)?; operate(working_set.permanent(), call, input, column_paths) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Capitalize contents", example: "'good day' | str capitalize", result: Some(Value::test_string("Good day")), }, Example { description: "Capitalize contents", example: "'anton' | str capitalize", result: Some(Value::test_string("Anton")), }, Example { description: "Capitalize a column in a table", example: "[[lang, gems]; [nu_test, 100]] | str capitalize lang", result: Some(Value::test_list(vec![Value::test_record(record! { "lang" => Value::test_string("Nu_test"), "gems" => Value::test_int(100), })])), }, ] } } fn operate( engine_state: &EngineState, call: &Call, input: PipelineData, column_paths: Vec<CellPath>, ) -> Result<PipelineData, ShellError> { let head = call.head; input.map( move |v| { if column_paths.is_empty() { action(&v, head) } else { let mut ret = v; for path in &column_paths { let r = ret.update_cell_path(&path.members, Box::new(move |old| action(old, head))); if let Err(error) = r { return Value::error(error, head); } } ret } }, engine_state.signals(), ) } fn action(input: &Value, head: Span) -> Value { match input { Value::String { val, .. } => Value::string(uppercase_helper(val), head), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } fn uppercase_helper(s: &str) -> String { // apparently more performant https://stackoverflow.com/questions/38406793/why-is-capitalizing-the-first-letter-of-a-string-so-convoluted-in-rust let mut chars = s.chars(); match chars.next() { None => String::new(), Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrCapitalize {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/case/mod.rs
crates/nu-command/src/strings/str_/case/mod.rs
mod capitalize; mod downcase; mod str_; mod upcase; pub use capitalize::StrCapitalize; pub use downcase::StrDowncase; pub use str_::Str; pub use upcase::StrUpcase; use nu_cmd_base::input_handler::{CmdArgument, operate as general_operate}; use nu_engine::command_prelude::*; struct Arguments<F: Fn(&str) -> String + Send + Sync + 'static> { case_operation: &'static F, cell_paths: Option<Vec<CellPath>>, } impl<F: Fn(&str) -> String + Send + Sync + 'static> CmdArgument for Arguments<F> { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } pub fn operate<F>( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, case_operation: &'static F, ) -> Result<PipelineData, ShellError> where F: Fn(&str) -> String + Send + Sync + 'static, { let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let args = Arguments { case_operation, cell_paths, }; general_operate(action, args, input, call.head, engine_state.signals()) } fn action<F>(input: &Value, args: &Arguments<F>, head: Span) -> Value where F: Fn(&str) -> String + Send + Sync + 'static, { let case_operation = args.case_operation; match input { Value::String { val, .. } => Value::string(case_operation(val), head), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/case/downcase.rs
crates/nu-command/src/strings/str_/case/downcase.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrDowncase; impl Command for StrDowncase { fn name(&self) -> &str { "str downcase" } fn signature(&self) -> Signature { Signature::build("str downcase") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, convert strings at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Make text lowercase." } fn search_terms(&self) -> Vec<&str> { vec!["lower case", "lowercase"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; operate(engine_state, call, input, column_paths) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let column_paths: Vec<CellPath> = call.rest_const(working_set, 0)?; operate(working_set.permanent(), call, input, column_paths) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Downcase contents", example: "'NU' | str downcase", result: Some(Value::test_string("nu")), }, Example { description: "Downcase contents", example: "'TESTa' | str downcase", result: Some(Value::test_string("testa")), }, Example { description: "Downcase contents", example: "[[ColA ColB]; [Test ABC]] | str downcase ColA", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_string("test"), "ColB" => Value::test_string("ABC"), })])), }, Example { description: "Downcase contents", example: "[[ColA ColB]; [Test ABC]] | str downcase ColA ColB", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_string("test"), "ColB" => Value::test_string("abc"), })])), }, ] } } fn operate( engine_state: &EngineState, call: &Call, input: PipelineData, column_paths: Vec<CellPath>, ) -> Result<PipelineData, ShellError> { let head = call.head; input.map( move |v| { if column_paths.is_empty() { action(&v, head) } else { let mut ret = v; for path in &column_paths { let r = ret.update_cell_path(&path.members, Box::new(move |old| action(old, head))); if let Err(error) = r { return Value::error(error, head); } } ret } }, engine_state.signals(), ) } fn action(input: &Value, head: Span) -> Value { match input { Value::String { val, .. } => Value::string(val.to_lowercase(), head), Value::Error { .. } => input.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: head, src_span: input.span(), }, head, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(StrDowncase {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/case/str_.rs
crates/nu-command/src/strings/str_/case/str_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Str; impl Command for Str { fn name(&self) -> &str { "str" } fn signature(&self) -> Signature { Signature::build("str") .category(Category::Strings) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for working with string 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/strings/str_/trim/trim_.rs
crates/nu-command/src/strings/str_/trim/trim_.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct StrTrim; struct Arguments { to_trim: Option<char>, trim_side: TrimSide, cell_paths: Option<Vec<CellPath>>, mode: ActionMode, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } pub enum TrimSide { Left, Right, Both, } impl Command for StrTrim { fn name(&self) -> &str { "str trim" } fn signature(&self) -> Signature { Signature::build("str trim") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, trim strings at the given cell paths.", ) .named( "char", SyntaxShape::String, "character to trim (default: whitespace)", Some('c'), ) .switch( "left", "trims characters only from the beginning of the string", Some('l'), ) .switch( "right", "trims characters only from the end of the string", Some('r'), ) .category(Category::Strings) } fn description(&self) -> &str { "Trim whitespace or specific character." } fn search_terms(&self) -> Vec<&str> { vec!["whitespace", "strip", "lstrip", "rstrip"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let character = call.get_flag::<Spanned<String>>(engine_state, stack, "char")?; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let left = call.has_flag(engine_state, stack, "left")?; let right = call.has_flag(engine_state, stack, "right")?; run( character, cell_paths, (left, right), call, input, engine_state, ) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let character = call.get_flag_const::<Spanned<String>>(working_set, "char")?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 0)?; let left = call.has_flag_const(working_set, "left")?; let right = call.has_flag_const(working_set, "right")?; run( character, cell_paths, (left, right), call, input, working_set.permanent(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Trim whitespace", example: "'Nu shell ' | str trim", result: Some(Value::test_string("Nu shell")), }, Example { description: "Trim a specific character (not the whitespace)", example: "'=== Nu shell ===' | str trim --char '='", result: Some(Value::test_string(" Nu shell ")), }, Example { description: "Trim whitespace from the beginning of string", example: "' Nu shell ' | str trim --left", result: Some(Value::test_string("Nu shell ")), }, Example { description: "Trim whitespace from the end of string", example: "' Nu shell ' | str trim --right", result: Some(Value::test_string(" Nu shell")), }, Example { description: "Trim a specific character only from the end of the string", example: "'=== Nu shell ===' | str trim --right --char '='", result: Some(Value::test_string("=== Nu shell ")), }, ] } } fn run( character: Option<Spanned<String>>, cell_paths: Vec<CellPath>, (left, right): (bool, bool), call: &Call, input: PipelineData, engine_state: &EngineState, ) -> Result<PipelineData, ShellError> { let to_trim = match character.as_ref() { Some(v) => { if v.item.chars().count() > 1 { return Err(ShellError::GenericError { error: "Trim only works with single character".into(), msg: "needs single character".into(), span: Some(v.span), help: None, inner: vec![], }); } v.item.chars().next() } None => None, }; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let mode = match cell_paths { None => ActionMode::Global, Some(_) => ActionMode::Local, }; let trim_side = match (left, right) { (true, true) => TrimSide::Both, (true, false) => TrimSide::Left, (false, true) => TrimSide::Right, (false, false) => TrimSide::Both, }; let args = Arguments { to_trim, trim_side, cell_paths, mode, }; operate(action, args, input, call.head, engine_state.signals()) } #[derive(Debug, Copy, Clone)] pub enum ActionMode { Local, Global, } fn action(input: &Value, arg: &Arguments, head: Span) -> Value { let char_ = arg.to_trim; let trim_side = &arg.trim_side; let mode = &arg.mode; match input { Value::String { val: s, .. } => Value::string(trim(s, char_, trim_side), head), // Propagate errors by explicitly matching them before the final case. Value::Error { .. } => input.clone(), other => { let span = other.span(); match mode { ActionMode::Global => match other { Value::Record { val: record, .. } => { let new_record = record .iter() .map(|(k, v)| (k.clone(), action(v, arg, head))) .collect(); Value::record(new_record, span) } Value::List { vals, .. } => { let new_vals = vals.iter().map(|v| action(v, arg, head)).collect(); Value::list(new_vals, span) } _ => input.clone(), }, ActionMode::Local => Value::error( ShellError::UnsupportedInput { msg: "Only string values are supported".into(), input: format!("input type: {:?}", other.get_type()), msg_span: head, input_span: other.span(), }, head, ), } } } } fn trim(s: &str, char_: Option<char>, trim_side: &TrimSide) -> String { let delimiters = match char_ { Some(c) => vec![c], // Trying to make this trim work like rust default trim() // which uses is_whitespace() as a default None => vec![ ' ', // space '\x09', // horizontal tab '\x0A', // new line, line feed '\x0B', // vertical tab '\x0C', // form feed, new page '\x0D', // carriage return ], //whitespace }; match trim_side { TrimSide::Left => s.trim_start_matches(&delimiters[..]).to_string(), TrimSide::Right => s.trim_end_matches(&delimiters[..]).to_string(), TrimSide::Both => s.trim_matches(&delimiters[..]).to_string(), } } #[cfg(test)] mod tests { use crate::strings::str_::trim::trim_::*; use nu_protocol::{Span, Value}; #[test] fn test_examples() { use crate::test_examples; test_examples(StrTrim {}) } fn make_record(cols: Vec<&str>, vals: Vec<&str>) -> Value { Value::test_record( cols.into_iter() .zip(vals) .map(|(col, val)| (col.to_owned(), Value::test_string(val))) .collect(), ) } fn make_list(vals: Vec<&str>) -> Value { Value::list( vals.iter() .map(|x| Value::test_string(x.to_string())) .collect(), Span::test_data(), ) } #[test] fn trims() { let word = Value::test_string("andres "); let expected = Value::test_string("andres"); let args = Arguments { to_trim: None, trim_side: TrimSide::Both, cell_paths: None, mode: ActionMode::Local, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_global() { let word = Value::test_string(" global "); let expected = Value::test_string("global"); let args = Arguments { to_trim: None, trim_side: TrimSide::Both, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_ignores_numbers() { let number = Value::test_int(2020); let expected = Value::test_int(2020); let args = Arguments { to_trim: None, trim_side: TrimSide::Both, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&number, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_row() { let row = make_record(vec!["a", "b"], vec![" c ", " d "]); // ["a".to_string() => string(" c "), " b ".to_string() => string(" d ")]; let expected = make_record(vec!["a", "b"], vec!["c", "d"]); let args = Arguments { to_trim: None, trim_side: TrimSide::Both, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&row, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_table() { let row = make_list(vec![" a ", "d"]); let expected = make_list(vec!["a", "d"]); let args = Arguments { to_trim: None, trim_side: TrimSide::Both, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&row, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_custom_character_both_ends() { let word = Value::test_string("!#andres#!"); let expected = Value::test_string("#andres#"); let args = Arguments { to_trim: Some('!'), trim_side: TrimSide::Both, cell_paths: None, mode: ActionMode::Local, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_whitespace_from_left() { let word = Value::test_string(" andres "); let expected = Value::test_string("andres "); let args = Arguments { to_trim: None, trim_side: TrimSide::Left, cell_paths: None, mode: ActionMode::Local, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_left_ignores_numbers() { let number = Value::test_int(2020); let expected = Value::test_int(2020); let args = Arguments { to_trim: None, trim_side: TrimSide::Left, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&number, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_left_global() { let word = Value::test_string(" global "); let expected = Value::test_string("global "); let args = Arguments { to_trim: None, trim_side: TrimSide::Left, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_left_row() { let row = make_record(vec!["a", "b"], vec![" c ", " d "]); let expected = make_record(vec!["a", "b"], vec!["c ", "d "]); let args = Arguments { to_trim: None, trim_side: TrimSide::Left, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&row, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_left_table() { let row = Value::list( vec![ Value::test_string(" a "), Value::test_int(65), Value::test_string(" d"), ], Span::test_data(), ); let expected = Value::list( vec![ Value::test_string("a "), Value::test_int(65), Value::test_string("d"), ], Span::test_data(), ); let args = Arguments { to_trim: None, trim_side: TrimSide::Left, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&row, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_custom_chars_from_left() { let word = Value::test_string("!!! andres !!!"); let expected = Value::test_string(" andres !!!"); let args = Arguments { to_trim: Some('!'), trim_side: TrimSide::Left, cell_paths: None, mode: ActionMode::Local, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_whitespace_from_right() { let word = Value::test_string(" andres "); let expected = Value::test_string(" andres"); let args = Arguments { to_trim: None, trim_side: TrimSide::Right, cell_paths: None, mode: ActionMode::Local, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_right_global() { let word = Value::test_string(" global "); let expected = Value::test_string(" global"); let args = Arguments { to_trim: None, trim_side: TrimSide::Right, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_right_ignores_numbers() { let number = Value::test_int(2020); let expected = Value::test_int(2020); let args = Arguments { to_trim: None, trim_side: TrimSide::Right, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&number, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_right_row() { let row = make_record(vec!["a", "b"], vec![" c ", " d "]); let expected = make_record(vec!["a", "b"], vec![" c", " d"]); let args = Arguments { to_trim: None, trim_side: TrimSide::Right, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&row, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn global_trim_right_table() { let row = Value::list( vec![ Value::test_string(" a "), Value::test_int(65), Value::test_string(" d"), ], Span::test_data(), ); let expected = Value::list( vec![ Value::test_string(" a"), Value::test_int(65), Value::test_string(" d"), ], Span::test_data(), ); let args = Arguments { to_trim: None, trim_side: TrimSide::Right, cell_paths: None, mode: ActionMode::Global, }; let actual = action(&row, &args, Span::test_data()); assert_eq!(actual, expected); } #[test] fn trims_custom_chars_from_right() { let word = Value::test_string("#@! andres !@#"); let expected = Value::test_string("#@! andres !@"); let args = Arguments { to_trim: Some('#'), trim_side: TrimSide::Right, cell_paths: None, mode: ActionMode::Local, }; let actual = action(&word, &args, Span::test_data()); assert_eq!(actual, expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/str_/trim/mod.rs
crates/nu-command/src/strings/str_/trim/mod.rs
mod trim_; pub use trim_::StrTrim;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/base/base32hex.rs
crates/nu-command/src/strings/base/base32hex.rs
use nu_engine::command_prelude::*; const EXTRA_USAGE: &str = r"This command uses an alternative Base32 alphabet, defined in RFC 4648, section 7. Note this command will collect stream input."; #[derive(Clone)] pub struct DecodeBase32Hex; impl Command for DecodeBase32Hex { fn name(&self) -> &str { "decode base32hex" } fn signature(&self) -> Signature { Signature::build("decode base32hex") .input_output_types(vec![(Type::String, Type::Binary)]) .allow_variants_without_examples(true) .switch("nopad", "Reject input with padding.", None) .category(Category::Formats) } fn description(&self) -> &str { "Encode a base32hex value." } fn extra_description(&self) -> &str { EXTRA_USAGE } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Decode arbitrary binary data", example: r#""ATNAQ===" | decode base32hex"#, result: Some(Value::test_binary(vec![0x57, 0x6E, 0xAD])), }, Example { description: "Decode an encoded string", example: r#""D1KG====" | decode base32hex | decode"#, result: None, }, Example { description: "Parse a string without padding", example: r#""ATNAQ" | decode base32hex --nopad"#, result: Some(Value::test_binary(vec![0x57, 0x6E, 0xAD])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag(engine_state, stack, "nopad")? { data_encoding::BASE32HEX_NOPAD } else { data_encoding::BASE32HEX }; super::decode(encoding, call.head, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag_const(working_set, "nopad")? { data_encoding::BASE32HEX_NOPAD } else { data_encoding::BASE32HEX }; super::decode(encoding, call.head, input) } } #[derive(Clone)] pub struct EncodeBase32Hex; impl Command for EncodeBase32Hex { fn name(&self) -> &str { "encode base32hex" } fn signature(&self) -> Signature { Signature::build("encode base32hex") .input_output_types(vec![ (Type::String, Type::String), (Type::Binary, Type::String), ]) .switch("nopad", "Don't pad the output.", None) .category(Category::Formats) } fn description(&self) -> &str { "Encode a binary value or a string using base32hex." } fn extra_description(&self) -> &str { EXTRA_USAGE } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Encode a binary value", example: r#"0x[57 6E AD] | encode base32hex"#, result: Some(Value::test_string("ATNAQ===")), }, Example { description: "Encode a string", example: r#""hello there" | encode base32hex"#, result: Some(Value::test_string("D1IMOR3F41Q6GPBICK======")), }, Example { description: "Don't apply padding to the output", example: r#""hello there" | encode base32hex --nopad"#, result: Some(Value::test_string("D1IMOR3F41Q6GPBICK")), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag(engine_state, stack, "nopad")? { data_encoding::BASE32HEX_NOPAD } else { data_encoding::BASE32HEX }; super::encode(encoding, call.head, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag_const(working_set, "nopad")? { data_encoding::BASE32HEX_NOPAD } else { data_encoding::BASE32HEX }; super::encode(encoding, call.head, input) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples_decode() { crate::test_examples(DecodeBase32Hex) } #[test] fn test_examples_encode() { crate::test_examples(EncodeBase32Hex) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/base/base64.rs
crates/nu-command/src/strings/base/base64.rs
use data_encoding::Encoding; use nu_engine::command_prelude::*; const EXTRA_USAGE: &str = r"The default alphabet is taken from RFC 4648, section 4. A URL-safe version is available. Note this command will collect stream input."; fn get_encoding_from_flags(url: bool, nopad: bool) -> Encoding { match (url, nopad) { (false, false) => data_encoding::BASE64, (false, true) => data_encoding::BASE64_NOPAD, (true, false) => data_encoding::BASE64URL, (true, true) => data_encoding::BASE64URL_NOPAD, } } fn get_encoding( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<Encoding, ShellError> { let url = call.has_flag(engine_state, stack, "url")?; let nopad = call.has_flag(engine_state, stack, "nopad")?; Ok(get_encoding_from_flags(url, nopad)) } fn get_encoding_const(working_set: &StateWorkingSet, call: &Call) -> Result<Encoding, ShellError> { let url = call.has_flag_const(working_set, "url")?; let nopad = call.has_flag_const(working_set, "nopad")?; Ok(get_encoding_from_flags(url, nopad)) } #[derive(Clone)] pub struct DecodeBase64; impl Command for DecodeBase64 { fn name(&self) -> &str { "decode base64" } fn signature(&self) -> Signature { Signature::build("decode base64") .input_output_types(vec![(Type::String, Type::Binary)]) .allow_variants_without_examples(true) .switch("url", "Decode the URL-safe Base64 version.", None) .switch("nopad", "Reject padding.", None) .category(Category::Formats) } fn description(&self) -> &str { "Decode a Base64 value." } fn extra_description(&self) -> &str { EXTRA_USAGE } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Decode a Base64 string", example: r#""U29tZSBEYXRh" | decode base64 | decode"#, result: None, }, Example { description: "Decode arbitrary data", example: r#""/w==" | decode base64"#, result: Some(Value::test_binary(vec![0xFF])), }, Example { description: "Decode a URL-safe Base64 string", example: r#""_w==" | decode base64 --url"#, result: Some(Value::test_binary(vec![0xFF])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = get_encoding(engine_state, stack, call)?; super::decode(encoding, call.head, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = get_encoding_const(working_set, call)?; super::decode(encoding, call.head, input) } } #[derive(Clone)] pub struct EncodeBase64; impl Command for EncodeBase64 { fn name(&self) -> &str { "encode base64" } fn signature(&self) -> Signature { Signature::build("encode base64") .input_output_types(vec![ (Type::String, Type::String), (Type::Binary, Type::String), ]) .switch("url", "Use the URL-safe Base64 version.", None) .switch("nopad", "Don't pad the output.", None) .category(Category::Formats) } fn description(&self) -> &str { "Encode a string or binary value using Base64." } fn extra_description(&self) -> &str { EXTRA_USAGE } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Encode a string with Base64", example: r#""Alphabet from A to Z" | encode base64"#, result: Some(Value::test_string("QWxwaGFiZXQgZnJvbSBBIHRvIFo=")), }, Example { description: "Encode arbitrary data", example: r#"0x[BE EE FF] | encode base64"#, result: Some(Value::test_string("vu7/")), }, Example { description: "Use a URL-safe alphabet", example: r#"0x[BE EE FF] | encode base64 --url"#, result: Some(Value::test_string("vu7_")), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = get_encoding(engine_state, stack, call)?; super::encode(encoding, call.head, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = get_encoding_const(working_set, call)?; super::encode(encoding, call.head, input) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples_decode() { crate::test_examples(DecodeBase64) } #[test] fn test_examples_encode() { crate::test_examples(EncodeBase64) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/base/hex.rs
crates/nu-command/src/strings/base/hex.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct DecodeHex; impl Command for DecodeHex { fn name(&self) -> &str { "decode hex" } fn signature(&self) -> Signature { Signature::build("decode hex") .input_output_types(vec![(Type::String, Type::Binary)]) .category(Category::Formats) } fn description(&self) -> &str { "Hex decode a value." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Decode arbitrary binary data", example: r#""09FD" | decode hex"#, result: Some(Value::test_binary(vec![0x09, 0xFD])), }, Example { description: "Lowercase Hex is also accepted", example: r#""09fd" | decode hex"#, result: Some(Value::test_binary(vec![0x09, 0xFD])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { super::decode(data_encoding::HEXLOWER_PERMISSIVE, call.head, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { super::decode(data_encoding::HEXLOWER_PERMISSIVE, call.span(), input) } } #[derive(Clone)] pub struct EncodeHex; impl Command for EncodeHex { fn name(&self) -> &str { "encode hex" } fn signature(&self) -> Signature { Signature::build("encode hex") .input_output_types(vec![ (Type::String, Type::String), (Type::Binary, Type::String), ]) .switch("lower", "Encode to lowercase hex.", None) .category(Category::Formats) } fn description(&self) -> &str { "Hex encode a binary value or a string." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Encode a binary value", example: r#"0x[C3 06] | encode hex"#, result: Some(Value::test_string("C306")), }, Example { description: "Encode a string", example: r#""hello" | encode hex"#, result: Some(Value::test_string("68656C6C6F")), }, Example { description: "Output a Lowercase version of the encoding", example: r#"0x[AD EF] | encode hex --lower"#, result: Some(Value::test_string("adef")), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag(engine_state, stack, "lower")? { data_encoding::HEXLOWER } else { data_encoding::HEXUPPER }; super::encode(encoding, call.head, input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag_const(working_set, "lower")? { data_encoding::HEXLOWER } else { data_encoding::HEXUPPER }; super::encode(encoding, call.head, input) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples_decode() { crate::test_examples(DecodeHex) } #[test] fn test_examples_encode() { crate::test_examples(EncodeHex) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/base/mod.rs
crates/nu-command/src/strings/base/mod.rs
#![allow(unused)] use data_encoding::Encoding; use nu_engine::command_prelude::*; mod base32; mod base32hex; mod base64; mod hex; pub use base32::{DecodeBase32, EncodeBase32}; pub use base32hex::{DecodeBase32Hex, EncodeBase32Hex}; pub use base64::{DecodeBase64, EncodeBase64}; pub use hex::{DecodeHex, EncodeHex}; pub fn decode( encoding: Encoding, call_span: Span, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input.metadata(); let (input_str, input_span) = get_string(input, call_span)?; let output = match encoding.decode(input_str.as_bytes()) { Ok(output) => output, Err(err) => { return Err(ShellError::IncorrectValue { msg: err.to_string(), val_span: input_span, call_span, }); } }; Ok(Value::binary(output, call_span).into_pipeline_data_with_metadata(metadata)) } pub fn encode( encoding: Encoding, call_span: Span, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input.metadata(); let (input_bytes, _) = get_binary(input, call_span)?; let output = encoding.encode(&input_bytes); Ok(Value::string(output, call_span).into_pipeline_data_with_metadata(metadata)) } fn get_string(input: PipelineData, call_span: Span) -> Result<(String, Span), ShellError> { match input { PipelineData::Value(val, ..) => { let span = val.span(); match val { Value::String { val, .. } => Ok((val, span)), value => Err(ShellError::TypeMismatch { err_message: "binary or string".to_owned(), span: call_span, }), } } PipelineData::ListStream(list, ..) => Err(ShellError::PipelineMismatch { exp_input_type: "binary or string".to_owned(), dst_span: call_span, src_span: list.span(), }), PipelineData::ByteStream(stream, ..) => { let span = stream.span(); Ok((stream.into_string()?, span)) } PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: call_span, }), } } fn get_binary(input: PipelineData, call_span: Span) -> Result<(Vec<u8>, Span), ShellError> { match input { PipelineData::Value(val, ..) => { let span = val.span(); match val { Value::Binary { val, .. } => Ok((val, span)), Value::String { val, .. } => Ok((val.into_bytes(), span)), value => Err(ShellError::TypeMismatch { err_message: "binary or string".to_owned(), span: call_span, }), } } PipelineData::ListStream(list, ..) => Err(ShellError::PipelineMismatch { exp_input_type: "binary or string".to_owned(), dst_span: call_span, src_span: list.span(), }), PipelineData::ByteStream(stream, ..) => { let span = stream.span(); Ok((stream.into_bytes()?, span)) } PipelineData::Empty => Err(ShellError::PipelineEmpty { dst_span: call_span, }), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/base/base32.rs
crates/nu-command/src/strings/base/base32.rs
use data_encoding::Encoding; use nu_engine::command_prelude::*; const EXTRA_USAGE: &str = r"The default alphabet is taken from RFC 4648, section 6. Note this command will collect stream input."; #[derive(Clone)] pub struct DecodeBase32; impl Command for DecodeBase32 { fn name(&self) -> &str { "decode base32" } fn signature(&self) -> Signature { Signature::build("decode base32") .input_output_types(vec![(Type::String, Type::Binary)]) .allow_variants_without_examples(true) .switch("nopad", "Do not pad the output.", None) .category(Category::Formats) } fn description(&self) -> &str { "Decode a Base32 value." } fn extra_description(&self) -> &str { EXTRA_USAGE } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Decode arbitrary binary data", example: r#""AEBAGBAF" | decode base32"#, result: Some(Value::test_binary(vec![1, 2, 3, 4, 5])), }, Example { description: "Decode an encoded string", example: r#""NBUQ====" | decode base32 | decode"#, result: None, }, Example { description: "Parse a string without padding", example: r#""NBUQ" | decode base32 --nopad"#, result: Some(Value::test_binary(vec![0x68, 0x69])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag(engine_state, stack, "nopad")? { data_encoding::BASE32_NOPAD } else { data_encoding::BASE32 }; super::decode(encoding, call.span(), input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag_const(working_set, "nopad")? { data_encoding::BASE32_NOPAD } else { data_encoding::BASE32 }; super::decode(encoding, call.span(), input) } } #[derive(Clone)] pub struct EncodeBase32; impl Command for EncodeBase32 { fn name(&self) -> &str { "encode base32" } fn signature(&self) -> Signature { Signature::build("encode base32") .input_output_types(vec![ (Type::String, Type::String), (Type::Binary, Type::String), ]) .switch("nopad", "Don't accept padding.", None) .category(Category::Formats) } fn description(&self) -> &str { "Encode a string or binary value using Base32." } fn extra_description(&self) -> &str { EXTRA_USAGE } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Encode a binary value", example: r#"0x[01 02 10] | encode base32"#, result: Some(Value::test_string("AEBBA===")), }, Example { description: "Encode a string", example: r#""hello there" | encode base32"#, result: Some(Value::test_string("NBSWY3DPEB2GQZLSMU======")), }, Example { description: "Don't apply padding to the output", example: r#""hi" | encode base32 --nopad"#, result: Some(Value::test_string("NBUQ")), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag(engine_state, stack, "nopad")? { data_encoding::BASE32_NOPAD } else { data_encoding::BASE32 }; super::encode(encoding, call.span(), input) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding = if call.has_flag_const(working_set, "nopad")? { data_encoding::BASE32_NOPAD } else { data_encoding::BASE32 }; super::encode(encoding, call.span(), input) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples_decode() { crate::test_examples(DecodeBase32) } #[test] fn test_examples_encode() { crate::test_examples(EncodeBase32) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/encode_decode/encode.rs
crates/nu-command/src/strings/encode_decode/encode.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Encode; impl Command for Encode { fn name(&self) -> &str { "encode" } fn description(&self) -> &str { // Note: "Encode a UTF-8 string into other forms" is semantically incorrect because // Nushell strings, as abstract values, have no user-facing encoding. // (Remember that "encoding" exclusively means "how the characters are // observably represented by bytes"). "Encode a string into bytes." } fn search_terms(&self) -> Vec<&str> { vec!["text", "encoding", "decoding"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("encode") .input_output_types(vec![(Type::String, Type::Binary)]) .required("encoding", SyntaxShape::String, "The text encoding to use.") .switch( "ignore-errors", "when a character isn't in the given encoding, replace with a HTML entity (like `&#127880;`)", Some('i'), ) .category(Category::Strings) } fn extra_description(&self) -> &str { r#"Multiple encodings are supported; here are a few: big5, euc-jp, euc-kr, gbk, iso-8859-1, cp1252, latin5 Note that since the Encoding Standard doesn't specify encoders for utf-16le and utf-16be, these are not yet supported. More information can be found here: https://docs.rs/encoding_rs/latest/encoding_rs/#utf-16le-utf-16be-and-unicode-encoding-schemes For a more complete list of encodings, please refer to the encoding_rs documentation link at https://docs.rs/encoding_rs/latest/encoding_rs/#statics"# } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Encode an UTF-8 string into Shift-JIS", example: r#""負けると知って戦うのが、遥かに美しいのだ" | encode shift-jis"#, result: Some(Value::binary( vec![ 0x95, 0x89, 0x82, 0xaf, 0x82, 0xe9, 0x82, 0xc6, 0x92, 0x6d, 0x82, 0xc1, 0x82, 0xc4, 0x90, 0xed, 0x82, 0xa4, 0x82, 0xcc, 0x82, 0xaa, 0x81, 0x41, 0x97, 0x79, 0x82, 0xa9, 0x82, 0xc9, 0x94, 0xfc, 0x82, 0xb5, 0x82, 0xa2, 0x82, 0xcc, 0x82, 0xbe, ], Span::test_data(), )), }, Example { description: "Replace characters with HTML entities if they can't be encoded", example: r#""🎈" | encode --ignore-errors shift-jis"#, result: Some(Value::binary( vec![0x26, 0x23, 0x31, 0x32, 0x37, 0x38, 0x38, 0x30, 0x3b], Span::test_data(), )), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding: Spanned<String> = call.req(engine_state, stack, 0)?; let ignore_errors = call.has_flag(engine_state, stack, "ignore-errors")?; run(call, input, encoding, ignore_errors) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding: Spanned<String> = call.req_const(working_set, 0)?; let ignore_errors = call.has_flag_const(working_set, "ignore-errors")?; run(call, input, encoding, ignore_errors) } } fn run( call: &Call, input: PipelineData, encoding: Spanned<String>, ignore_errors: bool, ) -> Result<PipelineData, ShellError> { let head = call.head; match input { PipelineData::ByteStream(stream, ..) => { let span = stream.span(); let s = stream.into_string()?; super::encoding::encode(head, encoding, &s, span, ignore_errors) .map(|val| val.into_pipeline_data()) } PipelineData::Value(v, ..) => { let span = v.span(); match v { Value::String { val: s, .. } => { super::encoding::encode(head, encoding, &s, span, ignore_errors) .map(|val| val.into_pipeline_data()) } Value::Error { error, .. } => Err(*error), _ => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: v.get_type().to_string(), dst_span: head, src_span: v.span(), }), } } // This should be more precise, but due to difficulties in getting spans // from PipelineData::ListStream, this is as it is. _ => Err(ShellError::UnsupportedInput { msg: "non-string input".into(), input: "value originates from here".into(), msg_span: head, input_span: input.span().unwrap_or(head), }), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { crate::test_examples(Encode) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/encode_decode/decode.rs
crates/nu-command/src/strings/encode_decode/decode.rs
use nu_engine::command_prelude::*; use oem_cp::decode_string_complete_table; use std::collections::HashMap; use std::sync::LazyLock; // create a lazycell of all the code_table "Complete" code pages // the commented out code pages are "Incomplete", which means they // are stored as Option<char> and not &[char; 128] static OEM_DECODE: LazyLock<HashMap<usize, &[char; 128]>> = LazyLock::new(|| { let mut m = HashMap::new(); m.insert(437, &oem_cp::code_table::DECODING_TABLE_CP437); // m.insert(720, &oem_cp::code_table::DECODING_TABLE_CP720); m.insert(737, &oem_cp::code_table::DECODING_TABLE_CP737); m.insert(775, &oem_cp::code_table::DECODING_TABLE_CP775); m.insert(850, &oem_cp::code_table::DECODING_TABLE_CP850); m.insert(852, &oem_cp::code_table::DECODING_TABLE_CP852); m.insert(855, &oem_cp::code_table::DECODING_TABLE_CP855); // m.insert(857, &oem_cp::code_table::DECODING_TABLE_CP857); m.insert(858, &oem_cp::code_table::DECODING_TABLE_CP858); m.insert(860, &oem_cp::code_table::DECODING_TABLE_CP860); m.insert(861, &oem_cp::code_table::DECODING_TABLE_CP861); m.insert(862, &oem_cp::code_table::DECODING_TABLE_CP862); m.insert(863, &oem_cp::code_table::DECODING_TABLE_CP863); // m.insert(864, &oem_cp::code_table::DECODING_TABLE_CP864); m.insert(865, &oem_cp::code_table::DECODING_TABLE_CP865); m.insert(866, &oem_cp::code_table::DECODING_TABLE_CP866); // m.insert(869, &oem_cp::code_table::DECODING_TABLE_CP869); // m.insert(874, &oem_cp::code_table::DECODING_TABLE_CP874); m }); #[derive(Clone)] pub struct Decode; impl Command for Decode { fn name(&self) -> &str { "decode" } fn description(&self) -> &str { "Decode bytes into a string." } fn search_terms(&self) -> Vec<&str> { vec!["text", "encoding", "decoding"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("decode") .input_output_types(vec![(Type::Binary, Type::String)]) .optional("encoding", SyntaxShape::String, "The text encoding to use.") .category(Category::Strings) } fn extra_description(&self) -> &str { r#"Multiple encodings are supported; here are a few: big5, euc-jp, euc-kr, gbk, iso-8859-1, utf-16, cp1252, latin5 For a more complete list of encodings please refer to the encoding_rs documentation link at https://docs.rs/encoding_rs/latest/encoding_rs/#statics"# } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Decode the output of an external command", example: "^cat myfile.q | decode utf-8", result: None, }, Example { description: "Decode an UTF-16 string into nushell UTF-8 string", example: r#"0x[00 53 00 6F 00 6D 00 65 00 20 00 44 00 61 00 74 00 61] | decode utf-16be"#, result: Some(Value::string("Some Data".to_owned(), Span::test_data())), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding: Option<Spanned<String>> = call.opt(engine_state, stack, 0)?; run(call, input, encoding) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let encoding: Option<Spanned<String>> = call.opt_const(working_set, 0)?; run(call, input, encoding) } } fn run( call: &Call, input: PipelineData, encoding: Option<Spanned<String>>, ) -> Result<PipelineData, ShellError> { let head = call.head; match input { PipelineData::ByteStream(stream, ..) => { let span = stream.span(); let bytes = stream.into_bytes()?; match encoding { Some(encoding_name) => detect_and_decode(encoding_name, head, bytes), None => super::encoding::detect_encoding_name(head, span, &bytes) .map(|encoding| encoding.decode(&bytes).0.into_owned()) .map(|s| Value::string(s, head)), } .map(|val| val.into_pipeline_data()) } PipelineData::Value(v, ..) => { let input_span = v.span(); match v { Value::Binary { val: bytes, .. } => match encoding { Some(encoding_name) => detect_and_decode(encoding_name, head, bytes), None => super::encoding::detect_encoding_name(head, input_span, &bytes) .map(|encoding| encoding.decode(&bytes).0.into_owned()) .map(|s| Value::string(s, head)), } .map(|val| val.into_pipeline_data()), Value::Error { error, .. } => Err(*error), _ => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "binary".into(), wrong_type: v.get_type().to_string(), dst_span: head, src_span: v.span(), }), } } // This should be more precise, but due to difficulties in getting spans // from PipelineData::ListData, this is as it is. _ => Err(ShellError::UnsupportedInput { msg: "non-binary input".into(), input: "value originates from here".into(), msg_span: head, input_span: input.span().unwrap_or(head), }), } } // Since we have two different decoding mechanisms, we allow oem_cp to be // specified by only a number like `open file | decode 850`. If this decode // parameter parses as a usize then we assume it was intentional and use oem_cp // crate. Otherwise, if it doesn't parse as a usize, we assume it was a string // and use the encoding_rs crate to try and decode it. fn detect_and_decode( encoding_name: Spanned<String>, head: Span, bytes: Vec<u8>, ) -> Result<Value, ShellError> { let dec_table_id = encoding_name.item.parse::<usize>().unwrap_or(0usize); if dec_table_id == 0 { super::encoding::decode(head, encoding_name, &bytes) } else { Ok(Value::string( decode_string_complete_table(&bytes, OEM_DECODE[&dec_table_id]), head, )) } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { crate::test_examples(Decode) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/encode_decode/mod.rs
crates/nu-command/src/strings/encode_decode/mod.rs
mod decode; mod encode; mod encoding; pub use self::decode::Decode; pub use self::encode::Encode;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/encode_decode/encoding.rs
crates/nu-command/src/strings/encode_decode/encoding.rs
use chardetng::EncodingDetector; use encoding_rs::Encoding; use nu_protocol::{ShellError, Span, Spanned, Value}; pub fn detect_encoding_name( head: Span, input: Span, bytes: &[u8], ) -> Result<&'static Encoding, ShellError> { let mut detector = EncodingDetector::new(); let _non_ascii = detector.feed(bytes, false); //Guess(TLD=None(usually used in HTML), Allow_UTF8=True) let (encoding, is_certain) = detector.guess_assess(None, true); if !is_certain { return Err(ShellError::UnsupportedInput { msg: "Input contains unknown encoding, try giving a encoding name".into(), input: "value originates from here".into(), msg_span: head, input_span: input, }); } Ok(encoding) } pub fn decode( head: Span, encoding_name: Spanned<String>, bytes: &[u8], ) -> Result<Value, ShellError> { // Workaround for a bug in the Encodings Specification. let encoding = if encoding_name.item.eq_ignore_ascii_case("utf16") { parse_encoding(encoding_name.span, "utf-16") } else { parse_encoding(encoding_name.span, &encoding_name.item) }?; let (result, ..) = encoding.decode(bytes); Ok(Value::string(result.into_owned(), head)) } pub fn encode( head: Span, encoding_name: Spanned<String>, s: &str, s_span: Span, ignore_errors: bool, ) -> Result<Value, ShellError> { // Workaround for a bug in the Encodings Specification. let encoding = if encoding_name.item.eq_ignore_ascii_case("utf16") { parse_encoding(encoding_name.span, "utf-16") } else { parse_encoding(encoding_name.span, &encoding_name.item) }?; // Since the Encoding Standard doesn't specify encoders for "UTF-16BE" and "UTF-16LE" // Check if the encoding is one of them and return an error if ["UTF-16BE", "UTF-16LE"].contains(&encoding.name()) { return Err(ShellError::GenericError { error: format!(r#"{} encoding is not supported"#, &encoding_name.item), msg: "invalid encoding".into(), span: Some(encoding_name.span), help: Some("refer to https://docs.rs/encoding_rs/latest/encoding_rs/index.html#statics for a valid list of encodings".into()), inner: vec![], }); } let (result, _actual_encoding, replacements) = encoding.encode(s); // Because encoding_rs is a Web-facing crate, it defaults to replacing unknowns with HTML entities. // This behaviour can be enabled with -i. Otherwise, it becomes an error. if replacements && !ignore_errors { // TODO: make GenericError accept two spans (including head) Err(ShellError::GenericError { error: "error while encoding string".into(), msg: format!("string contained characters not in {}", &encoding_name.item), span: Some(s_span), help: None, inner: vec![], }) } else { Ok(Value::binary(result.into_owned(), head)) } } fn parse_encoding(span: Span, label: &str) -> Result<&'static Encoding, ShellError> { // Workaround for a bug in the Encodings Specification. let label = if label.eq_ignore_ascii_case("utf16") { "utf-16" } else { label }; match Encoding::for_label_no_replacement(label.as_bytes()) { None => Err(ShellError::GenericError{ error: format!( r#"{label} is not a valid encoding"# ), msg: "invalid encoding".into(), span: Some(span), help: Some("refer to https://docs.rs/encoding_rs/latest/encoding_rs/index.html#statics for a valid list of encodings".into()), inner: vec![], }), Some(encoding) => Ok(encoding), } } #[cfg(test)] mod test { use super::*; use rstest::rstest; #[rstest] #[case::big5("big5", "簡体字")] #[case::shift_jis("shift-jis", "何だと?……無駄な努力だ?……百も承知だ!")] #[case::euc_jp("euc-jp", "だがな、勝つ望みがある時ばかり、戦うのとは訳が違うぞ!")] #[case::euc_kr("euc-kr", "가셨어요?")] #[case::gbk("gbk", "簡体字")] #[case::iso_8859_1("iso-8859-1", "Some ¼½¿ Data µ¶·¸¹º")] #[case::cp1252("cp1252", "Some ¼½¿ Data")] #[case::latin5("latin5", "Some ¼½¿ Data µ¶·¸¹º")] // Tests for specific renditions of UTF-8 labels #[case::utf8("utf8", "")] #[case::utf_hyphen_8("utf-8", "")] fn smoke(#[case] encoding: String, #[case] expected: &str) { let test_span = Span::test_data(); let encoding = Spanned { item: encoding, span: test_span, }; let encoded = encode(test_span, encoding.clone(), expected, test_span, true).unwrap(); let encoded = encoded.coerce_into_binary().unwrap(); let decoded = decode(test_span, encoding, &encoded).unwrap(); let decoded = decoded.coerce_into_string().unwrap(); assert_eq!(decoded, expected); } #[rstest] #[case::big5(&[186, 251, 176, 242, 164, 106, 168, 229, 161, 93, 87, 105, 107, 105, 112, 101, 100, 105, 97, 161, 94, 170, 204, 161, 65, 186, 244, 184, 244, 172, 176, 194, 166, 161, 70, 182, 176, 164, 209, 164, 85, 170, 190, 161, 66, 165, 124, 174, 252, 168, 165, 161, 66, 178, 179, 164, 72, 167, 211, 161, 65, 174, 209, 166, 202, 172, 236, 178, 106, 161, 67, 169, 108, 167, 64, 170, 204, 161, 65, 186, 251, 176, 242, 180, 67, 197, 233, 176, 242, 170, 247, 183, 124, 164, 93, 161, 67], "Big5")] // FIXME: chardetng fails on this //#[case::shiftjis(&[130, 162, 130, 235, 130, 205, 130, 201, 130, 217, 130, 214, 130, 198, 129, 64, 130, // 191, 130, 232, 130, 202, 130, 233, 130, 240], "SHIFT_JIS")] #[case::eucjp(&[164, 164, 164, 237, 164, 207, 164, 203, 164, 219, 164, 216, 164, 200, 161, 161, 164, 193, 164, 234, 164, 204, 164, 235, 164, 242],"EUC-JP")] #[case::euckr(&[192, 167, 197, 176, 185, 233, 176, 250, 40, 45, 219, 221, 206, 161, 41, 32, 182, 199, 180, 194, 32, 192, 167, 197, 176, 199, 199, 181, 240, 190, 198, 180, 194, 32, 180, 169, 177, 184, 179, 170, 32, 192, 218, 192, 175, 183, 211, 176, 212, 32, 190, 181, 32, 188, 246, 32, 192, 214, 180, 194, 32, 180, 217, 190, 240, 190, 238, 198, 199, 32, 192, 206, 197, 205, 179, 221, 32, 185, 233, 176, 250, 187, 231, 192, 252, 192, 204, 180, 217],"EUC-KR")] #[case::gb2312(&[206, 172, 187, 249, 202, 199, 210, 187, 214, 214, 212, 218, 205, 248, 194, 231, 201, 207, 191, 170, 183, 197, 199, 210, 191, 201, 185, 169, 182, 224, 200, 203, 208, 173, 205, 172, 180, 180, 215, 247, 181, 196, 179, 172, 206, 196, 177, 190, 207, 181, 205, 179, 163, 172, 211, 201, 195, 192, 185, 250, 200, 203, 206, 214, 181, 194, 161, 164, 191, 178, 196, 254, 176, 178, 211, 218, 49, 57, 57, 53, 196, 234, 202, 215, 207, 200, 191, 170, 183, 162], "GB2312")] #[case::tis620(&[199, 212, 185, 226, 180, 199, 202, 236, 45, 49, 50, 53, 50, 224, 187, 231, 185, 195, 203, 209, 202, 205, 209, 161, 162, 195, 208, 225, 186, 186, 203, 185, 214, 232, 167, 228, 186, 181, 236, 183, 213, 232, 227, 170, 233, 161, 209, 186, 205, 209, 161, 201, 195, 197, 208, 181, 212, 185, 32, 193, 209, 161, 182, 217, 161, 227, 170, 233, 227, 185, 205, 167, 164, 236, 187, 195, 208, 161, 205, 186, 195, 216, 232, 185, 224, 161, 232, 210, 227, 185, 228, 193, 226, 164, 195, 171, 205, 191, 183, 236], "TIS-620")] fn smoke_encoding_name(#[case] bytes: &[u8], #[case] expected: &str) { let encoding_name = detect_encoding_name(Span::test_data(), Span::test_data(), bytes).unwrap(); assert_eq!( encoding_name, Encoding::for_label(expected.as_bytes()).unwrap() ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/split/words.rs
crates/nu-command/src/strings/split/words.rs
use crate::{grapheme_flags, grapheme_flags_const}; use fancy_regex::Regex; use nu_engine::command_prelude::*; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone)] pub struct SplitWords; impl Command for SplitWords { fn name(&self) -> &str { "split words" } fn signature(&self) -> Signature { Signature::build("split words") .input_output_types(vec![ (Type::String, Type::List(Box::new(Type::String))), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::List(Box::new(Type::String)))) ), ]) .allow_variants_without_examples(true) .category(Category::Strings) // .switch( // "ignore-hyphenated", // "ignore hyphenated words, splitting at the hyphen", // Some('i'), // ) // .switch( // "ignore-apostrophes", // "ignore apostrophes in words by removing them", // Some('a'), // ) // .switch( // "ignore-punctuation", // "ignore punctuation around words by removing them", // Some('p'), // ) .named( "min-word-length", SyntaxShape::Int, "The minimum word length", Some('l'), ) .switch( "grapheme-clusters", "measure word length in grapheme clusters (requires -l)", Some('g'), ) .switch( "utf-8-bytes", "measure word length in UTF-8 bytes (default; requires -l; non-ASCII chars are length 2+)", Some('b'), ) } fn description(&self) -> &str { "Split a string's words into separate rows." } fn search_terms(&self) -> Vec<&str> { vec!["separate", "divide"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Split the string's words into separate rows", example: "'hello world' | split words", result: Some(Value::list( vec![Value::test_string("hello"), Value::test_string("world")], Span::test_data(), )), }, Example { description: "Split the string's words, of at least 3 characters, into separate rows", example: "'hello to the world' | split words --min-word-length 3", result: Some(Value::list( vec![ Value::test_string("hello"), Value::test_string("the"), Value::test_string("world"), ], Span::test_data(), )), }, Example { description: "A real-world example of splitting words", example: "http get https://www.gutenberg.org/files/11/11-0.txt | str downcase | split words --min-word-length 2 | uniq --count | sort-by count --reverse | first 10", result: None, }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let word_length: Option<usize> = call.get_flag(engine_state, stack, "min-word-length")?; let has_grapheme = call.has_flag(engine_state, stack, "grapheme-clusters")?; let has_utf8 = call.has_flag(engine_state, stack, "utf-8-bytes")?; let graphemes = grapheme_flags(engine_state, stack, call)?; let args = Arguments { word_length, has_grapheme, has_utf8, graphemes, }; split_words(engine_state, call, input, args) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let word_length: Option<usize> = call.get_flag_const(working_set, "min-word-length")?; let has_grapheme = call.has_flag_const(working_set, "grapheme-clusters")?; let has_utf8 = call.has_flag_const(working_set, "utf-8-bytes")?; let graphemes = grapheme_flags_const(working_set, call)?; let args = Arguments { word_length, has_grapheme, has_utf8, graphemes, }; split_words(working_set.permanent(), call, input, args) } } struct Arguments { word_length: Option<usize>, has_grapheme: bool, has_utf8: bool, graphemes: bool, } fn split_words( engine_state: &EngineState, call: &Call, input: PipelineData, args: Arguments, ) -> Result<PipelineData, ShellError> { let span = call.head; // let ignore_hyphenated = call.has_flag(engine_state, stack, "ignore-hyphenated")?; // let ignore_apostrophes = call.has_flag(engine_state, stack, "ignore-apostrophes")?; // let ignore_punctuation = call.has_flag(engine_state, stack, "ignore-punctuation")?; if args.word_length.is_none() { if args.has_grapheme { return Err(ShellError::IncompatibleParametersSingle { msg: "--grapheme-clusters (-g) requires --min-word-length (-l)".to_string(), span, }); } if args.has_utf8 { return Err(ShellError::IncompatibleParametersSingle { msg: "--utf-8-bytes (-b) requires --min-word-length (-l)".to_string(), span, }); } } input.map( move |x| split_words_helper(&x, args.word_length, span, args.graphemes), engine_state.signals(), ) } fn split_words_helper(v: &Value, word_length: Option<usize>, span: Span, graphemes: bool) -> Value { // There are some options here with this regex. // [^A-Za-z\'] = do not match uppercase or lowercase letters or apostrophes // [^[:alpha:]\'] = do not match any uppercase or lowercase letters or apostrophes // [^\p{L}\'] = do not match any unicode uppercase or lowercase letters or apostrophes // Let's go with the unicode one in hopes that it works on more than just ascii characters let regex_replace = Regex::new(r"[^\p{L}\p{N}\']").expect("regular expression error"); let v_span = v.span(); match v { Value::Error { error, .. } => Value::error(*error.clone(), v_span), v => { let v_span = v.span(); if let Ok(s) = v.as_str() { // let splits = s.unicode_words(); // let words = trim_to_words(s); // let words: Vec<&str> = s.split_whitespace().collect(); let replaced_string = regex_replace.replace_all(s, " ").to_string(); let words = replaced_string .split(' ') .filter_map(|s| { if s.trim() != "" { if let Some(len) = word_length { if if graphemes { s.graphemes(true).count() } else { s.len() } >= len { Some(Value::string(s, v_span)) } else { None } } else { Some(Value::string(s, v_span)) } } else { None } }) .collect::<Vec<Value>>(); Value::list(words, v_span) } else { Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: v.get_type().to_string(), dst_span: span, src_span: v_span, }, v_span, ) } } } } // original at least 1 char long // curl -sL "https://www.gutenberg.org/files/11/11-0.txt" | tr '[:upper:]' '[:lower:]' | grep -oE "[a-z\']{1,}" | ^sort | ^uniq -c | ^sort -nr | head -n 10 // benchmark INCLUDING DOWNLOAD: 1sec 253ms 91µs 511ns // 1839 the // 942 and // 811 to // 695 a // 638 of // 610 it // 553 she // 546 i // 486 you // 462 said // original at least 2 chars long // curl -sL "https://www.gutenberg.org/files/11/11-0.txt" | tr '[:upper:]' '[:lower:]' | grep -oE "[a-z\']{2,}" | ^sort | ^uniq -c | ^sort -nr | head -n 10 // 1839 the // 942 and // 811 to // 638 of // 610 it // 553 she // 486 you // 462 said // 435 in // 403 alice // regex means, replace everything that is not A-Z or a-z or ' with a space // ❯ $contents | str replace "[^A-Za-z\']" " " -a | split row ' ' | where ($it | str length) > 1 | uniq -i -c | sort-by count --reverse | first 10 // benchmark: 1sec 775ms 471µs 600ns // ╭───┬───────┬───────╮ // │ # │ value │ count │ // ├───┼───────┼───────┤ // │ 0 │ the │ 1839 │ // │ 1 │ and │ 942 │ // │ 2 │ to │ 811 │ // │ 3 │ of │ 638 │ // │ 4 │ it │ 610 │ // │ 5 │ she │ 553 │ // │ 6 │ you │ 486 │ // │ 7 │ said │ 462 │ // │ 8 │ in │ 435 │ // │ 9 │ alice │ 403 │ // ╰───┴───────┴───────╯ // $alice |str replace "[^A-Za-z\']" " " -a | split row ' ' | uniq -i -c | sort-by count --reverse | first 10 // benchmark: 1sec 518ms 701µs 200ns // ╭───┬───────┬───────╮ // │ # │ value │ count │ // ├───┼───────┼───────┤ // │ 0 │ the │ 1839 │ // │ 1 │ and │ 942 │ // │ 2 │ to │ 811 │ // │ 3 │ a │ 695 │ // │ 4 │ of │ 638 │ // │ 5 │ it │ 610 │ // │ 6 │ she │ 553 │ // │ 7 │ i │ 546 │ // │ 8 │ you │ 486 │ // │ 9 │ said │ 462 │ // ├───┼───────┼───────┤ // │ # │ value │ count │ // ╰───┴───────┴───────╯ // s.unicode_words() // $alice | str downcase | split words | sort | uniq -c | sort-by count | reverse | first 10 // benchmark: 4sec 965ms 285µs 800ns // ╭───┬───────┬───────╮ // │ # │ value │ count │ // ├───┼───────┼───────┤ // │ 0 │ the │ 1839 │ // │ 1 │ and │ 941 │ // │ 2 │ to │ 811 │ // │ 3 │ a │ 695 │ // │ 4 │ of │ 638 │ // │ 5 │ it │ 542 │ // │ 6 │ she │ 538 │ // │ 7 │ said │ 460 │ // │ 8 │ in │ 434 │ // │ 9 │ you │ 426 │ // ├───┼───────┼───────┤ // │ # │ value │ count │ // ╰───┴───────┴───────╯ // trim_to_words // benchmark: 5sec 992ms 76µs 200ns // ╭───┬───────┬───────╮ // │ # │ value │ count │ // ├───┼───────┼───────┤ // │ 0 │ the │ 1829 │ // │ 1 │ and │ 918 │ // │ 2 │ to │ 801 │ // │ 3 │ a │ 689 │ // │ 4 │ of │ 632 │ // │ 5 │ she │ 537 │ // │ 6 │ it │ 493 │ // │ 7 │ said │ 457 │ // │ 8 │ in │ 430 │ // │ 9 │ you │ 413 │ // ├───┼───────┼───────┤ // │ # │ value │ count │ // ╰───┴───────┴───────╯ // fn trim_to_words(content: String) -> std::vec::Vec<std::string::String> { // let content: Vec<String> = content // .to_lowercase() // .replace(&['-'][..], " ") // //should 's be replaced? // .replace("'s", "") // .replace( // &[ // '(', ')', ',', '\"', '.', ';', ':', '=', '[', ']', '{', '}', '-', '_', '/', '\'', // '’', '?', '!', '“', '‘', // ][..], // "", // ) // .split_whitespace() // .map(String::from) // .collect::<Vec<String>>(); // content // } // split_whitespace() // benchmark: 9sec 379ms 790µs 900ns // ╭───┬───────┬───────╮ // │ # │ value │ count │ // ├───┼───────┼───────┤ // │ 0 │ the │ 1683 │ // │ 1 │ and │ 783 │ // │ 2 │ to │ 778 │ // │ 3 │ a │ 667 │ // │ 4 │ of │ 605 │ // │ 5 │ she │ 485 │ // │ 6 │ said │ 416 │ // │ 7 │ in │ 406 │ // │ 8 │ it │ 357 │ // │ 9 │ was │ 329 │ // ├───┼───────┼───────┤ // │ # │ value │ count │ // ╰───┴───────┴───────╯ // current // $alice | str downcase | split words | uniq -c | sort-by count --reverse | first 10 // benchmark: 1sec 481ms 604µs 700ns // ╭───┬───────┬───────╮ // │ # │ value │ count │ // ├───┼───────┼───────┤ // │ 0 │ the │ 1839 │ // │ 1 │ and │ 942 │ // │ 2 │ to │ 811 │ // │ 3 │ a │ 695 │ // │ 4 │ of │ 638 │ // │ 5 │ it │ 610 │ // │ 6 │ she │ 553 │ // │ 7 │ i │ 546 │ // │ 8 │ you │ 486 │ // │ 9 │ said │ 462 │ // ├───┼───────┼───────┤ // │ # │ value │ count │ // ╰───┴───────┴───────╯ #[cfg(test)] mod test { use super::*; use nu_test_support::nu; #[test] fn test_incompat_flags() { let out = nu!("'a' | split words -bg -l 2"); assert!(out.err.contains("incompatible_parameters")); } #[test] fn test_incompat_flags_2() { let out = nu!("'a' | split words -g"); assert!(out.err.contains("incompatible_parameters")); } #[test] fn test_examples() { use crate::test_examples; test_examples(SplitWords {}) } #[test] fn mixed_letter_number() { let actual = nu!(r#"echo "a1 b2 c3" | split words | str join ','"#); assert_eq!(actual.out, "a1,b2,c3"); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/split/command.rs
crates/nu-command/src/strings/split/command.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Split; impl Command for Split { fn name(&self) -> &str { "split" } fn signature(&self) -> Signature { Signature::build("split") .category(Category::Strings) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Split contents across desired subcommand (like row, column) via the separator." } 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/strings/split/column.rs
crates/nu-command/src/strings/split/column.rs
use fancy_regex::{Regex, escape}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct SplitColumn; impl Command for SplitColumn { fn name(&self) -> &str { "split column" } fn signature(&self) -> Signature { Signature::build("split column") .input_output_types(vec![ (Type::String, Type::table()), ( // TODO: no test coverage (is this behavior a bug or a feature?) Type::List(Box::new(Type::String)), Type::table(), ), ]) .required( "separator", SyntaxShape::String, "The character or string that denotes what separates columns.", ) .switch("collapse-empty", "remove empty columns", Some('c')) .named( "number", SyntaxShape::Int, "Split into maximum number of items", Some('n'), ) .switch("regex", "separator is a regular expression", Some('r')) .rest( "rest", SyntaxShape::String, "Column names to give the new columns.", ) .category(Category::Strings) } fn description(&self) -> &str { "Split a string into multiple columns using a separator." } fn search_terms(&self) -> Vec<&str> { vec!["separate", "divide", "regex"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Split a string into columns by the specified separator", example: "'a--b--c' | split column '--'", result: Some(Value::test_list(vec![Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_string("b"), "column2" => Value::test_string("c"), })])), }, Example { description: "Split a string into columns of char and remove the empty columns", example: "'abc' | split column --collapse-empty ''", result: Some(Value::test_list(vec![Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_string("b"), "column2" => Value::test_string("c"), })])), }, Example { description: "Split a list of strings into a table", example: "['a-b' 'c-d'] | split column -", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_string("b"), }), Value::test_record(record! { "column0" => Value::test_string("c"), "column1" => Value::test_string("d"), }), ])), }, Example { description: "Split a list of strings into a table, ignoring padding", example: r"['a - b' 'c - d'] | split column --regex '\s*-\s*'", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("a"), "column1" => Value::test_string("b"), }), Value::test_record(record! { "column0" => Value::test_string("c"), "column1" => Value::test_string("d"), }), ])), }, Example { description: "Split into columns, last column may contain the delimiter", example: r"['author: Salina Yoon' r#'title: Where's Ellie?: A Hide-and-Seek Book'#] | split column --number 2 ': ' key value", result: Some(Value::test_list(vec![ Value::test_record(record! { "key" => Value::test_string("author"), "value" => Value::test_string("Salina Yoon"), }), Value::test_record(record! { "key" => Value::test_string("title"), "value" => Value::test_string("Where's Ellie?: A Hide-and-Seek Book"), }), ])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Spanned<String> = call.req(engine_state, stack, 0)?; let rest: Vec<Spanned<String>> = call.rest(engine_state, stack, 1)?; let collapse_empty = call.has_flag(engine_state, stack, "collapse-empty")?; let max_split: Option<usize> = call.get_flag(engine_state, stack, "number")?; let has_regex = call.has_flag(engine_state, stack, "regex")?; let args = Arguments { separator, rest, collapse_empty, max_split, has_regex, }; split_column(engine_state, call, input, args) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Spanned<String> = call.req_const(working_set, 0)?; let rest: Vec<Spanned<String>> = call.rest_const(working_set, 1)?; let collapse_empty = call.has_flag_const(working_set, "collapse-empty")?; let max_split: Option<usize> = call.get_flag_const(working_set, "number")?; let has_regex = call.has_flag_const(working_set, "regex")?; let args = Arguments { separator, rest, collapse_empty, max_split, has_regex, }; split_column(working_set.permanent(), call, input, args) } } struct Arguments { separator: Spanned<String>, rest: Vec<Spanned<String>>, collapse_empty: bool, max_split: Option<usize>, has_regex: bool, } fn split_column( engine_state: &EngineState, call: &Call, input: PipelineData, args: Arguments, ) -> Result<PipelineData, ShellError> { let name_span = call.head; let regex = if args.has_regex { Regex::new(&args.separator.item) } else { let escaped = escape(&args.separator.item); Regex::new(&escaped) } .map_err(|e| ShellError::GenericError { error: "Error with regular expression".into(), msg: e.to_string(), span: Some(args.separator.span), help: None, inner: vec![], })?; input.flat_map( move |x| { split_column_helper( &x, &regex, &args.rest, args.collapse_empty, args.max_split, name_span, ) }, engine_state.signals(), ) } fn split_column_helper( v: &Value, separator: &Regex, rest: &[Spanned<String>], collapse_empty: bool, max_split: Option<usize>, head: Span, ) -> Vec<Value> { if let Ok(s) = v.as_str() { let split_result: Vec<_> = match max_split { Some(max_split) => separator .splitn(s, max_split) .filter_map(|x| x.ok()) .filter(|x| !(collapse_empty && x.is_empty())) .collect(), None => separator .split(s) .filter_map(|x| x.ok()) .filter(|x| !(collapse_empty && x.is_empty())) .collect(), }; let positional: Vec<_> = rest.iter().map(|f| f.item.clone()).collect(); // If they didn't provide column names, make up our own let mut record = Record::new(); if positional.is_empty() { let mut gen_columns = vec![]; for i in 0..split_result.len() { gen_columns.push(format!("column{}", i)); } for (&k, v) in split_result.iter().zip(&gen_columns) { record.push(v, Value::string(k, head)); } } else { for (&k, v) in split_result.iter().zip(&positional) { record.push(v, Value::string(k, head)); } } vec![Value::record(record, head)] } else { match v { Value::Error { error, .. } => { vec![Value::error(*error.clone(), head)] } v => { let span = v.span(); vec![Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: v.get_type().to_string(), dst_span: head, src_span: span, }, span, )] } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SplitColumn {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/split/list.rs
crates/nu-command/src/strings/split/list.rs
use fancy_regex::Regex; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::{FromValue, Signals}; #[derive(Clone)] pub struct SubCommand; impl Command for SubCommand { fn name(&self) -> &str { "split list" } fn signature(&self) -> Signature { Signature::build("split list") .input_output_types(vec![( Type::List(Box::new(Type::Any)), Type::List(Box::new(Type::List(Box::new(Type::Any)))), )]) .required( "separator", SyntaxShape::Any, "The value that denotes what separates the list.", ) .switch( "regex", "separator is a regular expression, matching values that can be coerced into a \ string", Some('r'), ) .param( Flag::new("split") .arg(SyntaxShape::String) .desc("Whether to split lists before, after, or on (default) the separator") .completion(Completion::new_list(&["before", "after", "on"])), ) .category(Category::Filters) } fn description(&self) -> &str { "Split a list into multiple lists using a separator." } fn search_terms(&self) -> Vec<&str> { vec!["separate", "divide", "regex"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Split a list of chars into two lists", example: "[a, b, c, d, e, f, g] | split list d", result: Some(Value::list( vec![ Value::list( vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], Span::test_data(), ), Value::list( vec![ Value::test_string("e"), Value::test_string("f"), Value::test_string("g"), ], Span::test_data(), ), ], Span::test_data(), )), }, Example { description: "Split a list of lists into two lists of lists", example: "[[1,2], [2,3], [3,4]] | split list [2,3]", result: Some(Value::list( vec![ Value::list( vec![Value::list( vec![Value::test_int(1), Value::test_int(2)], Span::test_data(), )], Span::test_data(), ), Value::list( vec![Value::list( vec![Value::test_int(3), Value::test_int(4)], Span::test_data(), )], Span::test_data(), ), ], Span::test_data(), )), }, Example { description: "Split a list of chars into two lists", example: "[a, b, c, d, a, e, f, g] | split list a", result: Some(Value::list( vec![ Value::list(vec![], Span::test_data()), Value::list( vec![ Value::test_string("b"), Value::test_string("c"), Value::test_string("d"), ], Span::test_data(), ), Value::list( vec![ Value::test_string("e"), Value::test_string("f"), Value::test_string("g"), ], Span::test_data(), ), ], Span::test_data(), )), }, Example { description: "Split a list of chars into lists based on multiple characters", example: r"[a, b, c, d, a, e, f, g] | split list --regex '(b|e)'", result: Some(Value::list( vec![ Value::list(vec![Value::test_string("a")], Span::test_data()), Value::list( vec![ Value::test_string("c"), Value::test_string("d"), Value::test_string("a"), ], Span::test_data(), ), Value::list( vec![Value::test_string("f"), Value::test_string("g")], Span::test_data(), ), ], Span::test_data(), )), }, Example { description: "Split a list of numbers on multiples of 3", example: r"[1 2 3 4 5 6 7 8 9 10] | split list {|e| $e mod 3 == 0 }", 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)]), Value::test_list(vec![Value::test_int(10)]), ])), }, Example { description: "Split a list of numbers into lists ending with 0", example: r"[1 2 0 3 4 5 0 6 0 0 7] | split list --split after 0", result: Some(Value::test_list(vec![ Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(0), ]), Value::test_list(vec![ Value::test_int(3), Value::test_int(4), Value::test_int(5), Value::test_int(0), ]), Value::test_list(vec![Value::test_int(6), Value::test_int(0)]), Value::test_list(vec![Value::test_int(0)]), Value::test_list(vec![Value::test_int(7)]), ])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let has_regex = call.has_flag(engine_state, stack, "regex")?; let separator: Value = call.req(engine_state, stack, 0)?; let split: Option<Split> = call.get_flag(engine_state, stack, "split")?; let split = split.unwrap_or(Split::On); let matcher = match separator { Value::Closure { val, .. } => { Matcher::from_closure(ClosureEval::new(engine_state, stack, *val)) } _ => Matcher::new(has_regex, separator)?, }; split_list(engine_state, call, input, matcher, split) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let has_regex = call.has_flag_const(working_set, "regex")?; let separator: Value = call.req_const(working_set, 0)?; let split: Option<Split> = call.get_flag_const(working_set, "split")?; let split = split.unwrap_or(Split::On); let matcher = Matcher::new(has_regex, separator)?; split_list(working_set.permanent(), call, input, matcher, split) } } enum Matcher { Regex(Regex), Direct(Value), Closure(Box<ClosureEval>), } enum Split { On, Before, After, } impl FromValue for Split { fn from_value(v: Value) -> Result<Self, ShellError> { let span = v.span(); let s = <String>::from_value(v)?; match s.as_str() { "on" => Ok(Split::On), "before" => Ok(Split::Before), "after" => Ok(Split::After), _ => Err(ShellError::InvalidValue { valid: "one of: on, before, after".into(), actual: s, span, }), } } } impl Matcher { pub fn new(regex: bool, lhs: Value) -> Result<Self, ShellError> { if regex { Ok(Matcher::Regex(Regex::new(&lhs.coerce_str()?).map_err( |e| ShellError::GenericError { error: "Error with regular expression".into(), msg: e.to_string(), span: match lhs { Value::Error { .. } => None, _ => Some(lhs.span()), }, help: None, inner: vec![], }, )?)) } else { Ok(Matcher::Direct(lhs)) } } pub fn from_closure(closure: ClosureEval) -> Self { Self::Closure(Box::new(closure)) } pub fn compare(&mut self, rhs: &Value) -> Result<bool, ShellError> { Ok(match self { Matcher::Regex(regex) => { if let Ok(rhs_str) = rhs.coerce_str() { regex.is_match(&rhs_str).unwrap_or(false) } else { false } } Matcher::Direct(lhs) => rhs == lhs, Matcher::Closure(closure) => closure .run_with_value(rhs.clone()) .and_then(|data| data.into_value(Span::unknown())) .map(|value| value.is_true()) .unwrap_or(false), }) } } fn split_list( engine_state: &EngineState, call: &Call, input: PipelineData, mut matcher: Matcher, split: Split, ) -> Result<PipelineData, ShellError> { let head = call.head; Ok(SplitList::new( input.into_iter(), engine_state.signals().clone(), split, move |x| matcher.compare(x).unwrap_or(false), ) .map(move |x| Value::list(x, head)) .into_pipeline_data(head, engine_state.signals().clone())) } struct SplitList<I, T, F> { iterator: I, closure: F, done: bool, signals: Signals, split: Split, last_item: Option<T>, } impl<I, T, F> SplitList<I, T, F> where I: Iterator<Item = T>, F: FnMut(&I::Item) -> bool, { fn new(iterator: I, signals: Signals, split: Split, closure: F) -> Self { Self { iterator, closure, done: false, signals, split, last_item: None, } } 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> Iterator for SplitList<I, T, F> where I: Iterator<Item = T>, F: FnMut(&I::Item) -> bool, { type Item = Vec<I::Item>; fn next(&mut self) -> Option<Self::Item> { if self.done { return None; } let mut items = vec![]; if let Some(item) = self.last_item.take() { items.push(item); } loop { match self.inner_iterator_next() { None => { self.done = true; return Some(items); } Some(value) => { if (self.closure)(&value) { match self.split { Split::On => {} Split::Before => { self.last_item = Some(value); } Split::After => { items.push(value); } } return Some(items); } else { items.push(value); } } } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SubCommand {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/split/row.rs
crates/nu-command/src/strings/split/row.rs
use fancy_regex::{Regex, escape}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct SplitRow; impl Command for SplitRow { fn name(&self) -> &str { "split row" } fn signature(&self) -> Signature { Signature::build("split row") .input_output_types(vec![ (Type::String, Type::List(Box::new(Type::String))), ( Type::List(Box::new(Type::String)), (Type::List(Box::new(Type::String))), ), ]) .allow_variants_without_examples(true) .required( "separator", SyntaxShape::String, "A character or regex that denotes what separates rows.", ) .named( "number", SyntaxShape::Int, "Split into maximum number of items", Some('n'), ) .switch("regex", "use regex syntax for separator", Some('r')) .category(Category::Strings) } fn description(&self) -> &str { "Split a string into multiple rows using a separator." } fn search_terms(&self) -> Vec<&str> { vec!["separate", "divide", "regex"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Split a string into rows of char", example: "'abc' | split row ''", result: Some(Value::list( vec![ Value::test_string(""), Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), Value::test_string(""), ], Span::test_data(), )), }, Example { description: "Split a string into rows by the specified separator", example: "'a--b--c' | split row '--'", result: Some(Value::list( vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], Span::test_data(), )), }, Example { description: "Split a string by '-'", example: "'-a-b-c-' | split row '-'", result: Some(Value::list( vec![ Value::test_string(""), Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), Value::test_string(""), ], Span::test_data(), )), }, Example { description: "Split a string by regex", example: r"'a b c' | split row -r '\s+'", result: Some(Value::list( vec![ Value::test_string("a"), Value::test_string("b"), Value::test_string("c"), ], Span::test_data(), )), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Spanned<String> = call.req(engine_state, stack, 0)?; let max_split: Option<usize> = call.get_flag(engine_state, stack, "number")?; let has_regex = call.has_flag(engine_state, stack, "regex")?; let args = Arguments { separator, max_split, has_regex, }; split_row(engine_state, call, input, args) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let separator: Spanned<String> = call.req_const(working_set, 0)?; let max_split: Option<usize> = call.get_flag_const(working_set, "number")?; let has_regex = call.has_flag_const(working_set, "regex")?; let args = Arguments { separator, max_split, has_regex, }; split_row(working_set.permanent(), call, input, args) } } struct Arguments { has_regex: bool, separator: Spanned<String>, max_split: Option<usize>, } fn split_row( engine_state: &EngineState, call: &Call, input: PipelineData, args: Arguments, ) -> Result<PipelineData, ShellError> { let name_span = call.head; let regex = if args.has_regex { Regex::new(&args.separator.item) } else { let escaped = escape(&args.separator.item); Regex::new(&escaped) } .map_err(|e| ShellError::GenericError { error: "Error with regular expression".into(), msg: e.to_string(), span: Some(args.separator.span), help: None, inner: vec![], })?; input.flat_map( move |x| split_row_helper(&x, &regex, args.max_split, name_span), engine_state.signals(), ) } fn split_row_helper(v: &Value, regex: &Regex, max_split: Option<usize>, name: Span) -> Vec<Value> { let span = v.span(); match v { Value::Error { error, .. } => { vec![Value::error(*error.clone(), span)] } v => { let v_span = v.span(); if let Ok(s) = v.coerce_str() { match max_split { Some(max_split) => regex .splitn(&s, max_split) .map(|x| match x { Ok(val) => Value::string(val, v_span), Err(err) => Value::error( ShellError::GenericError { error: "Error with regular expression".into(), msg: err.to_string(), span: Some(v_span), help: None, inner: vec![], }, v_span, ), }) .collect(), None => regex .split(&s) .map(|x| match x { Ok(val) => Value::string(val, v_span), Err(err) => Value::error( ShellError::GenericError { error: "Error with regular expression".into(), msg: err.to_string(), span: Some(v_span), help: None, inner: vec![], }, v_span, ), }) .collect(), } } else { vec![Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: v.get_type().to_string(), dst_span: name, src_span: v_span, }, name, )] } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SplitRow {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/split/chars.rs
crates/nu-command/src/strings/split/chars.rs
use crate::{grapheme_flags, grapheme_flags_const}; use nu_engine::command_prelude::*; use unicode_segmentation::UnicodeSegmentation; #[derive(Clone)] pub struct SplitChars; impl Command for SplitChars { fn name(&self) -> &str { "split chars" } fn signature(&self) -> Signature { Signature::build("split chars") .input_output_types(vec![ (Type::String, Type::List(Box::new(Type::String))), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::List(Box::new(Type::String)))), ), ]) .allow_variants_without_examples(true) .switch("grapheme-clusters", "split on grapheme clusters", Some('g')) .switch( "code-points", "split on code points (default; splits combined characters)", Some('c'), ) .category(Category::Strings) } fn description(&self) -> &str { "Split a string into a list of characters." } fn search_terms(&self) -> Vec<&str> { vec!["character", "separate", "divide"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Split the string into a list of characters", example: "'hello' | split chars", result: Some(Value::list( vec![ Value::test_string("h"), Value::test_string("e"), Value::test_string("l"), Value::test_string("l"), Value::test_string("o"), ], Span::test_data(), )), }, Example { description: "Split on grapheme clusters", example: "'🇯🇵ほげ' | split chars --grapheme-clusters", result: Some(Value::list( vec![ Value::test_string("🇯🇵"), Value::test_string("ほ"), Value::test_string("げ"), ], Span::test_data(), )), }, Example { description: "Split multiple strings into lists of characters", example: "['hello', 'world'] | split chars", result: Some(Value::test_list(vec![ Value::test_list(vec![ Value::test_string("h"), Value::test_string("e"), Value::test_string("l"), Value::test_string("l"), Value::test_string("o"), ]), Value::test_list(vec![ Value::test_string("w"), Value::test_string("o"), Value::test_string("r"), Value::test_string("l"), Value::test_string("d"), ]), ])), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let graphemes = grapheme_flags(engine_state, stack, call)?; split_chars(engine_state, call, input, graphemes) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let graphemes = grapheme_flags_const(working_set, call)?; split_chars(working_set.permanent(), call, input, graphemes) } } fn split_chars( engine_state: &EngineState, call: &Call, input: PipelineData, graphemes: bool, ) -> Result<PipelineData, ShellError> { let span = call.head; input.map( move |x| split_chars_helper(&x, span, graphemes), engine_state.signals(), ) } fn split_chars_helper(v: &Value, name: Span, graphemes: bool) -> Value { let span = v.span(); match v { Value::Error { error, .. } => Value::error(*error.clone(), span), v => { let v_span = v.span(); if let Ok(s) = v.as_str() { Value::list( if graphemes { s.graphemes(true) .collect::<Vec<_>>() .into_iter() .map(move |x| Value::string(x, v_span)) .collect() } else { s.chars() .collect::<Vec<_>>() .into_iter() .map(move |x| Value::string(x, v_span)) .collect() }, v_span, ) } else { Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: v.get_type().to_string(), dst_span: name, src_span: v_span, }, name, ) } } } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SplitChars {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/split/mod.rs
crates/nu-command/src/strings/split/mod.rs
mod chars; mod column; mod command; mod list; mod row; mod words; pub use chars::SplitChars; pub use column::SplitColumn; pub use command::Split; pub use list::SubCommand as SplitList; pub use row::SplitRow; pub use words::SplitWords;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/ansi/ansi_.rs
crates/nu-command/src/strings/ansi/ansi_.rs
use nu_ansi_term::*; use nu_engine::command_prelude::*; use nu_protocol::{Signals, engine::StateWorkingSet}; use std::collections::HashMap; use std::sync::LazyLock; #[derive(Clone)] pub struct Ansi; struct AnsiCode { short_name: Option<&'static str>, long_name: &'static str, code: String, } #[rustfmt::skip] static CODE_LIST: LazyLock<Vec<AnsiCode>> = LazyLock::new(|| { vec![ AnsiCode{ short_name: Some("g"), long_name: "green", code: Color::Green.prefix().to_string()}, AnsiCode{ short_name: Some("gb"), long_name: "green_bold", code: Color::Green.bold().prefix().to_string()}, AnsiCode{ short_name: Some("gu"), long_name: "green_underline", code: Color::Green.underline().prefix().to_string()}, AnsiCode{ short_name: Some("gi"), long_name: "green_italic", code: Color::Green.italic().prefix().to_string()}, AnsiCode{ short_name: Some("gd"), long_name: "green_dimmed", code: Color::Green.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("gr"), long_name: "green_reverse", code: Color::Green.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_g"), long_name: "bg_green", code: Style::new().on(Color::Green).prefix().to_string()}, AnsiCode{ short_name: Some("lg"), long_name: "light_green", code: Color::LightGreen.prefix().to_string()}, AnsiCode{ short_name: Some("lgb"), long_name: "light_green_bold", code: Color::LightGreen.bold().prefix().to_string()}, AnsiCode{ short_name: Some("lgu"), long_name: "light_green_underline", code: Color::LightGreen.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lgi"), long_name: "light_green_italic", code: Color::LightGreen.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lgd"), long_name: "light_green_dimmed", code: Color::LightGreen.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lgr"), long_name: "light_green_reverse", code: Color::LightGreen.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_lg"), long_name: "bg_light_green", code: Style::new().on(Color::LightGreen).prefix().to_string()}, AnsiCode{ short_name: Some("r"), long_name: "red", code: Color::Red.prefix().to_string()}, AnsiCode{ short_name: Some("rb"), long_name: "red_bold", code: Color::Red.bold().prefix().to_string()}, AnsiCode{ short_name: Some("ru"), long_name: "red_underline", code: Color::Red.underline().prefix().to_string()}, AnsiCode{ short_name: Some("ri"), long_name: "red_italic", code: Color::Red.italic().prefix().to_string()}, AnsiCode{ short_name: Some("rd"), long_name: "red_dimmed", code: Color::Red.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("rr"), long_name: "red_reverse", code: Color::Red.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_r"), long_name: "bg_red", code: Style::new().on(Color::Red).prefix().to_string()}, AnsiCode{ short_name: Some("lr"), long_name: "light_red", code: Color::LightRed.prefix().to_string()}, AnsiCode{ short_name: Some("lrb"), long_name: "light_red_bold", code: Color::LightRed.bold().prefix().to_string()}, AnsiCode{ short_name: Some("lru"), long_name: "light_red_underline", code: Color::LightRed.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lri"), long_name: "light_red_italic", code: Color::LightRed.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lrd"), long_name: "light_red_dimmed", code: Color::LightRed.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lrr"), long_name: "light_red_reverse", code: Color::LightRed.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_lr"), long_name: "bg_light_red", code: Style::new().on(Color::LightRed).prefix().to_string()}, AnsiCode{ short_name: Some("b"), long_name: "blue", code: Color::Blue.prefix().to_string()}, AnsiCode{ short_name: Some("bb"), long_name: "blue_bold", code: Color::Blue.bold().prefix().to_string()}, AnsiCode{ short_name: Some("bu"), long_name: "blue_underline", code: Color::Blue.underline().prefix().to_string()}, AnsiCode{ short_name: Some("bi"), long_name: "blue_italic", code: Color::Blue.italic().prefix().to_string()}, AnsiCode{ short_name: Some("bd"), long_name: "blue_dimmed", code: Color::Blue.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("br"), long_name: "blue_reverse", code: Color::Blue.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_b"), long_name: "bg_blue", code: Style::new().on(Color::Blue).prefix().to_string()}, AnsiCode{ short_name: Some("lu"), long_name: "light_blue", code: Color::LightBlue.prefix().to_string()}, AnsiCode{ short_name: Some("lub"), long_name: "light_blue_bold", code: Color::LightBlue.bold().prefix().to_string()}, AnsiCode{ short_name: Some("luu"), long_name: "light_blue_underline", code: Color::LightBlue.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lui"), long_name: "light_blue_italic", code: Color::LightBlue.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lud"), long_name: "light_blue_dimmed", code: Color::LightBlue.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lur"), long_name: "light_blue_reverse", code: Color::LightBlue.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_lu"), long_name: "bg_light_blue", code: Style::new().on(Color::LightBlue).prefix().to_string()}, AnsiCode{ short_name: Some("k"), long_name: "black", code: Color::Black.prefix().to_string()}, AnsiCode{ short_name: Some("kb"), long_name: "black_bold", code: Color::Black.bold().prefix().to_string()}, AnsiCode{ short_name: Some("ku"), long_name: "black_underline", code: Color::Black.underline().prefix().to_string()}, AnsiCode{ short_name: Some("ki"), long_name: "black_italic", code: Color::Black.italic().prefix().to_string()}, AnsiCode{ short_name: Some("kd"), long_name: "black_dimmed", code: Color::Black.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("kr"), long_name: "black_reverse", code: Color::Black.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_k"), long_name: "bg_black", code: Style::new().on(Color::Black).prefix().to_string()}, AnsiCode{ short_name: Some("ligr"), long_name: "light_gray", code: Color::LightGray.prefix().to_string()}, AnsiCode{ short_name: Some("ligrb"), long_name: "light_gray_bold", code: Color::LightGray.bold().prefix().to_string()}, AnsiCode{ short_name: Some("ligru"), long_name: "light_gray_underline", code: Color::LightGray.underline().prefix().to_string()}, AnsiCode{ short_name: Some("ligri"), long_name: "light_gray_italic", code: Color::LightGray.italic().prefix().to_string()}, AnsiCode{ short_name: Some("ligrd"), long_name: "light_gray_dimmed", code: Color::LightGray.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("ligrr"), long_name: "light_gray_reverse", code: Color::LightGray.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_ligr"), long_name: "bg_light_gray", code: Style::new().on(Color::LightGray).prefix().to_string()}, AnsiCode{ short_name: Some("y"), long_name: "yellow", code: Color::Yellow.prefix().to_string()}, AnsiCode{ short_name: Some("yb"), long_name: "yellow_bold", code: Color::Yellow.bold().prefix().to_string()}, AnsiCode{ short_name: Some("yu"), long_name: "yellow_underline", code: Color::Yellow.underline().prefix().to_string()}, AnsiCode{ short_name: Some("yi"), long_name: "yellow_italic", code: Color::Yellow.italic().prefix().to_string()}, AnsiCode{ short_name: Some("yd"), long_name: "yellow_dimmed", code: Color::Yellow.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("yr"), long_name: "yellow_reverse", code: Color::Yellow.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_y"), long_name: "bg_yellow", code: Style::new().on(Color::Yellow).prefix().to_string()}, AnsiCode{ short_name: Some("ly"), long_name: "light_yellow", code: Color::LightYellow.prefix().to_string()}, AnsiCode{ short_name: Some("lyb"), long_name: "light_yellow_bold", code: Color::LightYellow.bold().prefix().to_string()}, AnsiCode{ short_name: Some("lyu"), long_name: "light_yellow_underline", code: Color::LightYellow.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lyi"), long_name: "light_yellow_italic", code: Color::LightYellow.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lyd"), long_name: "light_yellow_dimmed", code: Color::LightYellow.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lyr"), long_name: "light_yellow_reverse", code: Color::LightYellow.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_ly"), long_name: "bg_light_yellow", code: Style::new().on(Color::LightYellow).prefix().to_string()}, AnsiCode{ short_name: Some("p"), long_name: "purple", code: Color::Purple.prefix().to_string()}, AnsiCode{ short_name: Some("pb"), long_name: "purple_bold", code: Color::Purple.bold().prefix().to_string()}, AnsiCode{ short_name: Some("pu"), long_name: "purple_underline", code: Color::Purple.underline().prefix().to_string()}, AnsiCode{ short_name: Some("pi"), long_name: "purple_italic", code: Color::Purple.italic().prefix().to_string()}, AnsiCode{ short_name: Some("pd"), long_name: "purple_dimmed", code: Color::Purple.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("pr"), long_name: "purple_reverse", code: Color::Purple.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_p"), long_name: "bg_purple", code: Style::new().on(Color::Purple).prefix().to_string()}, AnsiCode{ short_name: Some("lp"), long_name: "light_purple", code: Color::LightPurple.prefix().to_string()}, AnsiCode{ short_name: Some("lpb"), long_name: "light_purple_bold", code: Color::LightPurple.bold().prefix().to_string()}, AnsiCode{ short_name: Some("lpu"), long_name: "light_purple_underline", code: Color::LightPurple.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lpi"), long_name: "light_purple_italic", code: Color::LightPurple.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lpd"), long_name: "light_purple_dimmed", code: Color::LightPurple.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lpr"), long_name: "light_purple_reverse", code: Color::LightPurple.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_lp"), long_name: "bg_light_purple", code: Style::new().on(Color::LightPurple).prefix().to_string()}, AnsiCode{ short_name: Some("m"), long_name: "magenta", code: Color::Magenta.prefix().to_string()}, AnsiCode{ short_name: Some("mb"), long_name: "magenta_bold", code: Color::Magenta.bold().prefix().to_string()}, AnsiCode{ short_name: Some("mu"), long_name: "magenta_underline", code: Color::Magenta.underline().prefix().to_string()}, AnsiCode{ short_name: Some("mi"), long_name: "magenta_italic", code: Color::Magenta.italic().prefix().to_string()}, AnsiCode{ short_name: Some("md"), long_name: "magenta_dimmed", code: Color::Magenta.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("mr"), long_name: "magenta_reverse", code: Color::Magenta.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_m"), long_name: "bg_magenta", code: Style::new().on(Color::Magenta).prefix().to_string()}, AnsiCode{ short_name: Some("lm"), long_name: "light_magenta", code: Color::LightMagenta.prefix().to_string()}, AnsiCode{ short_name: Some("lmb"), long_name: "light_magenta_bold", code: Color::LightMagenta.bold().prefix().to_string()}, AnsiCode{ short_name: Some("lmu"), long_name: "light_magenta_underline", code: Color::LightMagenta.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lmi"), long_name: "light_magenta_italic", code: Color::LightMagenta.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lmd"), long_name: "light_magenta_dimmed", code: Color::LightMagenta.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lmr"), long_name: "light_magenta_reverse", code: Color::LightMagenta.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_lm"), long_name: "bg_light_magenta", code: Style::new().on(Color::LightMagenta).prefix().to_string()}, AnsiCode{ short_name: Some("c"), long_name: "cyan", code: Color::Cyan.prefix().to_string()}, AnsiCode{ short_name: Some("cb"), long_name: "cyan_bold", code: Color::Cyan.bold().prefix().to_string()}, AnsiCode{ short_name: Some("cu"), long_name: "cyan_underline", code: Color::Cyan.underline().prefix().to_string()}, AnsiCode{ short_name: Some("ci"), long_name: "cyan_italic", code: Color::Cyan.italic().prefix().to_string()}, AnsiCode{ short_name: Some("cd"), long_name: "cyan_dimmed", code: Color::Cyan.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("cr"), long_name: "cyan_reverse", code: Color::Cyan.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_c"), long_name: "bg_cyan", code: Style::new().on(Color::Cyan).prefix().to_string()}, AnsiCode{ short_name: Some("lc"), long_name: "light_cyan", code: Color::LightCyan.prefix().to_string()}, AnsiCode{ short_name: Some("lcb"), long_name: "light_cyan_bold", code: Color::LightCyan.bold().prefix().to_string()}, AnsiCode{ short_name: Some("lcu"), long_name: "light_cyan_underline", code: Color::LightCyan.underline().prefix().to_string()}, AnsiCode{ short_name: Some("lci"), long_name: "light_cyan_italic", code: Color::LightCyan.italic().prefix().to_string()}, AnsiCode{ short_name: Some("lcd"), long_name: "light_cyan_dimmed", code: Color::LightCyan.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("lcr"), long_name: "light_cyan_reverse", code: Color::LightCyan.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_lc"), long_name: "bg_light_cyan", code: Style::new().on(Color::LightCyan).prefix().to_string()}, AnsiCode{ short_name: Some("w"), long_name: "white", code: Color::White.prefix().to_string()}, AnsiCode{ short_name: Some("wb"), long_name: "white_bold", code: Color::White.bold().prefix().to_string()}, AnsiCode{ short_name: Some("wu"), long_name: "white_underline", code: Color::White.underline().prefix().to_string()}, AnsiCode{ short_name: Some("wi"), long_name: "white_italic", code: Color::White.italic().prefix().to_string()}, AnsiCode{ short_name: Some("wd"), long_name: "white_dimmed", code: Color::White.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("wr"), long_name: "white_reverse", code: Color::White.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_w"), long_name: "bg_white", code: Style::new().on(Color::White).prefix().to_string()}, AnsiCode{ short_name: Some("dgr"), long_name: "dark_gray", code: Color::DarkGray.prefix().to_string()}, AnsiCode{ short_name: Some("dgrb"), long_name: "dark_gray_bold", code: Color::DarkGray.bold().prefix().to_string()}, AnsiCode{ short_name: Some("dgru"), long_name: "dark_gray_underline", code: Color::DarkGray.underline().prefix().to_string()}, AnsiCode{ short_name: Some("dgri"), long_name: "dark_gray_italic", code: Color::DarkGray.italic().prefix().to_string()}, AnsiCode{ short_name: Some("dgrd"), long_name: "dark_gray_dimmed", code: Color::DarkGray.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("dgrr"), long_name: "dark_gray_reverse", code: Color::DarkGray.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_dgr"), long_name: "bg_dark_gray", code: Style::new().on(Color::DarkGray).prefix().to_string()}, AnsiCode{ short_name: Some("def"), long_name: "default", code: Color::Default.prefix().to_string()}, AnsiCode{ short_name: Some("defb"), long_name: "default_bold", code: Color::Default.bold().prefix().to_string()}, AnsiCode{ short_name: Some("defu"), long_name: "default_underline", code: Color::Default.underline().prefix().to_string()}, AnsiCode{ short_name: Some("defi"), long_name: "default_italic", code: Color::Default.italic().prefix().to_string()}, AnsiCode{ short_name: Some("defd"), long_name: "default_dimmed", code: Color::Default.dimmed().prefix().to_string()}, AnsiCode{ short_name: Some("defr"), long_name: "default_reverse", code: Color::Default.reverse().prefix().to_string()}, AnsiCode{ short_name: Some("bg_def"), long_name: "bg_default", code: Style::new().on(Color::Default).prefix().to_string()}, // Xterm 256 colors with conflicting names names preceded by x AnsiCode { short_name: Some("xblack"), long_name: "xterm_black", code: Color::Fixed(0).prefix().to_string()}, AnsiCode { short_name: Some("maroon"), long_name: "xterm_maroon", code: Color::Fixed(1).prefix().to_string()}, AnsiCode { short_name: Some("xgreen"), long_name: "xterm_green", code: Color::Fixed(2).prefix().to_string()}, AnsiCode { short_name: Some("olive"), long_name: "xterm_olive", code: Color::Fixed(3).prefix().to_string()}, AnsiCode { short_name: Some("navy"), long_name: "xterm_navy", code: Color::Fixed(4).prefix().to_string()}, AnsiCode { short_name: Some("xpurplea"), long_name: "xterm_purplea", code: Color::Fixed(5).prefix().to_string()}, AnsiCode { short_name: Some("teal"), long_name: "xterm_teal", code: Color::Fixed(6).prefix().to_string()}, AnsiCode { short_name: Some("silver"), long_name: "xterm_silver", code: Color::Fixed(7).prefix().to_string()}, AnsiCode { short_name: Some("grey"), long_name: "xterm_grey", code: Color::Fixed(8).prefix().to_string()}, AnsiCode { short_name: Some("xred"), long_name: "xterm_red", code: Color::Fixed(9).prefix().to_string()}, AnsiCode { short_name: Some("lime"), long_name: "xterm_lime", code: Color::Fixed(10).prefix().to_string()}, AnsiCode { short_name: Some("xyellow"), long_name: "xterm_yellow", code: Color::Fixed(11).prefix().to_string()}, AnsiCode { short_name: Some("xblue"), long_name: "xterm_blue", code: Color::Fixed(12).prefix().to_string()}, AnsiCode { short_name: Some("fuchsia"), long_name: "xterm_fuchsia", code: Color::Fixed(13).prefix().to_string()}, AnsiCode { short_name: Some("aqua"), long_name: "xterm_aqua", code: Color::Fixed(14).prefix().to_string()}, AnsiCode { short_name: Some("xwhite"), long_name: "xterm_white", code: Color::Fixed(15).prefix().to_string()}, AnsiCode { short_name: Some("grey0"), long_name: "xterm_grey0", code: Color::Fixed(16).prefix().to_string()}, AnsiCode { short_name: Some("navyblue"), long_name: "xterm_navyblue", code: Color::Fixed(17).prefix().to_string()}, AnsiCode { short_name: Some("darkblue"), long_name: "xterm_darkblue", code: Color::Fixed(18).prefix().to_string()}, AnsiCode { short_name: Some("blue3a"), long_name: "xterm_blue3a", code: Color::Fixed(19).prefix().to_string()}, AnsiCode { short_name: Some("blue3b"), long_name: "xterm_blue3b", code: Color::Fixed(20).prefix().to_string()}, AnsiCode { short_name: Some("blue1"), long_name: "xterm_blue1", code: Color::Fixed(21).prefix().to_string()}, AnsiCode { short_name: Some("darkgreen"), long_name: "xterm_darkgreen", code: Color::Fixed(22).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue4a"), long_name: "xterm_deepskyblue4a", code: Color::Fixed(23).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue4b"), long_name: "xterm_deepskyblue4b", code: Color::Fixed(24).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue4c"), long_name: "xterm_deepskyblue4c", code: Color::Fixed(25).prefix().to_string()}, AnsiCode { short_name: Some("dodgerblue3"), long_name: "xterm_dodgerblue3", code: Color::Fixed(26).prefix().to_string()}, AnsiCode { short_name: Some("dodgerblue2"), long_name: "xterm_dodgerblue2", code: Color::Fixed(27).prefix().to_string()}, AnsiCode { short_name: Some("green4"), long_name: "xterm_green4", code: Color::Fixed(28).prefix().to_string()}, AnsiCode { short_name: Some("springgreen4"), long_name: "xterm_springgreen4", code: Color::Fixed(29).prefix().to_string()}, AnsiCode { short_name: Some("turquoise4"), long_name: "xterm_turquoise4", code: Color::Fixed(30).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue3a"), long_name: "xterm_deepskyblue3a", code: Color::Fixed(31).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue3b"), long_name: "xterm_deepskyblue3b", code: Color::Fixed(32).prefix().to_string()}, AnsiCode { short_name: Some("dodgerblue1"), long_name: "xterm_dodgerblue1", code: Color::Fixed(33).prefix().to_string()}, AnsiCode { short_name: Some("green3a"), long_name: "xterm_green3a", code: Color::Fixed(34).prefix().to_string()}, AnsiCode { short_name: Some("springgreen3a"), long_name: "xterm_springgreen3a", code: Color::Fixed(35).prefix().to_string()}, AnsiCode { short_name: Some("darkcyan"), long_name: "xterm_darkcyan", code: Color::Fixed(36).prefix().to_string()}, AnsiCode { short_name: Some("lightseagreen"), long_name: "xterm_lightseagreen", code: Color::Fixed(37).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue2"), long_name: "xterm_deepskyblue2", code: Color::Fixed(38).prefix().to_string()}, AnsiCode { short_name: Some("deepskyblue1"), long_name: "xterm_deepskyblue1", code: Color::Fixed(39).prefix().to_string()}, AnsiCode { short_name: Some("green3b"), long_name: "xterm_green3b", code: Color::Fixed(40).prefix().to_string()}, AnsiCode { short_name: Some("springgreen3b"), long_name: "xterm_springgreen3b", code: Color::Fixed(41).prefix().to_string()}, AnsiCode { short_name: Some("springgreen2a"), long_name: "xterm_springgreen2a", code: Color::Fixed(42).prefix().to_string()}, AnsiCode { short_name: Some("cyan3"), long_name: "xterm_cyan3", code: Color::Fixed(43).prefix().to_string()}, AnsiCode { short_name: Some("darkturquoise"), long_name: "xterm_darkturquoise", code: Color::Fixed(44).prefix().to_string()}, AnsiCode { short_name: Some("turquoise2"), long_name: "xterm_turquoise2", code: Color::Fixed(45).prefix().to_string()}, AnsiCode { short_name: Some("green1"), long_name: "xterm_green1", code: Color::Fixed(46).prefix().to_string()}, AnsiCode { short_name: Some("springgreen2b"), long_name: "xterm_springgreen2b", code: Color::Fixed(47).prefix().to_string()}, AnsiCode { short_name: Some("springgreen1"), long_name: "xterm_springgreen1", code: Color::Fixed(48).prefix().to_string()}, AnsiCode { short_name: Some("mediumspringgreen"), long_name: "xterm_mediumspringgreen", code: Color::Fixed(49).prefix().to_string()}, AnsiCode { short_name: Some("cyan2"), long_name: "xterm_cyan2", code: Color::Fixed(50).prefix().to_string()}, AnsiCode { short_name: Some("cyan1"), long_name: "xterm_cyan1", code: Color::Fixed(51).prefix().to_string()}, AnsiCode { short_name: Some("darkreda"), long_name: "xterm_darkreda", code: Color::Fixed(52).prefix().to_string()}, AnsiCode { short_name: Some("deeppink4a"), long_name: "xterm_deeppink4a", code: Color::Fixed(53).prefix().to_string()}, AnsiCode { short_name: Some("purple4a"), long_name: "xterm_purple4a", code: Color::Fixed(54).prefix().to_string()}, AnsiCode { short_name: Some("purple4b"), long_name: "xterm_purple4b", code: Color::Fixed(55).prefix().to_string()}, AnsiCode { short_name: Some("purple3"), long_name: "xterm_purple3", code: Color::Fixed(56).prefix().to_string()}, AnsiCode { short_name: Some("blueviolet"), long_name: "xterm_blueviolet", code: Color::Fixed(57).prefix().to_string()}, AnsiCode { short_name: Some("orange4a"), long_name: "xterm_orange4a", code: Color::Fixed(58).prefix().to_string()}, AnsiCode { short_name: Some("grey37"), long_name: "xterm_grey37", code: Color::Fixed(59).prefix().to_string()}, AnsiCode { short_name: Some("mediumpurple4"), long_name: "xterm_mediumpurple4", code: Color::Fixed(60).prefix().to_string()}, AnsiCode { short_name: Some("slateblue3a"), long_name: "xterm_slateblue3a", code: Color::Fixed(61).prefix().to_string()}, AnsiCode { short_name: Some("slateblue3b"), long_name: "xterm_slateblue3b", code: Color::Fixed(62).prefix().to_string()}, AnsiCode { short_name: Some("royalblue1"), long_name: "xterm_royalblue1", code: Color::Fixed(63).prefix().to_string()}, AnsiCode { short_name: Some("chartreuse4"), long_name: "xterm_chartreuse4", code: Color::Fixed(64).prefix().to_string()}, AnsiCode { short_name: Some("darkseagreen4a"), long_name: "xterm_darkseagreen4a", code: Color::Fixed(65).prefix().to_string()}, AnsiCode { short_name: Some("paleturquoise4"), long_name: "xterm_paleturquoise4", code: Color::Fixed(66).prefix().to_string()}, AnsiCode { short_name: Some("steelblue"), long_name: "xterm_steelblue", code: Color::Fixed(67).prefix().to_string()}, AnsiCode { short_name: Some("steelblue3"), long_name: "xterm_steelblue3", code: Color::Fixed(68).prefix().to_string()}, AnsiCode { short_name: Some("cornflowerblue"), long_name: "xterm_cornflowerblue", code: Color::Fixed(69).prefix().to_string()}, AnsiCode { short_name: Some("chartreuse3a"), long_name: "xterm_chartreuse3a", code: Color::Fixed(70).prefix().to_string()}, AnsiCode { short_name: Some("darkseagreen4b"), long_name: "xterm_darkseagreen4b", code: Color::Fixed(71).prefix().to_string()}, AnsiCode { short_name: Some("cadetbluea"), long_name: "xterm_cadetbluea", code: Color::Fixed(72).prefix().to_string()}, AnsiCode { short_name: Some("cadetblueb"), long_name: "xterm_cadetblueb", code: Color::Fixed(73).prefix().to_string()}, AnsiCode { short_name: Some("skyblue3"), long_name: "xterm_skyblue3", code: Color::Fixed(74).prefix().to_string()}, AnsiCode { short_name: Some("steelblue1a"), long_name: "xterm_steelblue1a", code: Color::Fixed(75).prefix().to_string()}, AnsiCode { short_name: Some("chartreuse3b"), long_name: "xterm_chartreuse3b", code: Color::Fixed(76).prefix().to_string()}, AnsiCode { short_name: Some("palegreen3a"), long_name: "xterm_palegreen3a", code: Color::Fixed(77).prefix().to_string()}, AnsiCode { short_name: Some("seagreen3"), long_name: "xterm_seagreen3", code: Color::Fixed(78).prefix().to_string()}, AnsiCode { short_name: Some("aquamarine3"), long_name: "xterm_aquamarine3", code: Color::Fixed(79).prefix().to_string()}, AnsiCode { short_name: Some("mediumturquoise"), long_name: "xterm_mediumturquoise", code: Color::Fixed(80).prefix().to_string()}, AnsiCode { short_name: Some("steelblue1b"), long_name: "xterm_steelblue1b", code: Color::Fixed(81).prefix().to_string()}, AnsiCode { short_name: Some("chartreuse2a"), long_name: "xterm_chartreuse2a", code: Color::Fixed(82).prefix().to_string()}, AnsiCode { short_name: Some("seagreen2"), long_name: "xterm_seagreen2", code: Color::Fixed(83).prefix().to_string()}, AnsiCode { short_name: Some("seagreen1a"), long_name: "xterm_seagreen1a", code: Color::Fixed(84).prefix().to_string()}, AnsiCode { short_name: Some("seagreen1b"), long_name: "xterm_seagreen1b", code: Color::Fixed(85).prefix().to_string()}, AnsiCode { short_name: Some("aquamarine1a"), long_name: "xterm_aquamarine1a", code: Color::Fixed(86).prefix().to_string()}, AnsiCode { short_name: Some("darkslategray2"), long_name: "xterm_darkslategray2", code: Color::Fixed(87).prefix().to_string()}, AnsiCode { short_name: Some("darkredb"), long_name: "xterm_darkredb", code: Color::Fixed(88).prefix().to_string()}, AnsiCode { short_name: Some("deeppink4b"), long_name: "xterm_deeppink4b", code: Color::Fixed(89).prefix().to_string()}, AnsiCode { short_name: Some("darkmagentaa"), long_name: "xterm_darkmagentaa", code: Color::Fixed(90).prefix().to_string()}, AnsiCode { short_name: Some("darkmagentab"), long_name: "xterm_darkmagentab", code: Color::Fixed(91).prefix().to_string()}, AnsiCode { short_name: Some("darkvioleta"), long_name: "xterm_darkvioleta", code: Color::Fixed(92).prefix().to_string()}, AnsiCode { short_name: Some("xpurpleb"), long_name: "xterm_purpleb", code: Color::Fixed(93).prefix().to_string()}, AnsiCode { short_name: Some("orange4b"), long_name: "xterm_orange4b", code: Color::Fixed(94).prefix().to_string()}, AnsiCode { short_name: Some("lightpink4"), long_name: "xterm_lightpink4", code: Color::Fixed(95).prefix().to_string()}, AnsiCode { short_name: Some("plum4"), long_name: "xterm_plum4", code: Color::Fixed(96).prefix().to_string()}, AnsiCode { short_name: Some("mediumpurple3a"), long_name: "xterm_mediumpurple3a", code: Color::Fixed(97).prefix().to_string()}, AnsiCode { short_name: Some("mediumpurple3b"), long_name: "xterm_mediumpurple3b", code: Color::Fixed(98).prefix().to_string()}, AnsiCode { short_name: Some("slateblue1"), long_name: "xterm_slateblue1", code: Color::Fixed(99).prefix().to_string()}, AnsiCode { short_name: Some("yellow4a"), long_name: "xterm_yellow4a", code: Color::Fixed(100).prefix().to_string()}, AnsiCode { short_name: Some("wheat4"), long_name: "xterm_wheat4", code: Color::Fixed(101).prefix().to_string()}, AnsiCode { short_name: Some("grey53"), long_name: "xterm_grey53", code: Color::Fixed(102).prefix().to_string()}, AnsiCode { short_name: Some("lightslategrey"), long_name: "xterm_lightslategrey", code: Color::Fixed(103).prefix().to_string()}, AnsiCode { short_name: Some("mediumpurple"), long_name: "xterm_mediumpurple", code: Color::Fixed(104).prefix().to_string()}, AnsiCode { short_name: Some("lightslateblue"), long_name: "xterm_lightslateblue", code: Color::Fixed(105).prefix().to_string()}, AnsiCode { short_name: Some("yellow4b"), long_name: "xterm_yellow4b", code: Color::Fixed(106).prefix().to_string()}, AnsiCode { short_name: Some("darkolivegreen3a"), long_name: "xterm_darkolivegreen3a", code: Color::Fixed(107).prefix().to_string()}, AnsiCode { short_name: Some("darkseagreen"), long_name: "xterm_darkseagreen", code: Color::Fixed(108).prefix().to_string()}, AnsiCode { short_name: Some("lightskyblue3a"), long_name: "xterm_lightskyblue3a", code: Color::Fixed(109).prefix().to_string()}, AnsiCode { short_name: Some("lightskyblue3b"), long_name: "xterm_lightskyblue3b", code: Color::Fixed(110).prefix().to_string()}, AnsiCode { short_name: Some("skyblue2"), long_name: "xterm_skyblue2", code: Color::Fixed(111).prefix().to_string()}, AnsiCode { short_name: Some("chartreuse2b"), long_name: "xterm_chartreuse2b", code: Color::Fixed(112).prefix().to_string()}, AnsiCode { short_name: Some("darkolivegreen3b"), long_name: "xterm_darkolivegreen3b", code: Color::Fixed(113).prefix().to_string()}, AnsiCode { short_name: Some("palegreen3b"), long_name: "xterm_palegreen3b", code: Color::Fixed(114).prefix().to_string()}, AnsiCode { short_name: Some("darkseagreen3a"), long_name: "xterm_darkseagreen3a", code: Color::Fixed(115).prefix().to_string()}, AnsiCode { short_name: Some("darkslategray3"), long_name: "xterm_darkslategray3", code: Color::Fixed(116).prefix().to_string()}, AnsiCode { short_name: Some("skyblue1"), long_name: "xterm_skyblue1", code: Color::Fixed(117).prefix().to_string()}, AnsiCode { short_name: Some("chartreuse1"), long_name: "xterm_chartreuse1", code: Color::Fixed(118).prefix().to_string()}, AnsiCode { short_name: Some("lightgreena"), long_name: "xterm_lightgreena", code: Color::Fixed(119).prefix().to_string()}, AnsiCode { short_name: Some("lightgreenb"), long_name: "xterm_lightgreenb", code: Color::Fixed(120).prefix().to_string()}, AnsiCode { short_name: Some("palegreen1a"), long_name: "xterm_palegreen1a", code: Color::Fixed(121).prefix().to_string()}, AnsiCode { short_name: Some("aquamarine1b"), long_name: "xterm_aquamarine1b", code: Color::Fixed(122).prefix().to_string()}, AnsiCode { short_name: Some("darkslategray1"), long_name: "xterm_darkslategray1", code: Color::Fixed(123).prefix().to_string()}, AnsiCode { short_name: Some("red3a"), long_name: "xterm_red3a", code: Color::Fixed(124).prefix().to_string()}, AnsiCode { short_name: Some("deeppink4c"), long_name: "xterm_deeppink4c", code: Color::Fixed(125).prefix().to_string()}, AnsiCode { short_name: Some("mediumvioletred"), long_name: "xterm_mediumvioletred", code: Color::Fixed(126).prefix().to_string()}, AnsiCode { short_name: Some("magenta3"), long_name: "xterm_magenta3", code: Color::Fixed(127).prefix().to_string()}, AnsiCode { short_name: Some("darkvioletb"), long_name: "xterm_darkvioletb", code: Color::Fixed(128).prefix().to_string()}, AnsiCode { short_name: Some("xpurplec"), long_name: "xterm_purplec", code: Color::Fixed(129).prefix().to_string()},
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/ansi/link.rs
crates/nu-command/src/strings/ansi/link.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct AnsiLink; impl Command for AnsiLink { fn name(&self) -> &str { "ansi link" } fn signature(&self) -> Signature { Signature::build("ansi link") .input_output_types(vec![ (Type::String, Type::String), ( Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .named( "text", SyntaxShape::String, "Link text. Uses uri as text if absent. In case of tables, records and lists applies this text to all elements", Some('t'), ) .rest( "cell path", SyntaxShape::CellPath, "For a data structure input, add links to all strings at the given cell paths.", ) .allow_variants_without_examples(true) .category(Category::Platform) } fn description(&self) -> &str { "Add a link (using OSC 8 escape sequence) to the given string." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a link to open some file", example: "'file:///file.txt' | ansi link --text 'Open Me!'", result: Some(Value::string( "\u{1b}]8;;file:///file.txt\u{1b}\\Open Me!\u{1b}]8;;\u{1b}\\", Span::unknown(), )), }, Example { description: "Create a link without text", example: "'https://www.nushell.sh/' | ansi link", result: Some(Value::string( "\u{1b}]8;;https://www.nushell.sh/\u{1b}\\https://www.nushell.sh/\u{1b}]8;;\u{1b}\\", Span::unknown(), )), }, Example { description: "Format a table column into links", example: "[[url text]; [https://example.com Text]] | ansi link url", result: None, }, ] } } fn operate( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let text: Option<Spanned<String>> = call.get_flag(engine_state, stack, "text")?; let text = text.map(|e| e.item); let column_paths: Vec<CellPath> = call.rest(engine_state, stack, 0)?; let command_span = call.head; if column_paths.is_empty() { input.map( move |v| process_value(&v, text.as_deref()), engine_state.signals(), ) } else { input.map( move |v| process_each_path(v, &column_paths, text.as_deref(), command_span), engine_state.signals(), ) } } fn process_each_path( mut value: Value, column_paths: &[CellPath], text: Option<&str>, command_span: Span, ) -> Value { for path in column_paths { let ret = value.update_cell_path(&path.members, Box::new(|v| process_value(v, text))); if let Err(error) = ret { return Value::error(error, command_span); } } value } fn process_value(value: &Value, text: Option<&str>) -> Value { let span = value.span(); match value { Value::String { val, .. } => { let text = text.unwrap_or(val.as_str()); let result = add_osc_link(text, val.as_str()); Value::string(result, span) } other => { let got = format!("value is {}, not string", other.get_type()); Value::error( ShellError::TypeMismatch { err_message: got, span: other.span(), }, other.span(), ) } } } fn add_osc_link(text: &str, link: &str) -> String { format!("\u{1b}]8;;{link}\u{1b}\\{text}\u{1b}]8;;\u{1b}\\") } #[cfg(test)] mod tests { use super::AnsiLink; #[test] fn examples_work_as_expected() { use crate::test_examples; test_examples(AnsiLink {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/ansi/strip.rs
crates/nu-command/src/strings/ansi/strip.rs
use std::sync::Arc; use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::Config; struct Arguments { cell_paths: Option<Vec<CellPath>>, config: Arc<Config>, } impl CmdArgument for Arguments { fn take_cell_paths(&mut self) -> Option<Vec<CellPath>> { self.cell_paths.take() } } #[derive(Clone)] pub struct AnsiStrip; impl Command for AnsiStrip { fn name(&self) -> &str { "ansi strip" } fn signature(&self) -> Signature { Signature::build("ansi strip") .input_output_types(vec![ (Type::String, Type::String), (Type::List(Box::new(Type::String)), Type::List(Box::new(Type::String))), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .rest( "cell path", SyntaxShape::CellPath, "For a data structure input, remove ANSI sequences from strings at the given cell paths.", ) .allow_variants_without_examples(true) .category(Category::Platform) } fn description(&self) -> &str { "Strip ANSI escape sequences from a string." } 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 cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let config = stack.get_config(engine_state); let args = Arguments { cell_paths, config }; operate(action, args, input, call.head, engine_state.signals()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Strip ANSI escape sequences from a string", example: r#"$'(ansi green)(ansi cursor_on)hello' | ansi strip"#, result: Some(Value::test_string("hello")), }, Example { description: "Strip ANSI escape sequences from a record field", example: r#"{ greeting: $'hello (ansi red)world' exclamation: false } | ansi strip greeting"#, result: Some(Value::test_record(record! { "greeting" => Value::test_string("hello world"), "exclamation" => Value::test_bool(false) })), }, Example { description: "Strip ANSI escape sequences from multiple table columns", example: r#"[[language feature]; [$'(ansi red)rust' $'(ansi i)safety']] | ansi strip language feature"#, result: Some(Value::test_list(vec![Value::test_record(record! { "language" => Value::test_string("rust"), "feature" => Value::test_string("safety") })])), }, ] } } fn action(input: &Value, args: &Arguments, _span: Span) -> Value { let span = input.span(); match input { Value::String { val, .. } => { Value::string(nu_utils::strip_ansi_likely(val).to_string(), span) } other => { // Fake stripping ansi for other types and just show the abbreviated string // instead of showing an error message Value::string(other.to_abbreviated_string(&args.config), span) } } } #[cfg(test)] mod tests { use super::{AnsiStrip, Arguments, action}; use nu_protocol::{Span, Value, engine::EngineState}; #[test] fn examples_work_as_expected() { use crate::test_examples; test_examples(AnsiStrip {}) } #[test] fn test_stripping() { let input_string = Value::test_string("\u{1b}[3;93;41mHello\u{1b}[0m \u{1b}[1;32mNu \u{1b}[1;35mWorld"); let expected = Value::test_string("Hello Nu World"); let args = Arguments { cell_paths: vec![].into(), config: EngineState::new().get_config().clone(), }; let actual = action(&input_string, &args, Span::test_data()); assert_eq!(actual, expected); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/ansi/mod.rs
crates/nu-command/src/strings/ansi/mod.rs
mod ansi_; mod link; mod strip; pub use ansi_::Ansi; pub use link::AnsiLink; pub use strip::AnsiStrip;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/format/format_.rs
crates/nu-command/src/strings/format/format_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Format; impl Command for Format { fn name(&self) -> &str { "format" } fn signature(&self) -> Signature { Signature::build("format") .category(Category::Strings) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for formatting 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/strings/format/filesize.rs
crates/nu-command/src/strings/format/filesize.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::{ FilesizeFormatter, FilesizeUnit, SUPPORTED_FILESIZE_UNITS, engine::StateWorkingSet, }; struct Arguments { unit: FilesizeUnit, 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 FormatFilesize; impl Command for FormatFilesize { fn name(&self) -> &str { "format filesize" } fn signature(&self) -> Signature { Signature::build("format filesize") .input_output_types(vec![ (Type::Filesize, Type::String), (Type::table(), Type::table()), (Type::record(), Type::record()), ]) .allow_variants_without_examples(true) .required( "format value", SyntaxShape::String, "The format into which convert the file sizes.", ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, format filesizes at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Converts a column of filesizes to some specified format." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "display", "pattern", "human readable"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let unit = parse_filesize_unit(call.req::<Spanned<String>>(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 { unit, cell_paths }; operate( format_value_impl, arg, input, call.head, engine_state.signals(), ) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let unit = parse_filesize_unit(call.req_const::<Spanned<String>>(working_set, 0)?)?; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let arg = Arguments { unit, cell_paths }; operate( format_value_impl, arg, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert the size column to KB", example: "ls | format filesize kB size", result: None, }, Example { description: "Convert the apparent column to B", example: "du | format filesize B apparent", result: None, }, Example { description: "Convert the size data to MB", example: "4GB | format filesize MB", result: Some(Value::test_string("4000 MB")), }, ] } } fn parse_filesize_unit(format: Spanned<String>) -> Result<FilesizeUnit, ShellError> { format.item.parse().map_err(|_| ShellError::InvalidUnit { supported_units: SUPPORTED_FILESIZE_UNITS.join(", "), span: format.span, }) } fn format_value_impl(val: &Value, arg: &Arguments, span: Span) -> Value { let value_span = val.span(); match val { Value::Filesize { val, .. } => FilesizeFormatter::new() .unit(arg.unit) .format(*val) .to_string() .into_value(span), Value::Error { .. } => val.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "filesize".into(), wrong_type: val.get_type().to_string(), dst_span: span, src_span: value_span, }, span, ), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FormatFilesize) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/format/date.rs
crates/nu-command/src/strings/format/date.rs
use crate::{generate_strftime_list, parse_date_from_string}; use chrono::{DateTime, Datelike, Locale, TimeZone}; use nu_engine::command_prelude::*; use nu_utils::locale::{LOCALE_OVERRIDE_ENV_VAR, get_system_locale_string}; use std::fmt::{Display, Write}; #[derive(Clone)] pub struct FormatDate; impl Command for FormatDate { fn name(&self) -> &str { "format date" } fn signature(&self) -> Signature { Signature::build("format date") .input_output_types(vec![ (Type::Date, Type::String), (Type::String, Type::String), (Type::Nothing, Type::table()), // FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors // which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details // only applicable for --list flag (Type::Any, Type::table()), ]) .allow_variants_without_examples(true) // https://github.com/nushell/nushell/issues/7032 .switch("list", "lists strftime cheatsheet", Some('l')) .optional( "format string", SyntaxShape::String, "The desired format date.", ) .category(Category::Strings) } fn description(&self) -> &str { "Format a given date using a format string." } fn search_terms(&self) -> Vec<&str> { vec!["fmt", "strftime"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Format a given date-time using the default format (RFC 2822).", example: r#"'2021-10-22 20:00:12 +01:00' | into datetime | format date"#, result: Some(Value::string( "Fri, 22 Oct 2021 20:00:12 +0100".to_string(), Span::test_data(), )), }, Example { description: "Format a given date-time as a string using the default format (RFC 2822).", example: r#""2021-10-22 20:00:12 +01:00" | format date"#, result: Some(Value::string( "Fri, 22 Oct 2021 20:00:12 +0100".to_string(), Span::test_data(), )), }, Example { description: "Format a given date-time according to the RFC 3339 standard.", example: r#"'2021-10-22 20:00:12 +01:00' | into datetime | format date "%+""#, result: Some(Value::string( "2021-10-22T20:00:12+01:00".to_string(), Span::test_data(), )), }, Example { description: "Format the current date-time using a given format string.", example: r#"date now | format date "%Y-%m-%d %H:%M:%S""#, result: None, }, Example { description: "Format the current date using a given format string.", example: r#"date now | format date "%Y-%m-%d %H:%M:%S""#, result: None, }, Example { description: "Format a given date using a given format string.", example: r#""2021-10-22 20:00:12 +01:00" | format date "%Y-%m-%d""#, result: Some(Value::test_string("2021-10-22")), }, ] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let list = call.has_flag(engine_state, stack, "list")?; let format = call.opt::<Spanned<String>>(engine_state, stack, 0)?; // env var preference is documented at https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html // LC_ALL overrides LC_TIME, LC_TIME overrides LANG // get the locale first so we can use the proper get_env_var functions since this is a const command // we can override the locale by setting $env.NU_TEST_LOCALE_OVERRIDE or $env.LC_TIME let locale = if let Some(loc) = engine_state .get_env_var(LOCALE_OVERRIDE_ENV_VAR) .or_else(|| engine_state.get_env_var("LC_ALL")) .or_else(|| engine_state.get_env_var("LC_TIME")) .or_else(|| engine_state.get_env_var("LANG")) { let locale_str = loc.as_str()?.split('.').next().unwrap_or("en_US"); locale_str.try_into().unwrap_or(Locale::en_US) } else { get_system_locale_string() .map(|l| l.replace('-', "_")) .unwrap_or_else(|| String::from("en_US")) .as_str() .try_into() .unwrap_or(Locale::en_US) }; run(engine_state, call, input, list, format, locale) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let list = call.has_flag_const(working_set, "list")?; let format = call.opt_const::<Spanned<String>>(working_set, 0)?; // env var preference is documented at https://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html // LC_ALL overrides LC_TIME, LC_TIME overrides LANG // get the locale first so we can use the proper get_env_var functions since this is a const command // we can override the locale by setting $env.NU_TEST_LOCALE_OVERRIDE or $env.LC_TIME let locale = if let Some(loc) = working_set .get_env_var(LOCALE_OVERRIDE_ENV_VAR) .or_else(|| working_set.get_env_var("LC_ALL")) .or_else(|| working_set.get_env_var("LC_TIME")) .or_else(|| working_set.get_env_var("LANG")) { let locale_str = loc.as_str()?.split('.').next().unwrap_or("en_US"); locale_str.try_into().unwrap_or(Locale::en_US) } else { get_system_locale_string() .map(|l| l.replace('-', "_")) .unwrap_or_else(|| String::from("en_US")) .as_str() .try_into() .unwrap_or(Locale::en_US) }; run(working_set.permanent(), call, input, list, format, locale) } } fn run( engine_state: &EngineState, call: &Call, input: PipelineData, list: bool, format: Option<Spanned<String>>, locale: Locale, ) -> Result<PipelineData, ShellError> { let head = call.head; if list { return Ok(PipelineData::value( generate_strftime_list(head, false), None, )); } // This doesn't match explicit nulls if let PipelineData::Empty = input { return Err(ShellError::PipelineEmpty { dst_span: head }); } input.map( move |value| match &format { Some(format) => format_helper(value, format.item.as_str(), format.span, head, locale), None => format_helper_rfc2822(value, head), }, engine_state.signals(), ) } fn format_from<Tz: TimeZone>( date_time: DateTime<Tz>, formatter: &str, span: Span, locale: Locale, ) -> Value where Tz::Offset: Display, { let mut formatter_buf = String::new(); // Handle custom format specifiers for compact formats let processed_formatter = formatter .replace("%J", "%Y%m%d") // %J for joined date (YYYYMMDD) .replace("%Q", "%H%M%S"); // %Q for sequential time (HHMMSS) let format = date_time.format_localized(&processed_formatter, locale); match formatter_buf.write_fmt(format_args!("{format}")) { Ok(_) => Value::string(formatter_buf, span), Err(_) => Value::error( ShellError::TypeMismatch { err_message: "invalid format".to_string(), span, }, span, ), } } fn format_helper( value: Value, formatter: &str, formatter_span: Span, head_span: Span, locale: Locale, ) -> Value { match value { Value::Date { val, .. } => format_from(val, formatter, formatter_span, locale), Value::String { val, .. } => { let dt = parse_date_from_string(&val, formatter_span); match dt { Ok(x) => format_from(x, formatter, formatter_span, locale), Err(e) => e, } } _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "date, string (that represents datetime)".into(), wrong_type: value.get_type().to_string(), dst_span: head_span, src_span: value.span(), }, head_span, ), } } fn format_helper_rfc2822(value: Value, span: Span) -> Value { let val_span = value.span(); match value { Value::Date { val, .. } => Value::string( { if val.year() >= 0 { val.to_rfc2822() } else { val.to_rfc3339() } }, span, ), Value::String { val, .. } => { let dt = parse_date_from_string(&val, val_span); match dt { Ok(x) => Value::string( { if x.year() >= 0 { x.to_rfc2822() } else { x.to_rfc3339() } }, span, ), Err(e) => e, } } _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "date, string (that represents datetime)".into(), wrong_type: value.get_type().to_string(), dst_span: span, src_span: val_span, }, span, ), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FormatDate {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/format/mod.rs
crates/nu-command/src/strings/format/mod.rs
mod date; mod duration; mod filesize; mod format_; pub use date::FormatDate; pub use duration::FormatDuration; pub use filesize::FormatFilesize; pub use format_::Format;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/strings/format/duration.rs
crates/nu-command/src/strings/format/duration.rs
use nu_cmd_base::input_handler::{CmdArgument, operate}; use nu_engine::command_prelude::*; use nu_protocol::SUPPORTED_DURATION_UNITS; struct Arguments { format_value: Spanned<String>, float_precision: usize, 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 FormatDuration; impl Command for FormatDuration { fn name(&self) -> &str { "format duration" } fn signature(&self) -> Signature { Signature::build("format duration") .input_output_types(vec![ (Type::Duration, Type::String), ( Type::List(Box::new(Type::Duration)), Type::List(Box::new(Type::String)), ), (Type::table(), Type::table()), ]) .allow_variants_without_examples(true) .required( "format value", SyntaxShape::String, "The unit in which to display the duration.", ) .rest( "rest", SyntaxShape::CellPath, "For a data structure input, format duration at the given cell paths.", ) .category(Category::Strings) } fn description(&self) -> &str { "Outputs duration with a specified unit of time." } fn search_terms(&self) -> Vec<&str> { vec!["convert", "display", "pattern", "human readable"] } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let format_value = call.req::<Value>(engine_state, stack, 0)?; let format_value_span = format_value.span(); let format_value = Spanned { item: format_value.coerce_into_string()?.to_ascii_lowercase(), span: format_value_span, }; let cell_paths: Vec<CellPath> = call.rest(engine_state, stack, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let float_precision = engine_state.config.float_precision as usize; let arg = Arguments { format_value, float_precision, cell_paths, }; operate( format_value_impl, arg, input, call.head, engine_state.signals(), ) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let format_value = call.req_const::<Value>(working_set, 0)?; let format_value_span = format_value.span(); let format_value = Spanned { item: format_value.coerce_into_string()?.to_ascii_lowercase(), span: format_value_span, }; let cell_paths: Vec<CellPath> = call.rest_const(working_set, 1)?; let cell_paths = (!cell_paths.is_empty()).then_some(cell_paths); let float_precision = working_set.permanent().config.float_precision as usize; let arg = Arguments { format_value, float_precision, cell_paths, }; operate( format_value_impl, arg, input, call.head, working_set.permanent().signals(), ) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert µs duration to the requested second duration as a string", example: "1000000µs | format duration sec", result: Some(Value::test_string("1 sec")), }, Example { description: "Convert durations to µs duration as strings", example: "[1sec 2sec] | format duration µs", result: Some(Value::test_list(vec![ Value::test_string("1000000 µs"), Value::test_string("2000000 µs"), ])), }, Example { description: "Convert duration to µs as a string if unit asked for was us", example: "1sec | format duration us", result: Some(Value::test_string("1000000 µs")), }, ] } } fn format_value_impl(val: &Value, arg: &Arguments, span: Span) -> Value { let inner_span = val.span(); match val { Value::Duration { val: inner, .. } => { let duration = *inner; let float_precision = arg.float_precision; match convert_inner_to_unit(duration, &arg.format_value.item, arg.format_value.span) { Ok(d) => { let unit = if &arg.format_value.item == "us" { "µs" } else { &arg.format_value.item }; if d.fract() == 0.0 { Value::string(format!("{d} {unit}"), inner_span) } else { Value::string(format!("{d:.float_precision$} {unit}"), inner_span) } } Err(e) => Value::error(e, inner_span), } } Value::Error { .. } => val.clone(), _ => Value::error( ShellError::OnlySupportsThisInputType { exp_input_type: "filesize".into(), wrong_type: val.get_type().to_string(), dst_span: span, src_span: val.span(), }, span, ), } } fn convert_inner_to_unit(val: i64, to_unit: &str, span: Span) -> Result<f64, ShellError> { match to_unit { "ns" => Ok(val as f64), "us" => Ok(val as f64 / 1000.0), "µs" => Ok(val as f64 / 1000.0), // Micro sign "μs" => Ok(val as f64 / 1000.0), // Greek small letter "ms" => Ok(val as f64 / 1000.0 / 1000.0), "sec" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0), "min" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0), "hr" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0), "day" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0), "wk" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 7.0), "month" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 30.0), "yr" => Ok(val as f64 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 365.0), "dec" => Ok(val as f64 / 10.0 / 1000.0 / 1000.0 / 1000.0 / 60.0 / 60.0 / 24.0 / 365.0), _ => Err(ShellError::InvalidUnit { span, supported_units: SUPPORTED_DURATION_UNITS.join(", "), }), } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FormatDuration) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/generators/seq_char.rs
crates/nu-command/src/generators/seq_char.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct SeqChar; impl Command for SeqChar { fn name(&self) -> &str { "seq char" } fn description(&self) -> &str { "Print a sequence of ASCII characters." } fn signature(&self) -> Signature { Signature::build("seq char") .input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::String)))]) .required( "start", SyntaxShape::String, "Start of character sequence (inclusive).", ) .required( "end", SyntaxShape::String, "End of character sequence (inclusive).", ) .category(Category::Generators) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "sequence a to e", example: "seq char a e", result: Some(Value::list( vec![ Value::test_string('a'), Value::test_string('b'), Value::test_string('c'), Value::test_string('d'), Value::test_string('e'), ], Span::test_data(), )), }, Example { description: "Sequence a to e, and join the characters with a pipe", example: "seq char a e | str join '|'", // TODO: it would be nice to test this example, but it currently breaks the input/output type tests // result: Some(Value::test_string("a|b|c|d|e")), result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { seq_char(engine_state, stack, call) } } fn is_single_character(ch: &str) -> bool { ch.is_ascii() && (ch.len() == 1) } fn seq_char( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<PipelineData, ShellError> { let start: Spanned<String> = call.req(engine_state, stack, 0)?; let end: Spanned<String> = call.req(engine_state, stack, 1)?; if !is_single_character(&start.item) { return Err(ShellError::GenericError { error: "seq char only accepts individual ASCII characters as parameters".into(), msg: "input should be a single ASCII character".into(), span: Some(start.span), help: None, inner: vec![], }); } if !is_single_character(&end.item) { return Err(ShellError::GenericError { error: "seq char only accepts individual ASCII characters as parameters".into(), msg: "input should be a single ASCII character".into(), span: Some(end.span), help: None, inner: vec![], }); } let start = start .item .chars() .next() // expect is ok here, because we just checked the length .expect("seq char input must contains 2 inputs"); let end = end .item .chars() .next() // expect is ok here, because we just checked the length .expect("seq char input must contains 2 inputs"); let span = call.head; run_seq_char(start, end, span) } fn run_seq_char(start_ch: char, end_ch: char, span: Span) -> Result<PipelineData, ShellError> { let start = start_ch as u8; let end = end_ch as u8; let range = if start <= end { start..=end } else { end..=start }; let result_vec = if start <= end { range.map(|c| (c as char).to_string()).collect::<Vec<_>>() } else { range .rev() .map(|c| (c as char).to_string()) .collect::<Vec<_>>() }; let result = result_vec .into_iter() .map(|x| Value::string(x, span)) .collect::<Vec<Value>>(); Ok(Value::list(result, span).into_pipeline_data()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SeqChar {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/generators/cal.rs
crates/nu-command/src/generators/cal.rs
use chrono::{Datelike, Local, NaiveDate}; use nu_color_config::StyleComputer; use nu_engine::command_prelude::*; use nu_protocol::ast::{self, Expr, Expression}; use std::collections::VecDeque; static DAYS_OF_THE_WEEK: [&str; 7] = ["su", "mo", "tu", "we", "th", "fr", "sa"]; #[derive(Clone)] pub struct Cal; struct Arguments { year: bool, quarter: bool, month: bool, month_names: bool, full_year: Option<Spanned<i64>>, week_start: Option<Spanned<String>>, as_table: bool, } impl Command for Cal { fn name(&self) -> &str { "cal" } fn signature(&self) -> Signature { Signature::build("cal") .switch("year", "Display the year column", Some('y')) .switch("quarter", "Display the quarter column", Some('q')) .switch("month", "Display the month column", Some('m')) .switch("as-table", "output as a table", Some('t')) .named( "full-year", SyntaxShape::Int, "Display a year-long calendar for the specified year", None, ) .param( Flag::new("week-start") .arg(SyntaxShape::String) .desc( "Display the calendar with the specified day as the first day of the week", ) .completion(Completion::new_list(DAYS_OF_THE_WEEK.as_slice())), ) .switch( "month-names", "Display the month names instead of integers", None, ) .input_output_types(vec![ (Type::Nothing, Type::String), (Type::Nothing, Type::table()), ]) .allow_variants_without_examples(true) // TODO: supply exhaustive examples .category(Category::Generators) } fn description(&self) -> &str { "Display a calendar." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { cal(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "This month's calendar", example: "cal", result: None, }, Example { description: "The calendar for all of 2012", example: "cal --full-year 2012", result: None, }, Example { description: "This month's calendar with the week starting on Monday", example: "cal --week-start mo", result: None, }, Example { description: "How many 'Friday the Thirteenths' occurred in 2015?", example: "cal --as-table --full-year 2015 | where fr == 13 | length", result: None, }, ] } } pub fn cal( engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let mut calendar_vec_deque = VecDeque::new(); let tag = call.head; let (current_year, current_month, current_day) = get_current_date(); let arguments = Arguments { year: call.has_flag(engine_state, stack, "year")?, month: call.has_flag(engine_state, stack, "month")?, month_names: call.has_flag(engine_state, stack, "month-names")?, quarter: call.has_flag(engine_state, stack, "quarter")?, full_year: call.get_flag(engine_state, stack, "full-year")?, week_start: call.get_flag(engine_state, stack, "week-start")?, as_table: call.has_flag(engine_state, stack, "as-table")?, }; let style_computer = &StyleComputer::from_config(engine_state, stack); let mut selected_year: i32 = current_year; let mut current_day_option: Option<u32> = Some(current_day); let full_year_value = &arguments.full_year; let month_range = if let Some(full_year_value) = full_year_value { selected_year = full_year_value.item as i32; if selected_year != current_year { current_day_option = None } (1, 12) } else { (current_month, current_month) }; add_months_of_year_to_table( &arguments, &mut calendar_vec_deque, tag, selected_year, month_range, current_month, current_day_option, style_computer, )?; let mut table_no_index = ast::Call::new(Span::unknown()); table_no_index.add_named(( Spanned { item: "index".to_string(), span: Span::unknown(), }, None, Some(Expression::new_unknown( Expr::Bool(false), Span::unknown(), Type::Bool, )), )); let cal_table_output = Value::list(calendar_vec_deque.into_iter().collect(), tag).into_pipeline_data(); if !arguments.as_table { crate::Table.run( engine_state, stack, &(&table_no_index).into(), cal_table_output, ) } else { Ok(cal_table_output) } } fn get_invalid_year_shell_error(head: Span) -> ShellError { ShellError::TypeMismatch { err_message: "The year is invalid".to_string(), span: head, } } struct MonthHelper { selected_year: i32, selected_month: u32, day_number_of_week_month_starts_on: u32, number_of_days_in_month: u32, quarter_number: u32, month_name: String, } impl MonthHelper { pub fn new(selected_year: i32, selected_month: u32) -> Result<MonthHelper, ()> { let naive_date = NaiveDate::from_ymd_opt(selected_year, selected_month, 1).ok_or(())?; let number_of_days_in_month = MonthHelper::calculate_number_of_days_in_month(selected_year, selected_month)?; Ok(MonthHelper { selected_year, selected_month, day_number_of_week_month_starts_on: naive_date.weekday().num_days_from_sunday(), number_of_days_in_month, quarter_number: ((selected_month - 1) / 3) + 1, month_name: naive_date.format("%B").to_string().to_ascii_lowercase(), }) } fn calculate_number_of_days_in_month( mut selected_year: i32, mut selected_month: u32, ) -> Result<u32, ()> { // Chrono does not provide a method to output the amount of days in a month // This is a workaround taken from the example code from the Chrono docs here: // https://docs.rs/chrono/0.3.0/chrono/naive/date/struct.NaiveDate.html#example-30 if selected_month == 12 { selected_year += 1; selected_month = 1; } else { selected_month += 1; }; let next_month_naive_date = NaiveDate::from_ymd_opt(selected_year, selected_month, 1).ok_or(())?; Ok(next_month_naive_date.pred_opt().unwrap_or_default().day()) } } fn get_current_date() -> (i32, u32, u32) { let local_now_date = Local::now().date_naive(); let current_year: i32 = local_now_date.year(); let current_month: u32 = local_now_date.month(); let current_day: u32 = local_now_date.day(); (current_year, current_month, current_day) } #[allow(clippy::too_many_arguments)] fn add_months_of_year_to_table( arguments: &Arguments, calendar_vec_deque: &mut VecDeque<Value>, tag: Span, selected_year: i32, (start_month, end_month): (u32, u32), current_month: u32, current_day_option: Option<u32>, style_computer: &StyleComputer, ) -> Result<(), ShellError> { for month_number in start_month..=end_month { let mut new_current_day_option: Option<u32> = None; if let Some(current_day) = current_day_option && month_number == current_month { new_current_day_option = Some(current_day) } let add_month_to_table_result = add_month_to_table( arguments, calendar_vec_deque, tag, selected_year, month_number, new_current_day_option, style_computer, ); add_month_to_table_result? } Ok(()) } fn add_month_to_table( arguments: &Arguments, calendar_vec_deque: &mut VecDeque<Value>, tag: Span, selected_year: i32, current_month: u32, current_day_option: Option<u32>, style_computer: &StyleComputer, ) -> Result<(), ShellError> { let month_helper_result = MonthHelper::new(selected_year, current_month); let full_year_value: &Option<Spanned<i64>> = &arguments.full_year; let month_helper = match month_helper_result { Ok(month_helper) => month_helper, Err(()) => match full_year_value { Some(x) => return Err(get_invalid_year_shell_error(x.span)), None => { return Err(ShellError::UnknownOperator { op_token: "Issue parsing command, invalid command".to_string(), span: tag, }); } }, }; let mut days_of_the_week = DAYS_OF_THE_WEEK; let mut total_start_offset: u32 = month_helper.day_number_of_week_month_starts_on; if let Some(week_start_day) = &arguments.week_start { if let Some(position) = days_of_the_week .iter() .position(|day| *day == week_start_day.item) { days_of_the_week.rotate_left(position); total_start_offset += (days_of_the_week.len() - position) as u32; total_start_offset %= days_of_the_week.len() as u32; } else { return Err(ShellError::TypeMismatch { err_message: format!( "The specified week start day is invalid, expected one of {DAYS_OF_THE_WEEK:?}" ), span: week_start_day.span, }); } }; let mut day_number: u32 = 1; let day_limit: u32 = total_start_offset + month_helper.number_of_days_in_month; let should_show_year_column = arguments.year; let should_show_quarter_column = arguments.quarter; let should_show_month_column = arguments.month; let should_show_month_names = arguments.month_names; while day_number <= day_limit { let mut record = Record::new(); if should_show_year_column { record.insert( "year".to_string(), Value::int(month_helper.selected_year as i64, tag), ); } if should_show_quarter_column { record.insert( "quarter".to_string(), Value::int(month_helper.quarter_number as i64, tag), ); } if should_show_month_column || should_show_month_names { let month_value = if should_show_month_names { Value::string(month_helper.month_name.clone(), tag) } else { Value::int(month_helper.selected_month as i64, tag) }; record.insert("month".to_string(), month_value); } for day in &days_of_the_week { let should_add_day_number_to_table = (day_number > total_start_offset) && (day_number <= day_limit); let mut value = Value::nothing(tag); if should_add_day_number_to_table { let adjusted_day_number = day_number - total_start_offset; value = Value::int(adjusted_day_number as i64, tag); if let Some(current_day) = current_day_option && current_day == adjusted_day_number { // This colors the current day let header_style = style_computer.compute("header", &Value::nothing(Span::unknown())); value = Value::string( header_style .paint(adjusted_day_number.to_string()) .to_string(), tag, ); } } record.insert((*day).to_string(), value); day_number += 1; } calendar_vec_deque.push_back(Value::record(record, tag)) } Ok(()) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Cal {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/generators/mod.rs
crates/nu-command/src/generators/mod.rs
mod cal; mod generate; mod seq; mod seq_char; mod seq_date; pub use cal::Cal; pub use generate::Generate; pub use seq::Seq; pub use seq_char::SeqChar; pub use seq_date::SeqDate;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/generators/seq.rs
crates/nu-command/src/generators/seq.rs
use nu_engine::command_prelude::*; use nu_protocol::ListStream; #[derive(Clone)] pub struct Seq; impl Command for Seq { fn name(&self) -> &str { "seq" } fn signature(&self) -> Signature { Signature::build("seq") .input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::Number)))]) .rest("rest", SyntaxShape::Number, "Sequence values.") .category(Category::Generators) } fn description(&self) -> &str { "Output sequences of numbers." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { seq(engine_state, stack, call) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "sequence 1 to 10", example: "seq 1 10", result: Some(Value::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), Value::test_int(7), Value::test_int(8), Value::test_int(9), Value::test_int(10), ], Span::test_data(), )), }, Example { description: "sequence 1.0 to 2.0 by 0.1s", example: "seq 1.0 0.1 2.0", result: Some(Value::list( vec![ Value::test_float(1.0000), Value::test_float(1.1000), Value::test_float(1.2000), Value::test_float(1.3000), Value::test_float(1.4000), Value::test_float(1.5000), Value::test_float(1.6000), Value::test_float(1.7000), Value::test_float(1.8000), Value::test_float(1.9000), Value::test_float(2.0000), ], Span::test_data(), )), }, Example { description: "sequence 1 to 5, then convert to a string with a pipe separator", example: "seq 1 5 | str join '|'", result: None, }, ] } } fn seq( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<PipelineData, ShellError> { let span = call.head; let rest_nums: Vec<Spanned<f64>> = call.rest(engine_state, stack, 0)?; // note that the check for int or float has to occur here. prior, the check would occur after // everything had been generated; this does not work well with ListStreams. // As such, the simple test is to check if this errors out: that means there is a float in the // input, which necessarily means that parts of the output will be floats. let rest_nums_check: Result<Vec<Spanned<i64>>, ShellError> = call.rest(engine_state, stack, 0); let contains_decimals = rest_nums_check.is_err(); if rest_nums.is_empty() { return Err(ShellError::GenericError { error: "seq requires some parameters".into(), msg: "needs parameter".into(), span: Some(call.head), help: None, inner: vec![], }); } let rest_nums: Vec<f64> = rest_nums.iter().map(|n| n.item).collect(); run_seq(rest_nums, span, contains_decimals, engine_state) } pub fn run_seq( free: Vec<f64>, span: Span, contains_decimals: bool, engine_state: &EngineState, ) -> Result<PipelineData, ShellError> { let first = free[0]; let step = if free.len() > 2 { free[1] } else { 1.0 }; let last = { free[free.len() - 1] }; let stream = if !contains_decimals { ListStream::new( IntSeq { count: first as i64, step: step as i64, last: last as i64, span, }, span, engine_state.signals().clone(), ) } else { ListStream::new( FloatSeq { first, step, last, index: 0, span, }, span, engine_state.signals().clone(), ) }; Ok(stream.into()) } struct FloatSeq { first: f64, step: f64, last: f64, index: isize, span: Span, } impl Iterator for FloatSeq { type Item = Value; fn next(&mut self) -> Option<Value> { let count = self.first + self.index as f64 * self.step; // Accuracy guaranteed as far as possible; each time, the value is re-evaluated from the // base arguments if (count > self.last && self.step >= 0.0) || (count < self.last && self.step <= 0.0) { return None; } self.index += 1; Some(Value::float(count, self.span)) } } struct IntSeq { count: i64, step: i64, last: i64, span: Span, } impl Iterator for IntSeq { type Item = Value; fn next(&mut self) -> Option<Value> { if (self.count > self.last && self.step >= 0) || (self.count < self.last && self.step <= 0) { return None; } let ret = Some(Value::int(self.count, self.span)); self.count += self.step; ret } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Seq {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/generators/generate.rs
crates/nu-command/src/generators/generate.rs
use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct Generate; impl Command for Generate { fn name(&self) -> &str { "generate" } fn signature(&self) -> Signature { Signature::build("generate") .input_output_types(vec![ (Type::Nothing, Type::list(Type::Any)), (Type::list(Type::Any), Type::list(Type::Any)), (Type::table(), Type::list(Type::Any)), (Type::Range, Type::list(Type::Any)), ]) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])), "Generator function.", ) .optional("initial", SyntaxShape::Any, "Initial value.") .allow_variants_without_examples(true) .category(Category::Generators) } fn description(&self) -> &str { "Generate a list of values by successively invoking a closure." } fn extra_description(&self) -> &str { r#"The generator closure accepts a single argument and returns a record containing two optional keys: 'out' and 'next'. Each invocation, the 'out' value, if present, is added to the stream. If a 'next' key is present, it is used as the next argument to the closure, otherwise generation stops. Additionally, if an input stream is provided, the generator closure accepts two arguments. On each invocation an element of the input stream is provided as the first argument. The second argument is the `next` value from the last invocation. In this case, generation also stops when the input stream stops."# } fn search_terms(&self) -> Vec<&str> { vec!["unfold", "stream", "yield", "expand", "state", "scan"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "generate {|i| if $i <= 10 { {out: $i, next: ($i + 2)} }} 0", description: "Generate a sequence of numbers", result: Some(Value::list( vec![ Value::test_int(0), Value::test_int(2), Value::test_int(4), Value::test_int(6), Value::test_int(8), Value::test_int(10), ], Span::test_data(), )), }, Example { example: "generate {|fib| {out: $fib.0, next: [$fib.1, ($fib.0 + $fib.1)]} } [0, 1]", description: "Generate a continuous stream of Fibonacci numbers", result: None, }, Example { example: "generate {|fib=[0, 1]| {out: $fib.0, next: [$fib.1, ($fib.0 + $fib.1)]} }", description: "Generate a continuous stream of Fibonacci numbers, using default parameters", result: None, }, Example { example: "1..5 | generate {|e, sum=0| let sum = $e + $sum; {out: $sum, next: $sum} }", description: "Generate a running sum of the inputs", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(3), Value::test_int(6), Value::test_int(10), Value::test_int(15), ])), }, ] } 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 initial: Option<Value> = call.opt(engine_state, stack, 1)?; let block = engine_state.get_block(closure.block_id); let mut closure = ClosureEval::new(engine_state, stack, closure); match input { PipelineData::Empty => { // A type of Option<S> is used to represent state. Invocation // will stop on None. Using Option<S> allows functions to output // one final value before stopping. let mut state = Some(get_initial_state(initial, &block.signature, call.head)?); let iter = std::iter::from_fn(move || { let state_arg = state.take()?; let closure_result = closure .add_arg(state_arg) .run_with_input(PipelineData::empty()); let (output, next_input) = parse_closure_result(closure_result, head); // We use `state` to control when to stop, not `output`. By wrapping // it in a `Some`, we allow the generator to output `None` as a valid output // value. state = next_input; Some(output) }); Ok(iter .flatten() .into_pipeline_data(call.head, engine_state.signals().clone())) } input @ (PipelineData::Value(Value::Range { .. }, ..) | PipelineData::Value(Value::List { .. }, ..) | PipelineData::ListStream(..)) => { let mut state = Some(get_initial_state(initial, &block.signature, call.head)?); let iter = input.into_iter().map_while(move |item| { let state_arg = state.take()?; let closure_result = closure .add_arg(item) .add_arg(state_arg) .run_with_input(PipelineData::empty()); let (output, next_input) = parse_closure_result(closure_result, head); state = next_input; Some(output) }); Ok(iter .flatten() .into_pipeline_data(call.head, engine_state.signals().clone())) } _ => Err(ShellError::PipelineMismatch { exp_input_type: "nothing".to_string(), dst_span: head, src_span: input.span().unwrap_or(head), }), } } } fn get_initial_state( initial: Option<Value>, signature: &Signature, span: Span, ) -> Result<Value, ShellError> { match initial { Some(v) => Ok(v), None => { // the initial state should be referred from signature if !signature.optional_positional.is_empty() && signature.optional_positional[0].default_value.is_some() { Ok(signature.optional_positional[0] .default_value .clone() .expect("Already checked default value")) } else { Err(ShellError::GenericError { error: "The initial value is missing".to_string(), msg: "Missing initial value".to_string(), span: Some(span), help: Some( "Provide an <initial> value as an argument to generate, or assign a default value to the closure parameter" .to_string(), ), inner: vec![], }) } } } } fn parse_closure_result( closure_result: Result<PipelineData, ShellError>, head: Span, ) -> (Option<Value>, Option<Value>) { match closure_result { // no data -> output nothing and stop. Ok(PipelineData::Empty) => (None, None), Ok(PipelineData::Value(value, ..)) => { let span = value.span(); match value { // {out: ..., next: ...} -> output and continue Value::Record { val, .. } => { let iter = val.into_owned().into_iter(); let mut out = None; let mut next = None; let mut err = None; for (k, v) in iter { if k.eq_ignore_ascii_case("out") { out = Some(v); } else if k.eq_ignore_ascii_case("next") { next = Some(v); } else { let error = ShellError::GenericError { error: "Invalid block return".into(), msg: format!("Unexpected record key '{k}'"), span: Some(span), help: None, inner: vec![], }; err = Some(Value::error(error, head)); break; } } if err.is_some() { (err, None) } else { (out, next) } } // some other value -> error and stop _ => { let error = ShellError::GenericError { error: "Invalid block return".into(), msg: format!("Expected record, found {}", value.get_type()), span: Some(span), help: None, inner: vec![], }; (Some(Value::error(error, head)), None) } } } Ok(other) => { let error = other .into_value(head) .map(|val| ShellError::GenericError { error: "Invalid block return".into(), msg: format!("Expected record, found {}", val.get_type()), span: Some(val.span()), help: None, inner: vec![], }) .unwrap_or_else(|err| err); (Some(Value::error(error, head)), None) } // error -> error and stop Err(error) => (Some(Value::error(error, head)), None), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Generate {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/generators/seq_date.rs
crates/nu-command/src/generators/seq_date.rs
use chrono::{Duration, Local, NaiveDate, NaiveDateTime}; use nu_engine::command_prelude::*; use nu_protocol::FromValue; use std::fmt::Write; const NANOSECONDS_IN_DAY: i64 = 1_000_000_000i64 * 60i64 * 60i64 * 24i64; #[derive(Clone)] pub struct SeqDate; impl Command for SeqDate { fn name(&self) -> &str { "seq date" } fn description(&self) -> &str { "Print sequences of dates." } fn signature(&self) -> nu_protocol::Signature { Signature::build("seq date") .input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::String)))]) .named( "output-format", SyntaxShape::String, "prints dates in this format (defaults to %Y-%m-%d)", Some('o'), ) .named( "input-format", SyntaxShape::String, "give argument dates in this format (defaults to %Y-%m-%d)", Some('i'), ) .named( "begin-date", SyntaxShape::String, "beginning date range", Some('b'), ) .named("end-date", SyntaxShape::String, "ending date", Some('e')) .named( "increment", SyntaxShape::OneOf(vec![SyntaxShape::Duration, SyntaxShape::Int]), "increment dates by this duration (defaults to days if integer)", Some('n'), ) .named( "days", SyntaxShape::Int, "number of days to print (ignored if periods is used)", Some('d'), ) .named( "periods", SyntaxShape::Int, "number of periods to print", Some('p'), ) .switch("reverse", "print dates in reverse", Some('r')) .category(Category::Generators) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Return a list of the next 10 days in the YYYY-MM-DD format", example: "seq date --days 10", result: None, }, Example { description: "Return the previous 10 days in the YYYY-MM-DD format", example: "seq date --days 10 --reverse", result: None, }, Example { description: "Return the previous 10 days, starting today, in the MM/DD/YYYY format", example: "seq date --days 10 -o '%m/%d/%Y' --reverse", result: None, }, Example { description: "Return the first 10 days in January, 2020", example: "seq date --begin-date '2020-01-01' --end-date '2020-01-10' --increment 1day", result: Some(Value::list( vec![ Value::test_string("2020-01-01"), Value::test_string("2020-01-02"), Value::test_string("2020-01-03"), Value::test_string("2020-01-04"), Value::test_string("2020-01-05"), Value::test_string("2020-01-06"), Value::test_string("2020-01-07"), Value::test_string("2020-01-08"), Value::test_string("2020-01-09"), Value::test_string("2020-01-10"), ], Span::test_data(), )), }, Example { description: "Return the first 10 days in January, 2020 using --days flag", example: "seq date --begin-date '2020-01-01' --days 10 --increment 1day", result: Some(Value::list( vec![ Value::test_string("2020-01-01"), Value::test_string("2020-01-02"), Value::test_string("2020-01-03"), Value::test_string("2020-01-04"), Value::test_string("2020-01-05"), Value::test_string("2020-01-06"), Value::test_string("2020-01-07"), Value::test_string("2020-01-08"), Value::test_string("2020-01-09"), Value::test_string("2020-01-10"), ], Span::test_data(), )), }, Example { description: "Return the first five 5-minute periods starting January 1, 2020", example: "seq date --begin-date '2020-01-01' --periods 5 --increment 5min --output-format '%Y-%m-%d %H:%M:%S'", result: Some(Value::list( vec![ Value::test_string("2020-01-01 00:00:00"), Value::test_string("2020-01-01 00:05:00"), Value::test_string("2020-01-01 00:10:00"), Value::test_string("2020-01-01 00:15:00"), Value::test_string("2020-01-01 00:20:00"), ], Span::test_data(), )), }, Example { description: "print every fifth day between January 1st 2020 and January 31st 2020", example: "seq date --begin-date '2020-01-01' --end-date '2020-01-31' --increment 5day", result: Some(Value::list( vec![ Value::test_string("2020-01-01"), Value::test_string("2020-01-06"), Value::test_string("2020-01-11"), Value::test_string("2020-01-16"), Value::test_string("2020-01-21"), Value::test_string("2020-01-26"), Value::test_string("2020-01-31"), ], Span::test_data(), )), }, Example { description: "increment defaults to days if no duration is supplied", example: "seq date --begin-date '2020-01-01' --end-date '2020-01-31' --increment 5", result: Some(Value::list( vec![ Value::test_string("2020-01-01"), Value::test_string("2020-01-06"), Value::test_string("2020-01-11"), Value::test_string("2020-01-16"), Value::test_string("2020-01-21"), Value::test_string("2020-01-26"), Value::test_string("2020-01-31"), ], Span::test_data(), )), }, Example { description: "print every six hours starting January 1st, 2020 until January 3rd, 2020", example: "seq date --begin-date '2020-01-01' --end-date '2020-01-03' --increment 6hr --output-format '%Y-%m-%d %H:%M:%S'", result: Some(Value::list( vec![ Value::test_string("2020-01-01 00:00:00"), Value::test_string("2020-01-01 06:00:00"), Value::test_string("2020-01-01 12:00:00"), Value::test_string("2020-01-01 18:00:00"), Value::test_string("2020-01-02 00:00:00"), Value::test_string("2020-01-02 06:00:00"), Value::test_string("2020-01-02 12:00:00"), Value::test_string("2020-01-02 18:00:00"), Value::test_string("2020-01-03 00:00:00"), ], Span::test_data(), )), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let output_format: Option<Spanned<String>> = call.get_flag(engine_state, stack, "output-format")?; let input_format: Option<Spanned<String>> = call.get_flag(engine_state, stack, "input-format")?; let begin_date: Option<Spanned<String>> = call.get_flag(engine_state, stack, "begin-date")?; let end_date: Option<Spanned<String>> = call.get_flag(engine_state, stack, "end-date")?; let increment = match call.get_flag::<Value>(engine_state, stack, "increment")? { Some(increment) => { let span = increment.span(); match increment { Value::Int { val, .. } => Some( val.checked_mul(NANOSECONDS_IN_DAY) .ok_or_else(|| ShellError::GenericError { error: "increment is too large".into(), msg: "increment is too large".into(), span: Some(span), help: None, inner: vec![], })? .into_spanned(span), ), Value::Duration { val, .. } => Some(val.into_spanned(span)), _ => None, } } None => None, }; let days: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "days")?; let periods: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "periods")?; let reverse = call.has_flag(engine_state, stack, "reverse")?; let out_format = match output_format { Some(s) => Some(Value::string(s.item, s.span)), _ => None, }; let in_format = match input_format { Some(s) => Some(Value::string(s.item, s.span)), _ => None, }; let begin = match begin_date { Some(s) => Some(s.item), _ => None, }; let end = match end_date { Some(s) => Some(s.item), _ => None, }; let inc = match increment { Some(i) => Value::int(i.item, i.span), _ => Value::int(NANOSECONDS_IN_DAY, call.head), }; let day_count = days.map(|i| Value::int(i.item, i.span)); let period_count = periods.map(|i| Value::int(i.item, i.span)); let mut rev = false; if reverse { rev = reverse; } Ok(run_seq_dates( out_format, in_format, begin, end, inc, day_count, period_count, rev, call.head, )? .into_pipeline_data()) } } #[allow(clippy::unnecessary_lazy_evaluations)] pub fn parse_date_string(s: &str, format: &str) -> Result<NaiveDateTime, &'static str> { NaiveDateTime::parse_from_str(s, format).or_else(|_| { // If parsing as DateTime fails, try parsing as Date before throwing error let date = NaiveDate::parse_from_str(s, format).map_err(|_| "Failed to parse date.")?; date.and_hms_opt(0, 0, 0) .ok_or_else(|| "Failed to convert NaiveDate to NaiveDateTime.") }) } #[allow(clippy::too_many_arguments)] pub fn run_seq_dates( output_format: Option<Value>, input_format: Option<Value>, beginning_date: Option<String>, ending_date: Option<String>, increment: Value, day_count: Option<Value>, period_count: Option<Value>, reverse: bool, call_span: Span, ) -> Result<Value, ShellError> { let today = Local::now().naive_local(); // if cannot convert , it will return error let increment_span = increment.span(); let mut step_size: i64 = i64::from_value(increment)?; if step_size == 0 { return Err(ShellError::GenericError { error: "increment cannot be 0".into(), msg: "increment cannot be 0".into(), span: Some(increment_span), help: None, inner: vec![], }); } let in_format = match input_format { Some(i) => match i.coerce_into_string() { Ok(v) => v, Err(e) => { return Err(ShellError::GenericError { error: e.to_string(), msg: "".into(), span: None, help: Some("error with input_format as_string".into()), inner: vec![], }); } }, _ => "%Y-%m-%d".to_string(), }; let out_format = match output_format { Some(o) => match o.coerce_into_string() { Ok(v) => v, Err(e) => { return Err(ShellError::GenericError { error: e.to_string(), msg: "".into(), span: None, help: Some("error with output_format as_string".into()), inner: vec![], }); } }, _ => "%Y-%m-%d".to_string(), }; let start_date = match beginning_date { Some(d) => match parse_date_string(&d, &in_format) { Ok(nd) => nd, Err(e) => { return Err(ShellError::GenericError { error: e.to_string(), msg: "Failed to parse date".into(), span: Some(call_span), help: None, inner: vec![], }); } }, _ => today, }; let mut end_date = match ending_date { Some(d) => match parse_date_string(&d, &in_format) { Ok(nd) => nd, Err(e) => { return Err(ShellError::GenericError { error: e.to_string(), msg: "Failed to parse date".into(), span: Some(call_span), help: None, inner: vec![], }); } }, _ => today, }; let mut days_to_output = match day_count { Some(d) => i64::from_value(d)?, None => 0i64, }; let mut periods_to_output = match period_count { Some(d) => i64::from_value(d)?, None => 0i64, }; // Make the signs opposite if we're created dates in reverse direction if reverse { step_size *= -1; days_to_output *= -1; periods_to_output *= -1; } // --days is ignored when --periods is set if periods_to_output != 0 { end_date = periods_to_output .checked_sub(1) .and_then(|val| val.checked_mul(step_size.abs())) .map(Duration::nanoseconds) .and_then(|inc| start_date.checked_add_signed(inc)) .ok_or_else(|| ShellError::GenericError { error: "incrementing by the number of periods is too large".into(), msg: "incrementing by the number of periods is too large".into(), span: Some(call_span), help: None, inner: vec![], })?; } else if days_to_output != 0 { end_date = days_to_output .checked_sub(1) .and_then(Duration::try_days) .and_then(|days| start_date.checked_add_signed(days)) .ok_or_else(|| ShellError::GenericError { error: "int value too large".into(), msg: "int value too large".into(), span: Some(call_span), help: None, inner: vec![], })?; } // conceptually counting down with a positive step or counting up with a negative step // makes no sense, attempt to do what one means by inverting the signs in those cases. if (start_date > end_date) && (step_size > 0) || (start_date < end_date) && step_size < 0 { step_size = -step_size; } let is_out_of_range = |next| (step_size > 0 && next > end_date) || (step_size < 0 && next < end_date); // Bounds are enforced by i64 conversion above let step_size = Duration::nanoseconds(step_size); let mut next = start_date; if is_out_of_range(next) { return Err(ShellError::GenericError { error: "date is out of range".into(), msg: "date is out of range".into(), span: Some(call_span), help: None, inner: vec![], }); } let mut ret = vec![]; loop { let mut date_string = String::new(); match write!(date_string, "{}", next.format(&out_format)) { Ok(_) => {} Err(e) => { return Err(ShellError::GenericError { error: "Invalid output format".into(), msg: e.to_string(), span: Some(call_span), help: None, inner: vec![], }); } } ret.push(Value::string(date_string, call_span)); if let Some(n) = next.checked_add_signed(step_size) { next = n; } else { return Err(ShellError::GenericError { error: "date overflow".into(), msg: "adding the increment overflowed".into(), span: Some(call_span), help: None, inner: vec![], }); } if is_out_of_range(next) { break; } } Ok(Value::list(ret, call_span)) } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SeqDate {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/open.rs
crates/nu-command/src/filesystem/open.rs
#[allow(deprecated)] use nu_engine::{command_prelude::*, current_dir, eval_call}; use nu_path::is_windows_device_path; use nu_protocol::{ DataSource, NuGlob, PipelineMetadata, ast, debugger::{WithDebug, WithoutDebug}, shell_error::{self, io::IoError}, }; use std::{ collections::HashMap, path::{Path, PathBuf}, }; #[cfg(feature = "sqlite")] use crate::database::SQLiteDatabase; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; #[derive(Clone)] pub struct Open; impl Command for Open { fn name(&self) -> &str { "open" } fn description(&self) -> &str { "Load a file into a cell, converting to table if possible (avoid by appending '--raw')." } fn extra_description(&self) -> &str { "Support to automatically parse files with an extension `.xyz` can be provided by a `from xyz` command in scope." } fn search_terms(&self) -> Vec<&str> { vec![ "load", "read", "load_file", "read_file", "cat", "get-content", ] } fn signature(&self) -> nu_protocol::Signature { Signature::build("open") .input_output_types(vec![ (Type::Nothing, Type::Any), (Type::String, Type::Any), // FIXME Type::Any input added to disable pipeline input type checking, as run-time checks can raise undesirable type errors // which aren't caught by the parser. see https://github.com/nushell/nushell/pull/14922 for more details (Type::Any, Type::Any), ]) .rest( "files", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]), "The file(s) to open.", ) .switch("raw", "open file as raw binary", Some('r')) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let raw = call.has_flag(engine_state, stack, "raw")?; let call_span = call.head; #[allow(deprecated)] let cwd = current_dir(engine_state, stack)?; let mut paths = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; if paths.is_empty() && !call.has_positional_args(stack, 0) { // try to use path from pipeline input if there were no positional or spread args let (filename, span) = match input { PipelineData::Value(val, ..) => { let span = val.span(); (val.coerce_into_string()?, span) } _ => { return Err(ShellError::MissingParameter { param_name: "needs filename".to_string(), span: call.head, }); } }; paths.push(Spanned { item: NuGlob::Expand(filename), span, }); } let mut output = vec![]; for mut path in paths { //FIXME: `open` should not have to do this path.item = path.item.strip_ansi_string_unlikely(); let arg_span = path.span; // let path_no_whitespace = &path.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d')); let matches: Box<dyn Iterator<Item = Result<PathBuf, ShellError>> + Send> = if is_windows_device_path(Path::new(&path.item.to_string())) { Box::new(vec![Ok(PathBuf::from(path.item.to_string()))].into_iter()) } else { nu_engine::glob_from( &path, &cwd, call_span, None, engine_state.signals().clone(), ) .map_err(|err| match err { ShellError::Io(mut err) => { err.kind = err.kind.not_found_as(NotFound::File); err.span = arg_span; err.into() } _ => err, })? .1 }; for path in matches { let path = path?; let path = Path::new(&path); if permission_denied(path) { let err = IoError::new( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::PermissionDenied), arg_span, PathBuf::from(path), ); #[cfg(unix)] let err = { let mut err = err; err.additional_context = Some( match path.metadata() { Ok(md) => format!( "The permissions of {:o} does not allow access for this user", md.permissions().mode() & 0o0777 ), Err(e) => e.to_string(), } .into(), ); err }; return Err(err.into()); } else { #[cfg(feature = "sqlite")] if !raw { let res = SQLiteDatabase::try_from_path( path, arg_span, engine_state.signals().clone(), ) .map(|db| db.into_value(call.head).into_pipeline_data()); if res.is_ok() { return res; } } if path.is_dir() { // At least under windows this check ensures that we don't get a // permission denied error on directories return Err(ShellError::Io(IoError::new( #[allow( deprecated, reason = "we don't have a IsADirectory variant here, so we provide one" )] shell_error::io::ErrorKind::from_std(std::io::ErrorKind::IsADirectory), arg_span, PathBuf::from(path), ))); } let file = std::fs::File::open(path) .map_err(|err| IoError::new(err, arg_span, PathBuf::from(path)))?; // No content_type by default - Is added later if no converter is found let stream = PipelineData::byte_stream( ByteStream::file(file, call_span, engine_state.signals().clone()), Some(PipelineMetadata { data_source: DataSource::FilePath(path.to_path_buf()), ..Default::default() }), ); let exts_opt: Option<Vec<String>> = if raw { None } else { let path_str = path .file_name() .unwrap_or(std::ffi::OsStr::new(path)) .to_string_lossy() .to_lowercase(); Some(extract_extensions(path_str.as_str())) }; let converter = exts_opt.and_then(|exts| { exts.iter().find_map(|ext| { engine_state .find_decl(format!("from {ext}").as_bytes(), &[]) .map(|id| (id, ext.to_string())) }) }); match converter { Some((converter_id, ext)) => { let open_call = ast::Call { decl_id: converter_id, head: call_span, arguments: vec![], parser_info: HashMap::new(), }; let command_output = if engine_state.is_debugging() { eval_call::<WithDebug>(engine_state, stack, &open_call, stream) } else { eval_call::<WithoutDebug>(engine_state, stack, &open_call, stream) }; output.push(command_output.map_err(|inner| { ShellError::GenericError{ error: format!("Error while parsing as {ext}"), msg: format!("Could not parse '{}' with `from {}`", path.display(), ext), span: Some(arg_span), help: Some(format!("Check out `help from {}` or `help from` for more options or open raw data with `open --raw '{}'`", ext, path.display())), inner: vec![inner], } })?); } None => { // If no converter was found, add content-type metadata let content_type = path .extension() .map(|ext| ext.to_string_lossy().to_string()) .and_then(|ref s| detect_content_type(s)); let stream_with_content_type = stream.set_metadata(Some(PipelineMetadata { data_source: DataSource::FilePath(path.to_path_buf()), content_type, ..Default::default() })); output.push(stream_with_content_type); } } } } } if output.is_empty() { Ok(PipelineData::empty()) } else if output.len() == 1 { Ok(output.remove(0)) } else { Ok(output .into_iter() .flatten() .into_pipeline_data(call_span, engine_state.signals().clone())) } } fn examples(&self) -> Vec<nu_protocol::Example<'_>> { vec![ Example { description: "Open a file, with structure (based on file extension or SQLite database header)", example: "open myfile.json", result: None, }, Example { description: "Open a file, as raw bytes", example: "open myfile.json --raw", result: None, }, Example { description: "Open a file, using the input to get filename", example: "'myfile.txt' | open", result: None, }, Example { description: "Open a file, and decode it by the specified encoding", example: "open myfile.txt --raw | decode utf-8", result: None, }, Example { description: "Create a custom `from` parser to open newline-delimited JSON files with `open`", example: r#"def "from ndjson" [] { from json -o }; open myfile.ndjson"#, result: None, }, Example { description: "Show the extensions for which the `open` command will automatically parse", example: r#"scope commands | where name starts-with "from " | insert extension { get name | str replace -r "^from " "" | $"*.($in)" } | select extension name | rename extension command "#, result: None, }, ] } } fn permission_denied(dir: impl AsRef<Path>) -> bool { match dir.as_ref().read_dir() { Err(e) => matches!(e.kind(), std::io::ErrorKind::PermissionDenied), Ok(_) => false, } } fn extract_extensions(filename: &str) -> Vec<String> { let parts: Vec<&str> = filename.split('.').collect(); let mut extensions: Vec<String> = Vec::new(); let mut current_extension = String::new(); for part in parts.iter().rev() { if current_extension.is_empty() { current_extension.push_str(part); } else { current_extension = format!("{part}.{current_extension}"); } extensions.push(current_extension.clone()); } extensions.pop(); extensions.reverse(); extensions } fn detect_content_type(extension: &str) -> Option<String> { // This will allow the overriding of metadata to be consistent with // the content type match extension { // Per RFC-9512, application/yaml should be used "yaml" | "yml" => Some("application/yaml".to_string()), "nu" => Some("application/x-nuscript".to_string()), "json" | "jsonl" | "ndjson" => Some("application/json".to_string()), "nuon" => Some("application/x-nuon".to_string()), _ => mime_guess::from_ext(extension) .first() .map(|mime| mime.to_string()), } } #[cfg(test)] mod test { #[test] fn test_content_type() {} }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/ls.rs
crates/nu-command/src/filesystem/ls.rs
use crate::{DirBuilder, DirInfo}; use chrono::{DateTime, Local, LocalResult, TimeZone, Utc}; use nu_engine::glob_from; #[allow(deprecated)] use nu_engine::{command_prelude::*, env::current_dir}; use nu_glob::MatchOptions; use nu_path::{expand_path_with, expand_to_real_path}; use nu_protocol::{ DataSource, NuGlob, PipelineMetadata, Signals, shell_error::{self, io::IoError}, }; use pathdiff::diff_paths; use rayon::prelude::*; #[cfg(unix)] use std::os::unix::fs::PermissionsExt; use std::{ cmp::Ordering, path::PathBuf, sync::{Arc, Mutex, mpsc}, time::{SystemTime, UNIX_EPOCH}, }; #[derive(Clone)] pub struct Ls; #[derive(Clone, Copy)] struct Args { all: bool, long: bool, short_names: bool, full_paths: bool, du: bool, directory: bool, use_mime_type: bool, use_threads: bool, call_span: Span, } impl Command for Ls { fn name(&self) -> &str { "ls" } fn description(&self) -> &str { "List the filenames, sizes, and modification times of items in a directory." } fn search_terms(&self) -> Vec<&str> { vec!["dir"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("ls") .input_output_types(vec![(Type::Nothing, Type::table())]) // LsGlobPattern is similar to string, it won't auto-expand // and we use it to track if the user input is quoted. .rest("pattern", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]), "The glob pattern to use.") .switch("all", "Show hidden files", Some('a')) .switch( "long", "Get all available columns for each entry (slower; columns are platform-dependent)", Some('l'), ) .switch( "short-names", "Only print the file names, and not the path", Some('s'), ) .switch("full-paths", "display paths as absolute paths", Some('f')) .switch( "du", "Display the apparent directory size (\"disk usage\") in place of the directory metadata size", Some('d'), ) .switch( "directory", "List the specified directory itself instead of its contents", Some('D'), ) .switch("mime-type", "Show mime-type in type column instead of 'file' (based on filenames only; files' contents are not examined)", Some('m')) .switch("threads", "Use multiple threads to list contents. Output will be non-deterministic.", Some('t')) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let all = call.has_flag(engine_state, stack, "all")?; let long = call.has_flag(engine_state, stack, "long")?; let short_names = call.has_flag(engine_state, stack, "short-names")?; let full_paths = call.has_flag(engine_state, stack, "full-paths")?; let du = call.has_flag(engine_state, stack, "du")?; let directory = call.has_flag(engine_state, stack, "directory")?; let use_mime_type = call.has_flag(engine_state, stack, "mime-type")?; let use_threads = call.has_flag(engine_state, stack, "threads")?; let call_span = call.head; #[allow(deprecated)] let cwd = current_dir(engine_state, stack)?; let args = Args { all, long, short_names, full_paths, du, directory, use_mime_type, use_threads, call_span, }; let pattern_arg = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; let input_pattern_arg = if !call.has_positional_args(stack, 0) { None } else { Some(pattern_arg) }; match input_pattern_arg { None => Ok( ls_for_one_pattern(None, args, engine_state.signals().clone(), cwd)? .into_pipeline_data_with_metadata( call_span, engine_state.signals().clone(), PipelineMetadata { data_source: DataSource::Ls, ..Default::default() }, ), ), Some(pattern) => { let mut result_iters = vec![]; for pat in pattern { result_iters.push(ls_for_one_pattern( Some(pat), args, engine_state.signals().clone(), cwd.clone(), )?) } // Here nushell needs to use // use `flatten` to chain all iterators into one. Ok(result_iters .into_iter() .flatten() .into_pipeline_data_with_metadata( call_span, engine_state.signals().clone(), PipelineMetadata { data_source: DataSource::Ls, ..Default::default() }, )) } } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "List visible files in the current directory", example: "ls", result: None, }, Example { description: "List visible files in a subdirectory", example: "ls subdir", result: None, }, Example { description: "List visible files with full path in the parent directory", example: "ls -f ..", result: None, }, Example { description: "List Rust files", example: "ls *.rs", result: None, }, Example { description: "List files and directories whose name do not contain 'bar'", example: "ls | where name !~ bar", result: None, }, Example { description: "List the full path of all dirs in your home directory", example: "ls -a ~ | where type == dir", result: None, }, Example { description: "List only the names (not paths) of all dirs in your home directory which have not been modified in 7 days", example: "ls -as ~ | where type == dir and modified < ((date now) - 7day)", result: None, }, Example { description: "Recursively list all files and subdirectories under the current directory using a glob pattern", example: "ls -a **/*", result: None, }, Example { description: "Recursively list *.rs and *.toml files using the glob command", example: "ls ...(glob **/*.{rs,toml})", result: None, }, Example { description: "List given paths and show directories themselves", example: "['/path/to/directory' '/path/to/file'] | each {|| ls -D $in } | flatten", result: None, }, ] } } fn ls_for_one_pattern( pattern_arg: Option<Spanned<NuGlob>>, args: Args, signals: Signals, cwd: PathBuf, ) -> 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 (tx, rx) = mpsc::channel(); let Args { all, long, short_names, full_paths, du, directory, use_mime_type, use_threads, call_span, } = args; let pattern_arg = { if let Some(path) = pattern_arg { // it makes no sense to list an empty string. if path.item.as_ref().is_empty() { return Err(ShellError::Io(IoError::new_with_additional_context( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::NotFound), path.span, PathBuf::from(path.item.to_string()), "empty string('') directory or file does not exist", ))); } match path.item { NuGlob::DoNotExpand(p) => Some(Spanned { item: NuGlob::DoNotExpand(nu_utils::strip_ansi_string_unlikely(p)), span: path.span, }), NuGlob::Expand(p) => Some(Spanned { item: NuGlob::Expand(nu_utils::strip_ansi_string_unlikely(p)), span: path.span, }), } } else { pattern_arg } }; let mut just_read_dir = false; let p_tag: Span = pattern_arg.as_ref().map(|p| p.span).unwrap_or(call_span); let (pattern_arg, absolute_path) = match pattern_arg { Some(pat) => { // expand with cwd here is only used for checking let tmp_expanded = nu_path::expand_path_with(pat.item.as_ref(), &cwd, pat.item.is_expand()); // Avoid checking and pushing "*" to the path when directory (do not show contents) flag is true if !directory && tmp_expanded.is_dir() { if read_dir(tmp_expanded, p_tag, use_threads, signals.clone())? .next() .is_none() { return Ok(Value::test_nothing().into_pipeline_data()); } just_read_dir = !(pat.item.is_expand() && nu_glob::is_glob(pat.item.as_ref())); } // it's absolute path if: // 1. pattern is absolute. // 2. pattern can be expanded, and after expands to real_path, it's absolute. // here `expand_to_real_path` call is required, because `~/aaa` should be absolute // path. let absolute_path = Path::new(pat.item.as_ref()).is_absolute() || (pat.item.is_expand() && expand_to_real_path(pat.item.as_ref()).is_absolute()); (pat.item, absolute_path) } None => { // Avoid pushing "*" to the default path when directory (do not show contents) flag is true if directory { (NuGlob::Expand(".".to_string()), false) } else if read_dir(cwd.clone(), p_tag, use_threads, signals.clone())? .next() .is_none() { return Ok(Value::test_nothing().into_pipeline_data()); } else { (NuGlob::Expand("*".to_string()), false) } } }; let hidden_dir_specified = is_hidden_dir(pattern_arg.as_ref()); let path = pattern_arg.into_spanned(p_tag); let (prefix, paths) = if just_read_dir { let expanded = nu_path::expand_path_with(path.item.as_ref(), &cwd, path.item.is_expand()); let paths = read_dir(expanded.clone(), p_tag, use_threads, signals.clone())?; // just need to read the directory, so prefix is path itself. (Some(expanded), paths) } else { let glob_options = if all { None } else { let glob_options = MatchOptions { recursive_match_hidden_dir: false, ..Default::default() }; Some(glob_options) }; glob_from(&path, &cwd, call_span, glob_options, signals.clone())? }; let mut paths_peek = paths.peekable(); let no_matches = paths_peek.peek().is_none(); signals.check(&call_span)?; if no_matches { return Err(ShellError::GenericError { error: format!("No matches found for {:?}", path.item), msg: "Pattern, file or folder not found".into(), span: Some(p_tag), help: Some("no matches found".into()), inner: vec![], }); } let hidden_dirs = Arc::new(Mutex::new(Vec::new())); let signals_clone = signals.clone(); let pool = if use_threads { let count = std::thread::available_parallelism() .map_err(|err| { IoError::new_with_additional_context( err, call_span, None, "Could not get available parallelism", ) })? .get(); create_pool(count)? } else { create_pool(1)? }; pool.install(|| { rayon::spawn(move || { let result = paths_peek .par_bridge() .filter_map(move |x| match x { Ok(path) => { let metadata = std::fs::symlink_metadata(&path).ok(); let hidden_dir_clone = Arc::clone(&hidden_dirs); let mut hidden_dir_mutex = hidden_dir_clone .lock() .expect("Unable to acquire lock for hidden_dirs"); if path_contains_hidden_folder(&path, &hidden_dir_mutex) { return None; } if !all && !hidden_dir_specified && is_hidden_dir(&path) { if path.is_dir() { hidden_dir_mutex.push(path); drop(hidden_dir_mutex); } return None; } let display_name = if short_names { path.file_name().map(|os| os.to_string_lossy().to_string()) } else if full_paths || absolute_path { Some(path.to_string_lossy().to_string()) } else if let Some(prefix) = &prefix { if let Ok(remainder) = path.strip_prefix(prefix) { if directory { // When the path is the same as the cwd, path_diff should be "." let path_diff = if let Some(path_diff_not_dot) = diff_paths(&path, &cwd) { let path_diff_not_dot = path_diff_not_dot.to_string_lossy(); if path_diff_not_dot.is_empty() { ".".to_string() } else { path_diff_not_dot.to_string() } } else { path.to_string_lossy().to_string() }; Some(path_diff) } else { let new_prefix = if let Some(pfx) = diff_paths(prefix, &cwd) { pfx } else { prefix.to_path_buf() }; Some(new_prefix.join(remainder).to_string_lossy().to_string()) } } else { Some(path.to_string_lossy().to_string()) } } else { Some(path.to_string_lossy().to_string()) } .ok_or_else(|| ShellError::GenericError { error: format!("Invalid file name: {:}", path.to_string_lossy()), msg: "invalid file name".into(), span: Some(call_span), help: None, inner: vec![], }); match display_name { Ok(name) => { let entry = dir_entry_dict( &path, &name, metadata.as_ref(), call_span, long, du, &signals_clone, use_mime_type, args.full_paths, ); match entry { Ok(value) => Some(value), Err(err) => Some(Value::error(err, call_span)), } } Err(err) => Some(Value::error(err, call_span)), } } Err(err) => Some(Value::error(err, call_span)), }) .try_for_each(|stream| { tx.send(stream).map_err(|e| ShellError::GenericError { error: "Error streaming data".into(), msg: e.to_string(), span: Some(call_span), help: None, inner: vec![], }) }) .map_err(|err| ShellError::GenericError { error: "Unable to create a rayon pool".into(), msg: err.to_string(), span: Some(call_span), help: None, inner: vec![], }); if let Err(error) = result { let _ = tx.send(Value::error(error, call_span)); } }); }); Ok(rx .into_iter() .into_pipeline_data(call_span, signals.clone())) } fn is_hidden_dir(dir: impl AsRef<Path>) -> bool { #[cfg(windows)] { use std::os::windows::fs::MetadataExt; if let Ok(metadata) = dir.as_ref().metadata() { let attributes = metadata.file_attributes(); // https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants (attributes & 0x2) != 0 } else { false } } #[cfg(not(windows))] { dir.as_ref() .file_name() .map(|name| name.to_string_lossy().starts_with('.')) .unwrap_or(false) } } fn path_contains_hidden_folder(path: &Path, folders: &[PathBuf]) -> bool { if folders.iter().any(|p| path.starts_with(p.as_path())) { return true; } false } #[cfg(unix)] use std::os::unix::fs::FileTypeExt; use std::path::Path; pub fn get_file_type(md: &std::fs::Metadata, display_name: &str, use_mime_type: bool) -> String { let ft = md.file_type(); let mut file_type = "unknown"; if ft.is_dir() { file_type = "dir"; } else if ft.is_file() { file_type = "file"; } else if ft.is_symlink() { file_type = "symlink"; } else { #[cfg(unix)] { if ft.is_block_device() { file_type = "block device"; } else if ft.is_char_device() { file_type = "char device"; } else if ft.is_fifo() { file_type = "pipe"; } else if ft.is_socket() { file_type = "socket"; } } } if use_mime_type { let guess = mime_guess::from_path(display_name); let mime_guess = match guess.first() { Some(mime_type) => mime_type.essence_str().to_string(), None => "unknown".to_string(), }; if file_type == "file" { mime_guess } else { file_type.to_string() } } else { file_type.to_string() } } #[allow(clippy::too_many_arguments)] pub(crate) fn dir_entry_dict( filename: &std::path::Path, // absolute path display_name: &str, // file name to be displayed metadata: Option<&std::fs::Metadata>, span: Span, long: bool, du: bool, signals: &Signals, use_mime_type: bool, full_symlink_target: bool, ) -> Result<Value, ShellError> { #[cfg(windows)] if metadata.is_none() { return Ok(windows_helper::dir_entry_dict_windows_fallback( filename, display_name, span, long, )); } let mut record = Record::new(); let mut file_type = "unknown".to_string(); record.push("name", Value::string(display_name, span)); if let Some(md) = metadata { file_type = get_file_type(md, display_name, use_mime_type); record.push("type", Value::string(file_type.clone(), span)); } else { record.push("type", Value::nothing(span)); } if long && let Some(md) = metadata { record.push( "target", if md.file_type().is_symlink() { if let Ok(path_to_link) = filename.read_link() { // Actually `filename` should always have a parent because it's a symlink. // But for safety, we check `filename.parent().is_some()` first. if full_symlink_target && filename.parent().is_some() { Value::string( expand_path_with( path_to_link, filename .parent() .expect("already check the filename have a parent"), true, ) .to_string_lossy(), span, ) } else { Value::string(path_to_link.to_string_lossy(), span) } } else { Value::string("Could not obtain target file's path", span) } } else { Value::nothing(span) }, ) } if long && let Some(md) = metadata { record.push("readonly", Value::bool(md.permissions().readonly(), span)); #[cfg(unix)] { use nu_utils::filesystem::users; use std::os::unix::fs::MetadataExt; let mode = md.permissions().mode(); record.push( "mode", Value::string(umask::Mode::from(mode).to_string(), span), ); let nlinks = md.nlink(); record.push("num_links", Value::int(nlinks as i64, span)); let inode = md.ino(); record.push("inode", Value::int(inode as i64, span)); record.push( "user", if let Some(user) = users::get_user_by_uid(md.uid().into()) { Value::string(user.name, span) } else { Value::int(md.uid().into(), span) }, ); record.push( "group", if let Some(group) = users::get_group_by_gid(md.gid().into()) { Value::string(group.name, span) } else { Value::int(md.gid().into(), span) }, ); } } record.push( "size", if let Some(md) = metadata { let zero_sized = file_type == "pipe" || file_type == "socket" || file_type == "char device" || file_type == "block device"; if md.is_dir() { if du { let params = DirBuilder::new(Span::new(0, 2), None, false, None, false); let dir_size = DirInfo::new(filename, &params, None, span, signals)?.get_size(); Value::filesize(dir_size as i64, span) } else { let dir_size: u64 = md.len(); Value::filesize(dir_size as i64, span) } } else if md.is_file() { Value::filesize(md.len() as i64, span) } else if md.file_type().is_symlink() { if let Ok(symlink_md) = filename.symlink_metadata() { Value::filesize(symlink_md.len() as i64, span) } else { Value::nothing(span) } } else if zero_sized { Value::filesize(0, span) } else { Value::nothing(span) } } else { Value::nothing(span) }, ); if let Some(md) = metadata { if long { record.push("created", { let mut val = Value::nothing(span); if let Ok(c) = md.created() && let Some(local) = try_convert_to_local_date_time(c) { val = Value::date(local.with_timezone(local.offset()), span); } val }); record.push("accessed", { let mut val = Value::nothing(span); if let Ok(a) = md.accessed() && let Some(local) = try_convert_to_local_date_time(a) { val = Value::date(local.with_timezone(local.offset()), span) } val }); } record.push("modified", { let mut val = Value::nothing(span); if let Ok(m) = md.modified() && let Some(local) = try_convert_to_local_date_time(m) { val = Value::date(local.with_timezone(local.offset()), span); } val }) } else { if long { record.push("created", Value::nothing(span)); record.push("accessed", Value::nothing(span)); } record.push("modified", Value::nothing(span)); } Ok(Value::record(record, span)) } // TODO: can we get away from local times in `ls`? internals might be cleaner if we worked in UTC // and left the conversion to local time to the display layer fn try_convert_to_local_date_time(t: SystemTime) -> Option<DateTime<Local>> { // Adapted from https://github.com/chronotope/chrono/blob/v0.4.19/src/datetime.rs#L755-L767. let (sec, nsec) = match t.duration_since(UNIX_EPOCH) { Ok(dur) => (dur.as_secs() as i64, dur.subsec_nanos()), Err(e) => { // unlikely but should be handled let dur = e.duration(); let (sec, nsec) = (dur.as_secs() as i64, dur.subsec_nanos()); if nsec == 0 { (-sec, 0) } else { (-sec - 1, 1_000_000_000 - nsec) } } }; const NEG_UNIX_EPOCH: i64 = -11644473600; // t was invalid 0, UNIX_EPOCH subtracted above. if sec == NEG_UNIX_EPOCH { // do not tz lookup invalid SystemTime return None; } match Utc.timestamp_opt(sec, nsec) { LocalResult::Single(t) => Some(t.with_timezone(&Local)), _ => None, } } // #[cfg(windows)] is just to make Clippy happy, remove if you ever want to use this on other platforms #[cfg(windows)] fn unix_time_to_local_date_time(secs: i64) -> Option<DateTime<Local>> { match Utc.timestamp_opt(secs, 0) { LocalResult::Single(t) => Some(t.with_timezone(&Local)), _ => None, } } #[cfg(windows)] mod windows_helper { use super::*; use nu_protocol::shell_error; use std::os::windows::prelude::OsStrExt; use windows::Win32::Foundation::FILETIME; use windows::Win32::Storage::FileSystem::{ FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY, FILE_ATTRIBUTE_REPARSE_POINT, FindClose, FindFirstFileW, WIN32_FIND_DATAW, }; use windows::Win32::System::SystemServices::{ IO_REPARSE_TAG_MOUNT_POINT, IO_REPARSE_TAG_SYMLINK, }; /// A secondary way to get file info on Windows, for when std::fs::symlink_metadata() fails. /// dir_entry_dict depends on metadata, but that can't be retrieved for some Windows system files: /// https://github.com/rust-lang/rust/issues/96980 pub fn dir_entry_dict_windows_fallback( filename: &Path, display_name: &str, span: Span, long: bool, ) -> Value { let mut record = Record::new(); record.push("name", Value::string(display_name, span)); let find_data = match find_first_file(filename, span) { Ok(fd) => fd, Err(e) => { // Sometimes this happens when the file name is not allowed on Windows (ex: ends with a '.', pipes) // For now, we just log it and give up on returning metadata columns // TODO: find another way to get this data (like cmd.exe, pwsh, and MINGW bash can) log::error!("ls: '{}' {}", filename.to_string_lossy(), e); return Value::record(record, span); } }; record.push( "type", Value::string(get_file_type_windows_fallback(&find_data), span), ); if long { record.push( "target", if is_symlink(&find_data) { if let Ok(path_to_link) = filename.read_link() { Value::string(path_to_link.to_string_lossy(), span) } else { Value::string("Could not obtain target file's path", span) } } else { Value::nothing(span) }, ); record.push( "readonly", Value::bool( find_data.dwFileAttributes & FILE_ATTRIBUTE_READONLY.0 != 0, span, ), ); } let file_size = ((find_data.nFileSizeHigh as u64) << 32) | find_data.nFileSizeLow as u64; record.push("size", Value::filesize(file_size as i64, span)); if long { record.push("created", { let mut val = Value::nothing(span); let seconds_since_unix_epoch = unix_time_from_filetime(&find_data.ftCreationTime); if let Some(local) = unix_time_to_local_date_time(seconds_since_unix_epoch) { val = Value::date(local.with_timezone(local.offset()), span); } val }); record.push("accessed", { let mut val = Value::nothing(span); let seconds_since_unix_epoch = unix_time_from_filetime(&find_data.ftLastAccessTime); if let Some(local) = unix_time_to_local_date_time(seconds_since_unix_epoch) { val = Value::date(local.with_timezone(local.offset()), span); } val }); } record.push("modified", { let mut val = Value::nothing(span); let seconds_since_unix_epoch = unix_time_from_filetime(&find_data.ftLastWriteTime); if let Some(local) = unix_time_to_local_date_time(seconds_since_unix_epoch) { val = Value::date(local.with_timezone(local.offset()), span); } val }); Value::record(record, span) } fn unix_time_from_filetime(ft: &FILETIME) -> i64 { /// January 1, 1970 as Windows file time const EPOCH_AS_FILETIME: u64 = 116444736000000000; const HUNDREDS_OF_NANOSECONDS: u64 = 10000000; let time_u64 = ((ft.dwHighDateTime as u64) << 32) | (ft.dwLowDateTime as u64); if time_u64 > 0 {
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/utouch.rs
crates/nu-command/src/filesystem/utouch.rs
use chrono::{DateTime, FixedOffset}; use filetime::FileTime; use nu_engine::command_prelude::*; use nu_glob::{glob, is_glob}; use nu_path::expand_path_with; use nu_protocol::{NuGlob, shell_error::io::IoError}; use std::path::PathBuf; use uu_touch::{ChangeTimes, InputFile, Options, Source, error::TouchError}; use uucore::{localized_help_template, translate}; #[derive(Clone)] pub struct UTouch; impl Command for UTouch { fn name(&self) -> &str { "touch" } fn search_terms(&self) -> Vec<&str> { vec!["create", "file", "coreutils"] } fn signature(&self) -> Signature { Signature::build("touch") .input_output_types(vec![ (Type::Nothing, Type::Nothing) ]) .rest( "files", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Filepath]), "The file(s) to create. '-' is used to represent stdout." ) .named( "reference", SyntaxShape::Filepath, "Use the access and modification times of the reference file/directory instead of the current time", Some('r'), ) .named( "timestamp", SyntaxShape::DateTime, "Use the given timestamp instead of the current time", Some('t') ) .named( "date", SyntaxShape::String, "Use the given time instead of the current time. This can be a full timestamp or it can be relative to either the current time or reference file time (if given). For more information, see https://www.gnu.org/software/coreutils/manual/html_node/touch-invocation.html", Some('d') ) .switch( "modified", "Change only the modification time (if used with -a, access time is changed too)", Some('m'), ) .switch( "access", "Change only the access time (if used with -m, modification time is changed too)", Some('a'), ) .switch( "no-create", "Don't create the file if it doesn't exist", Some('c'), ) .switch( "no-deref", "Affect each symbolic link instead of any referenced file (only for systems that can change the timestamps of a symlink). Ignored if touching stdout", Some('s'), ) .category(Category::FileSystem) } fn description(&self) -> &str { "Creates one or more files." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // setup the uutils error translation let _ = localized_help_template("touch"); let change_mtime: bool = call.has_flag(engine_state, stack, "modified")?; let change_atime: bool = call.has_flag(engine_state, stack, "access")?; let no_create: bool = call.has_flag(engine_state, stack, "no-create")?; let no_deref: bool = call.has_flag(engine_state, stack, "no-deref")?; let file_globs = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; let cwd = engine_state.cwd(Some(stack))?; if file_globs.is_empty() { return Err(ShellError::MissingParameter { param_name: "requires file paths".to_string(), span: call.head, }); } let (reference_file, reference_span) = if let Some(reference) = call.get_flag::<Spanned<PathBuf>>(engine_state, stack, "reference")? { (Some(reference.item), Some(reference.span)) } else { (None, None) }; let (date_str, date_span) = if let Some(date) = call.get_flag::<Spanned<String>>(engine_state, stack, "date")? { (Some(date.item), Some(date.span)) } else { (None, None) }; let timestamp: Option<Spanned<DateTime<FixedOffset>>> = call.get_flag(engine_state, stack, "timestamp")?; let source = if let Some(timestamp) = timestamp { if let Some(reference_span) = reference_span { return Err(ShellError::IncompatibleParameters { left_message: "timestamp given".to_string(), left_span: timestamp.span, right_message: "reference given".to_string(), right_span: reference_span, }); } if let Some(date_span) = date_span { return Err(ShellError::IncompatibleParameters { left_message: "timestamp given".to_string(), left_span: timestamp.span, right_message: "date given".to_string(), right_span: date_span, }); } Source::Timestamp(FileTime::from_unix_time( timestamp.item.timestamp(), timestamp.item.timestamp_subsec_nanos(), )) } else if let Some(reference_file) = reference_file { let reference_file = expand_path_with(reference_file, &cwd, true); Source::Reference(reference_file) } else { Source::Now }; let change_times = if change_atime && !change_mtime { ChangeTimes::AtimeOnly } else if change_mtime && !change_atime { ChangeTimes::MtimeOnly } else { ChangeTimes::Both }; let mut input_files = Vec::new(); for file_glob in &file_globs { if file_glob.item.as_ref() == "-" { input_files.push(InputFile::Stdout); } else { let file_path = expand_path_with(file_glob.item.as_ref(), &cwd, file_glob.item.is_expand()); if !file_glob.item.is_expand() { input_files.push(InputFile::Path(file_path)); continue; } let mut expanded_globs = glob(&file_path.to_string_lossy(), engine_state.signals().clone()) .unwrap_or_else(|_| { panic!( "Failed to process file path: {}", &file_path.to_string_lossy() ) }) .peekable(); if expanded_globs.peek().is_none() { let file_name = file_path.file_name().unwrap_or_else(|| { panic!( "Failed to process file path: {}", &file_path.to_string_lossy() ) }); if is_glob(&file_name.to_string_lossy()) { return Err(ShellError::GenericError { error: format!( "No matches found for glob {}", file_name.to_string_lossy() ), msg: "No matches found for glob".into(), span: Some(file_glob.span), help: Some(format!( "Use quotes if you want to create a file named {}", file_name.to_string_lossy() )), inner: vec![], }); } input_files.push(InputFile::Path(file_path)); continue; } input_files.extend(expanded_globs.filter_map(Result::ok).map(InputFile::Path)); } } if let Err(err) = uu_touch::touch( &input_files, &Options { no_create, no_deref, source, date: date_str, change_times, strict: true, }, ) { let nu_err = match err { TouchError::TouchFileError { path, index, error } => ShellError::GenericError { error: format!("Could not touch {}", path.display()), msg: translate!(&error.to_string()), span: Some(file_globs[index].span), help: None, inner: Vec::new(), }, TouchError::InvalidDateFormat(date) => ShellError::IncorrectValue { msg: format!("Invalid date: {date}"), val_span: date_span.expect("touch should've been given a date"), call_span: call.head, }, TouchError::ReferenceFileInaccessible(reference_path, io_err) => { let span = reference_span.expect("touch should've been given a reference file"); ShellError::Io(IoError::new_with_additional_context( io_err, span, reference_path, "failed to read metadata", )) } _ => ShellError::GenericError { error: format!("{err}"), msg: translate!(&err.to_string()), span: Some(call.head), help: None, inner: Vec::new(), }, }; return Err(nu_err); } Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Creates \"fixture.json\"", example: "touch fixture.json", result: None, }, Example { description: "Creates files a, b and c", example: "touch a b c", result: None, }, Example { description: r#"Changes the last modified time of "fixture.json" to today's date"#, example: "touch -m fixture.json", result: None, }, Example { description: r#"Changes the last modified and accessed time of all files with the .json extension to today's date"#, example: "touch *.json", result: None, }, Example { description: "Changes the last accessed and modified times of files a, b and c to the current time but yesterday", example: r#"touch -d "yesterday" a b c"#, result: None, }, Example { description: r#"Changes the last modified time of files d and e to "fixture.json"'s last modified time"#, example: r#"touch -m -r fixture.json d e"#, result: None, }, Example { description: r#"Changes the last accessed time of "fixture.json" to a datetime"#, example: r#"touch -a -t 2019-08-24T12:30:30 fixture.json"#, result: None, }, Example { description: r#"Change the last accessed and modified times of stdout"#, example: r#"touch -"#, result: None, }, Example { description: r#"Changes the last accessed and modified times of file a to 1 month before "fixture.json"'s last modified time"#, example: r#"touch -r fixture.json -d "-1 month" a"#, 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/filesystem/cd.rs
crates/nu-command/src/filesystem/cd.rs
use std::path::PathBuf; use nu_engine::command_prelude::*; use nu_protocol::shell_error::{self, io::IoError}; use nu_utils::filesystem::{PermissionResult, have_permission}; #[derive(Clone)] pub struct Cd; impl Command for Cd { fn name(&self) -> &str { "cd" } fn description(&self) -> &str { "Change directory." } fn search_terms(&self) -> Vec<&str> { vec!["change", "directory", "dir", "folder", "switch"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("cd") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .switch("physical", "use the physical directory structure; resolve symbolic links before processing instances of ..", Some('P')) .optional("path", SyntaxShape::Directory, "The path to change to.") .allow_variants_without_examples(true) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let physical = call.has_flag(engine_state, stack, "physical")?; let path_val: Option<Spanned<String>> = call.opt(engine_state, stack, 0)?; // If getting PWD failed, default to the home directory. The user can // use `cd` to reset PWD to a good state. let cwd = engine_state .cwd(Some(stack)) .ok() .or_else(nu_path::home_dir) .map(|path| path.into_std_path_buf()) .unwrap_or_default(); let path_val = { if let Some(path) = path_val { Some(Spanned { item: nu_utils::strip_ansi_string_unlikely(path.item), span: path.span, }) } else { path_val } }; let path = match path_val { Some(v) => { if v.item == "-" { if let Some(oldpwd) = stack.get_env_var(engine_state, "OLDPWD") { oldpwd.to_path()? } else { cwd } } else { // Trim whitespace from the end of path. let path_no_whitespace = &v.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d')); // If `--physical` is specified, canonicalize the path; otherwise expand the path. if physical { if let Ok(path) = nu_path::canonicalize_with(path_no_whitespace, &cwd) { if !path.is_dir() { return Err(shell_error::io::IoError::new( shell_error::io::ErrorKind::from_std( std::io::ErrorKind::NotADirectory, ), v.span, None, ) .into()); }; path } else { return Err(shell_error::io::IoError::new( ErrorKind::DirectoryNotFound, v.span, PathBuf::from(path_no_whitespace), ) .into()); } } else { let path = nu_path::expand_path_with(path_no_whitespace, &cwd, true); if !path.exists() { return Err(shell_error::io::IoError::new( ErrorKind::DirectoryNotFound, v.span, PathBuf::from(path_no_whitespace), ) .into()); }; if !path.is_dir() { return Err(shell_error::io::IoError::new( shell_error::io::ErrorKind::from_std( std::io::ErrorKind::NotADirectory, ), v.span, path, ) .into()); }; path } } } None => nu_path::expand_tilde("~"), }; // Set OLDPWD. // We're using `Stack::get_env_var()` instead of `EngineState::cwd()` to avoid a conversion roundtrip. if let Some(oldpwd) = stack.get_env_var(engine_state, "PWD") { stack.add_env_var("OLDPWD".into(), oldpwd.clone()) } match have_permission(&path) { //FIXME: this only changes the current scope, but instead this environment variable //should probably be a block that loads the information from the state in the overlay PermissionResult::PermissionOk => { stack.set_cwd(path)?; Ok(PipelineData::empty()) } PermissionResult::PermissionDenied => Err(IoError::new( shell_error::io::ErrorKind::from_std(std::io::ErrorKind::PermissionDenied), call.head, path, ) .into()), } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Change to your home directory", example: r#"cd ~"#, result: None, }, Example { description: r#"Change to the previous working directory (same as "cd $env.OLDPWD")"#, example: r#"cd -"#, result: None, }, Example { description: "Changing directory with a custom command requires 'def --env'", example: r#"def --env gohome [] { cd ~ }"#, result: None, }, Example { description: "Move two directories up in the tree (the parent directory's parent). Additional dots can be added for additional levels.", example: r#"cd ..."#, result: None, }, Example { description: "The cd command itself is often optional. Simply entering a path to a directory will cd to it.", example: r#"/home"#, 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/filesystem/rm.rs
crates/nu-command/src/filesystem/rm.rs
use super::util::try_interaction; #[allow(deprecated)] use nu_engine::{command_prelude::*, env::current_dir}; use nu_glob::MatchOptions; use nu_path::expand_path_with; use nu_protocol::{ NuGlob, report_shell_error, shell_error::{self, io::IoError}, }; #[cfg(unix)] use std::os::unix::prelude::FileTypeExt; use std::{collections::HashMap, io::Error, path::PathBuf}; const TRASH_SUPPORTED: bool = cfg!(all( feature = "trash-support", not(any(target_os = "android", target_os = "ios")) )); #[derive(Clone)] pub struct Rm; impl Command for Rm { fn name(&self) -> &str { "rm" } fn description(&self) -> &str { "Remove files and directories." } fn search_terms(&self) -> Vec<&str> { vec!["delete", "remove"] } fn signature(&self) -> Signature { Signature::build("rm") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .rest("paths", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]), "The file paths(s) to remove.") .switch( "trash", "move to the platform's trash instead of permanently deleting. not used on android and ios", Some('t'), ) .switch( "permanent", "delete permanently, ignoring the 'always_trash' config option. always enabled on android and ios", Some('p'), ) .switch("recursive", "delete subdirectories recursively", Some('r')) .switch("force", "suppress error when no file", Some('f')) .switch("verbose", "print names of deleted files", Some('v')) .switch("interactive", "ask user to confirm action", Some('i')) .switch( "interactive-once", "ask user to confirm action only once", Some('I'), ) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { rm(engine_state, stack, call) } fn examples(&self) -> Vec<Example<'_>> { let mut examples = vec![Example { description: "Delete, or move a file to the trash (based on the 'always_trash' config option)", example: "rm file.txt", result: None, }]; if TRASH_SUPPORTED { examples.append(&mut vec![ Example { description: "Move a file to the trash", example: "rm --trash file.txt", result: None, }, Example { description: "Delete a file permanently, even if the 'always_trash' config option is true", example: "rm --permanent file.txt", result: None, }, ]); } examples.push(Example { description: "Delete a file, ignoring 'file not found' errors", example: "rm --force file.txt", result: None, }); examples.push(Example { description: "Delete all 0KB files in the current directory", example: "ls | where size == 0KB and type == file | each { rm $in.name } | null", result: None, }); examples } } fn rm( engine_state: &EngineState, stack: &mut Stack, call: &Call, ) -> Result<PipelineData, ShellError> { let trash = call.has_flag(engine_state, stack, "trash")?; let permanent = call.has_flag(engine_state, stack, "permanent")?; let recursive = call.has_flag(engine_state, stack, "recursive")?; let force = call.has_flag(engine_state, stack, "force")?; let verbose = call.has_flag(engine_state, stack, "verbose")?; let interactive = call.has_flag(engine_state, stack, "interactive")?; let interactive_once = call.has_flag(engine_state, stack, "interactive-once")? && !interactive; let mut paths = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; if paths.is_empty() { return Err(ShellError::MissingParameter { param_name: "requires file paths".to_string(), span: call.head, }); } let mut unique_argument_check = None; #[allow(deprecated)] let currentdir_path = current_dir(engine_state, stack)?; let home: Option<String> = nu_path::home_dir().map(|path| { { if path.exists() { nu_path::canonicalize_with(&path, &currentdir_path).unwrap_or(path.into()) } else { path.into() } } .to_string_lossy() .into() }); for (idx, path) in paths.clone().into_iter().enumerate() { if let Some(ref home) = home && expand_path_with(path.item.as_ref(), &currentdir_path, path.item.is_expand()) .to_string_lossy() .as_ref() == home.as_str() { unique_argument_check = Some(path.span); } let corrected_path = Spanned { item: match path.item { NuGlob::DoNotExpand(s) => { NuGlob::DoNotExpand(nu_utils::strip_ansi_string_unlikely(s)) } NuGlob::Expand(s) => NuGlob::Expand(nu_utils::strip_ansi_string_unlikely(s)), }, span: path.span, }; let _ = std::mem::replace(&mut paths[idx], corrected_path); } let span = call.head; let rm_always_trash = stack.get_config(engine_state).rm.always_trash; if !TRASH_SUPPORTED { if rm_always_trash { return Err(ShellError::GenericError { error: "Cannot execute `rm`; the current configuration specifies \ `always_trash = true`, but the current nu executable was not \ built with feature `trash_support`." .into(), msg: "trash required to be true but not supported".into(), span: Some(span), help: None, inner: vec![], }); } else if trash { return Err(ShellError::GenericError{ error: "Cannot execute `rm` with option `--trash`; feature `trash-support` not enabled or on an unsupported platform" .into(), msg: "this option is only available if nu is built with the `trash-support` feature and the platform supports trash" .into(), span: Some(span), help: None, inner: vec![], }); } } if paths.is_empty() { return Err(ShellError::GenericError { error: "rm requires target paths".into(), msg: "needs parameter".into(), span: Some(span), help: None, inner: vec![], }); } if unique_argument_check.is_some() && !(interactive_once || interactive) { return Err(ShellError::GenericError { error: "You are trying to remove your home dir".into(), msg: "If you really want to remove your home dir, please use -I or -i".into(), span: unique_argument_check, help: None, inner: vec![], }); } let targets_span = Span::new( paths .iter() .map(|x| x.span.start) .min() .expect("targets were empty"), paths .iter() .map(|x| x.span.end) .max() .expect("targets were empty"), ); let (mut target_exists, mut empty_span) = (false, call.head); let mut all_targets: HashMap<PathBuf, Span> = HashMap::new(); for target in paths { let path = expand_path_with( target.item.as_ref(), &currentdir_path, target.item.is_expand(), ); if currentdir_path.to_string_lossy() == path.to_string_lossy() || currentdir_path.starts_with(format!("{}{}", target.item, std::path::MAIN_SEPARATOR)) { return Err(ShellError::GenericError { error: "Cannot remove any parent directory".into(), msg: "cannot remove any parent directory".into(), span: Some(target.span), help: None, inner: vec![], }); } match nu_engine::glob_from( &target, &currentdir_path, call.head, Some(MatchOptions { require_literal_leading_dot: true, ..Default::default() }), engine_state.signals().clone(), ) { Ok(files) => { for file in files.1 { match file { Ok(f) => { if !target_exists { target_exists = true; } // It is not appropriate to try and remove the // current directory or its parent when using // glob patterns. let name = f.display().to_string(); if name.ends_with("/.") || name.ends_with("/..") { continue; } all_targets .entry(nu_path::expand_path_with( f, &currentdir_path, target.item.is_expand(), )) .or_insert_with(|| target.span); } Err(e) => { return Err(ShellError::GenericError { error: format!("Could not remove {:}", path.to_string_lossy()), msg: e.to_string(), span: Some(target.span), help: None, inner: vec![], }); } } } // Target doesn't exists if !target_exists && empty_span.eq(&call.head) { empty_span = target.span; } } Err(e) => { // glob_from may canonicalize path and return an error when a directory is not found // nushell should suppress the error if `--force` is used. if !(force && matches!( e, ShellError::Io(IoError { kind: shell_error::io::ErrorKind::Std(std::io::ErrorKind::NotFound, ..), .. }) )) { return Err(e); } } }; } if all_targets.is_empty() && !force { return Err(ShellError::GenericError { error: "File(s) not found".into(), msg: "File(s) not found".into(), span: Some(targets_span), help: None, inner: vec![], }); } if interactive_once { let (interaction, confirmed) = try_interaction( interactive_once, format!("rm: remove {} files? ", all_targets.len()), ); if let Err(e) = interaction { return Err(ShellError::GenericError { error: format!("Error during interaction: {e:}"), msg: "could not move".into(), span: None, help: None, inner: vec![], }); } else if !confirmed { return Ok(PipelineData::empty()); } } let iter = all_targets.into_iter().map(move |(f, span)| { let is_empty = || match f.read_dir() { Ok(mut p) => p.next().is_none(), Err(_) => false, }; if let Ok(metadata) = f.symlink_metadata() { #[cfg(unix)] let is_socket = metadata.file_type().is_socket(); #[cfg(unix)] let is_fifo = metadata.file_type().is_fifo(); #[cfg(not(unix))] let is_socket = false; #[cfg(not(unix))] let is_fifo = false; if metadata.is_file() || metadata.file_type().is_symlink() || recursive || is_socket || is_fifo || is_empty() { let (interaction, confirmed) = try_interaction( interactive, format!("rm: remove '{}'? ", f.to_string_lossy()), ); let result = if let Err(e) = interaction { Err(Error::other(&*e.to_string())) } else if interactive && !confirmed { Ok(()) } else if TRASH_SUPPORTED && (trash || (rm_always_trash && !permanent)) { #[cfg(all( feature = "trash-support", not(any(target_os = "android", target_os = "ios")) ))] { trash::delete(&f).map_err(|e: trash::Error| { Error::other(format!("{e:?}\nTry '--permanent' flag")) }) } // Should not be reachable since we error earlier if // these options are given on an unsupported platform #[cfg(any( not(feature = "trash-support"), target_os = "android", target_os = "ios" ))] { unreachable!() } } else if metadata.is_symlink() { // In Windows, symlink pointing to a directory can be removed using // std::fs::remove_dir instead of std::fs::remove_file. #[cfg(windows)] { f.metadata().and_then(|metadata| { if metadata.is_dir() { std::fs::remove_dir(&f) } else { std::fs::remove_file(&f) } }) } #[cfg(not(windows))] std::fs::remove_file(&f) } else if metadata.is_file() || is_socket || is_fifo { std::fs::remove_file(&f) } else { std::fs::remove_dir_all(&f) }; if let Err(e) = result { let original_error = e.to_string(); Err(ShellError::Io(IoError::new_with_additional_context( e, span, f, original_error, ))) } else if verbose { let msg = if interactive && !confirmed { "not deleted" } else { "deleted" }; Ok(Some(format!("{} {:}", msg, f.to_string_lossy()))) } else { Ok(None) } } else { let error = format!("Cannot remove {:}. try --recursive", f.to_string_lossy()); Err(ShellError::GenericError { error, msg: "cannot remove non-empty directory".into(), span: Some(span), help: None, inner: vec![], }) } } else { let error = format!("no such file or directory: {:}", f.to_string_lossy()); Err(ShellError::GenericError { error, msg: "no such file or directory".into(), span: Some(span), help: None, inner: vec![], }) } }); let mut cmd_result = Ok(PipelineData::empty()); for result in iter { engine_state.signals().check(&call.head)?; match result { Ok(None) => {} Ok(Some(msg)) => eprintln!("{msg}"), Err(err) => { if !(force && matches!( err, ShellError::Io(IoError { kind: shell_error::io::ErrorKind::Std(std::io::ErrorKind::NotFound, ..), .. }) )) { if cmd_result.is_ok() { cmd_result = Err(err); } else { report_shell_error(Some(stack), engine_state, &err) } } } } } cmd_result }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/ucp.rs
crates/nu-command/src/filesystem/ucp.rs
#[allow(deprecated)] use nu_engine::{command_prelude::*, current_dir}; use nu_glob::MatchOptions; use nu_protocol::{ NuGlob, shell_error::{self, io::IoError}, }; use std::path::PathBuf; use uu_cp::{BackupMode, CopyMode, CpError, UpdateMode}; use uucore::{localized_help_template, translate}; // TODO: related to uucore::error::set_exit_code(EXIT_ERR) // const EXIT_ERR: i32 = 1; #[cfg(not(target_os = "windows"))] const PATH_SEPARATOR: &str = "/"; #[cfg(target_os = "windows")] const PATH_SEPARATOR: &str = "\\"; #[derive(Clone)] pub struct UCp; impl Command for UCp { fn name(&self) -> &str { "cp" } fn description(&self) -> &str { "Copy files using uutils/coreutils cp." } fn search_terms(&self) -> Vec<&str> { vec!["copy", "file", "files", "coreutils"] } fn signature(&self) -> Signature { Signature::build("cp") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .switch("recursive", "copy directories recursively", Some('r')) .switch("verbose", "explicitly state what is being done", Some('v')) .switch( "force", "if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used). currently not implemented for windows", Some('f'), ) .switch("interactive", "ask before overwriting files", Some('i')) .switch( "update", "copy only when the SOURCE file is newer than the destination file or when the destination file is missing", Some('u') ) .switch("progress", "display a progress bar", Some('p')) .switch("no-clobber", "do not overwrite an existing file", Some('n')) .named( "preserve", SyntaxShape::List(Box::new(SyntaxShape::String)), "preserve only the specified attributes (empty list means no attributes preserved) if not specified only mode is preserved possible values: mode, ownership (unix only), timestamps, context, link, links, xattr", None ) .switch("debug", "explain how a file is copied. Implies -v", None) .switch("all", "move hidden files if '*' is provided", Some('a')) .rest("paths", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]), "Copy SRC file/s to DEST.") .allow_variants_without_examples(true) .category(Category::FileSystem) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Copy myfile to dir_b", example: "cp myfile dir_b", result: None, }, Example { description: "Recursively copy dir_a to dir_b", example: "cp -r dir_a dir_b", result: None, }, Example { description: "Recursively copy dir_a to dir_b, and print the feedbacks", example: "cp -r -v dir_a dir_b", result: None, }, Example { description: "Move many files into a directory", example: "cp *.txt dir_a", result: None, }, Example { description: "Copy only if source file is newer than target file", example: "cp -u myfile newfile", result: None, }, Example { description: "Copy file preserving mode and timestamps attributes", example: "cp --preserve [ mode timestamps ] myfile newfile", result: None, }, Example { description: "Copy file erasing all attributes", example: "cp --preserve [] myfile newfile", result: None, }, Example { description: "Copy file to a directory three levels above its current location", example: "cp myfile ....", result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // setup the uutils error translation let _ = localized_help_template("cp"); let interactive = call.has_flag(engine_state, stack, "interactive")?; let (update, copy_mode) = if call.has_flag(engine_state, stack, "update")? { (UpdateMode::IfOlder, CopyMode::Update) } else { (UpdateMode::All, CopyMode::Copy) }; let force = call.has_flag(engine_state, stack, "force")?; let no_clobber = call.has_flag(engine_state, stack, "no-clobber")?; let progress = call.has_flag(engine_state, stack, "progress")?; let recursive = call.has_flag(engine_state, stack, "recursive")?; let verbose = call.has_flag(engine_state, stack, "verbose")?; let preserve: Option<Value> = call.get_flag(engine_state, stack, "preserve")?; let all = call.has_flag(engine_state, stack, "all")?; let debug = call.has_flag(engine_state, stack, "debug")?; let overwrite = if no_clobber { uu_cp::OverwriteMode::NoClobber } else if interactive { if force { uu_cp::OverwriteMode::Interactive(uu_cp::ClobberMode::Force) } else { uu_cp::OverwriteMode::Interactive(uu_cp::ClobberMode::Standard) } } else if force { uu_cp::OverwriteMode::Clobber(uu_cp::ClobberMode::Force) } else { uu_cp::OverwriteMode::Clobber(uu_cp::ClobberMode::Standard) }; #[cfg(any(target_os = "linux", target_os = "android", target_os = "macos"))] let reflink_mode = uu_cp::ReflinkMode::Auto; #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "macos")))] let reflink_mode = uu_cp::ReflinkMode::Never; let mut paths = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; if paths.is_empty() { return Err(ShellError::GenericError { error: "Missing file operand".into(), msg: "Missing file operand".into(), span: Some(call.head), help: Some("Please provide source and destination paths".into()), inner: vec![], }); } if paths.len() == 1 { return Err(ShellError::GenericError { error: "Missing destination path".into(), msg: format!( "Missing destination path operand after {}", paths[0].item.as_ref() ), span: Some(paths[0].span), help: None, inner: vec![], }); } let target = paths.pop().expect("Should not be reached?"); let target_path = PathBuf::from(&nu_utils::strip_ansi_string_unlikely( target.item.to_string(), )); #[allow(deprecated)] let cwd = current_dir(engine_state, stack)?; let target_path = nu_path::expand_path_with(target_path, &cwd, target.item.is_expand()); if target.item.as_ref().ends_with(PATH_SEPARATOR) && !target_path.is_dir() { return Err(ShellError::GenericError { error: "is not a directory".into(), msg: "is not a directory".into(), span: Some(target.span), help: None, inner: vec![], }); }; // paths now contains the sources let mut sources: Vec<(Vec<PathBuf>, bool)> = Vec::new(); let glob_options = if all { None } else { let glob_options = MatchOptions { require_literal_leading_dot: true, ..Default::default() }; Some(glob_options) }; for mut p in paths { p.item = p.item.strip_ansi_string_unlikely(); let exp_files: Vec<Result<PathBuf, ShellError>> = nu_engine::glob_from( &p, &cwd, call.head, glob_options, engine_state.signals().clone(), ) .map(|f| f.1)? .collect(); if exp_files.is_empty() { return Err(ShellError::Io(IoError::new( shell_error::io::ErrorKind::FileNotFound, p.span, PathBuf::from(p.item.to_string()), ))); }; let mut app_vals: Vec<PathBuf> = Vec::new(); for v in exp_files { match v { Ok(path) => { if !recursive && path.is_dir() { return Err(ShellError::GenericError { error: "could_not_copy_directory".into(), msg: "resolves to a directory (not copied)".into(), span: Some(p.span), help: Some( "Directories must be copied using \"--recursive\"".into(), ), inner: vec![], }); }; app_vals.push(path) } Err(e) => return Err(e), } } sources.push((app_vals, p.item.is_expand())); } // Make sure to send absolute paths to avoid uu_cp looking for cwd in std::env which is not // supported in Nushell for (sources, need_expand_tilde) in sources.iter_mut() { for src in sources.iter_mut() { if !src.is_absolute() { *src = nu_path::expand_path_with(&*src, &cwd, *need_expand_tilde); } } } let sources: Vec<PathBuf> = sources.into_iter().flat_map(|x| x.0).collect(); let attributes = make_attributes(preserve)?; let options = uu_cp::Options { overwrite, reflink_mode, recursive, debug, attributes, verbose: verbose || debug, dereference: !recursive, progress_bar: progress, attributes_only: false, backup: BackupMode::None, copy_contents: false, cli_dereference: false, copy_mode, no_target_dir: false, one_file_system: false, parents: false, sparse_mode: uu_cp::SparseMode::Auto, strip_trailing_slashes: false, backup_suffix: String::from("~"), target_dir: None, update, set_selinux_context: false, context: None, }; if let Err(error) = uu_cp::copy(&sources, &target_path, &options) { match error { // code should still be EXIT_ERR as does GNU cp CpError::NotAllFilesCopied => {} _ => { eprintln!("here"); return Err(ShellError::GenericError { error: format!("{error}"), msg: translate!(&error.to_string()), span: None, help: None, inner: vec![], }); } }; // TODO: What should we do in place of set_exit_code? // uucore::error::set_exit_code(EXIT_ERR); } Ok(PipelineData::empty()) } } const ATTR_UNSET: uu_cp::Preserve = uu_cp::Preserve::No { explicit: true }; const ATTR_SET: uu_cp::Preserve = uu_cp::Preserve::Yes { required: true }; fn make_attributes(preserve: Option<Value>) -> Result<uu_cp::Attributes, ShellError> { if let Some(preserve) = preserve { let mut attributes = uu_cp::Attributes { #[cfg(any( target_os = "linux", target_os = "freebsd", target_os = "android", target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] ownership: ATTR_UNSET, mode: ATTR_UNSET, timestamps: ATTR_UNSET, context: ATTR_UNSET, links: ATTR_UNSET, xattr: ATTR_UNSET, }; parse_and_set_attributes_list(&preserve, &mut attributes)?; Ok(attributes) } else { // By default preseerve only mode Ok(uu_cp::Attributes { mode: ATTR_SET, #[cfg(any( target_os = "linux", target_os = "freebsd", target_os = "android", target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] ownership: ATTR_UNSET, timestamps: ATTR_UNSET, context: ATTR_UNSET, links: ATTR_UNSET, xattr: ATTR_UNSET, }) } } fn parse_and_set_attributes_list( list: &Value, attribute: &mut uu_cp::Attributes, ) -> Result<(), ShellError> { match list { Value::List { vals, .. } => { for val in vals { parse_and_set_attribute(val, attribute)?; } Ok(()) } _ => Err(ShellError::IncompatibleParametersSingle { msg: "--preserve flag expects a list of strings".into(), span: list.span(), }), } } fn parse_and_set_attribute( value: &Value, attribute: &mut uu_cp::Attributes, ) -> Result<(), ShellError> { match value { Value::String { val, .. } => { let attribute = match val.as_str() { "mode" => &mut attribute.mode, #[cfg(any( target_os = "linux", target_os = "freebsd", target_os = "android", target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] "ownership" => &mut attribute.ownership, "timestamps" => &mut attribute.timestamps, "context" => &mut attribute.context, "link" | "links" => &mut attribute.links, "xattr" => &mut attribute.xattr, _ => { return Err(ShellError::IncompatibleParametersSingle { msg: format!("--preserve flag got an unexpected attribute \"{val}\""), span: value.span(), }); } }; *attribute = ATTR_SET; Ok(()) } _ => Err(ShellError::IncompatibleParametersSingle { msg: "--preserve flag expects a list of strings".into(), span: value.span(), }), } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(UCp {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/glob.rs
crates/nu-command/src/filesystem/glob.rs
use nu_engine::command_prelude::*; use nu_protocol::{ListStream, Signals}; use wax::{Glob as WaxGlob, WalkBehavior, WalkEntry}; #[derive(Clone)] pub struct Glob; impl Command for Glob { fn name(&self) -> &str { "glob" } fn signature(&self) -> Signature { Signature::build("glob") .input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::String)))]) .required("glob", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::GlobPattern]), "The glob expression.") .named( "depth", SyntaxShape::Int, "directory depth to search", Some('d'), ) .switch( "no-dir", "Whether to filter out directories from the returned paths", Some('D'), ) .switch( "no-file", "Whether to filter out files from the returned paths", Some('F'), ) .switch( "no-symlink", "Whether to filter out symlinks from the returned paths", Some('S'), ) .switch( "follow-symlinks", "Whether to follow symbolic links to their targets", Some('l'), ) .named( "exclude", SyntaxShape::List(Box::new(SyntaxShape::String)), "Patterns to exclude from the search: `glob` will not walk the inside of directories matching the excluded patterns.", Some('e'), ) .category(Category::FileSystem) } fn description(&self) -> &str { "Creates a list of files and/or folders based on the glob pattern provided." } fn search_terms(&self) -> Vec<&str> { vec!["pattern", "files", "folders", "list", "ls"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Search for *.rs files", example: "glob *.rs", result: None, }, Example { description: "Search for *.rs and *.toml files recursively up to 2 folders deep", example: "glob **/*.{rs,toml} --depth 2", result: None, }, Example { description: "Search for files and folders that begin with uppercase C or lowercase c", example: r#"glob "[Cc]*""#, result: None, }, Example { description: "Search for files and folders like abc or xyz substituting a character for ?", example: r#"glob "{a?c,x?z}""#, result: None, }, Example { description: "A case-insensitive search for files and folders that begin with c", example: r#"glob "(?i)c*""#, result: None, }, Example { description: "Search for files or folders that do not begin with c, C, b, M, or s", example: r#"glob "[!cCbMs]*""#, result: None, }, Example { description: "Search for files or folders with 3 a's in a row in the name", example: "glob <a*:3>", result: None, }, Example { description: "Search for files or folders with only a, b, c, or d in the file name between 1 and 10 times", example: "glob <[a-d]:1,10>", result: None, }, Example { description: "Search for folders that begin with an uppercase ASCII letter, ignoring files and symlinks", example: r#"glob "[A-Z]*" --no-file --no-symlink"#, result: None, }, Example { description: "Search for files named tsconfig.json that are not in node_modules directories", example: r#"glob **/tsconfig.json --exclude [**/node_modules/**]"#, result: None, }, Example { description: "Search for all files that are not in the target nor .git directories", example: r#"glob **/* --exclude [**/target/** **/.git/** */]"#, result: None, }, Example { description: "Search for files following symbolic links to their targets", example: r#"glob "**/*.txt" --follow-symlinks"#, result: None, }, ] } fn extra_description(&self) -> &str { r#"For more glob pattern help, please refer to https://docs.rs/crate/wax/latest"# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; let glob_pattern_input: Value = call.req(engine_state, stack, 0)?; let glob_span = glob_pattern_input.span(); let depth = call.get_flag(engine_state, stack, "depth")?; let no_dirs = call.has_flag(engine_state, stack, "no-dir")?; let no_files = call.has_flag(engine_state, stack, "no-file")?; let no_symlinks = call.has_flag(engine_state, stack, "no-symlink")?; let follow_symlinks = call.has_flag(engine_state, stack, "follow-symlinks")?; let paths_to_exclude: Option<Value> = call.get_flag(engine_state, stack, "exclude")?; let (not_patterns, not_pattern_span): (Vec<String>, Span) = match paths_to_exclude { None => (vec![], span), Some(f) => { let pat_span = f.span(); match f { Value::List { vals: pats, .. } => { let p = convert_patterns(pats.as_slice())?; (p, pat_span) } _ => (vec![], span), } } }; let glob_pattern = match glob_pattern_input { Value::String { val, .. } | Value::Glob { val, .. } => val, _ => return Err(ShellError::IncorrectValue { msg: "Incorrect glob pattern supplied to glob. Please use string or glob only." .to_string(), val_span: call.head, call_span: glob_span, }), }; // paths starting with drive letters must be escaped on Windows #[cfg(windows)] let glob_pattern = patch_windows_glob_pattern(glob_pattern, glob_span)?; if glob_pattern.is_empty() { return Err(ShellError::GenericError { error: "glob pattern must not be empty".into(), msg: "glob pattern is empty".into(), span: Some(glob_span), help: Some("add characters to the glob pattern".into()), inner: vec![], }); } // below we have to check / instead of MAIN_SEPARATOR because glob uses / as separator // using a glob like **\*.rs should fail because it's not a valid glob pattern let folder_depth = if let Some(depth) = depth { depth } else if glob_pattern.contains("**") { usize::MAX } else if glob_pattern.contains('/') { glob_pattern.split('/').count() + 1 } else { 1 }; let (prefix, glob) = match WaxGlob::new(&glob_pattern) { Ok(p) => p.partition(), Err(e) => { return Err(ShellError::GenericError { error: "error with glob pattern".into(), msg: format!("{e}"), span: Some(glob_span), help: None, inner: vec![], }); } }; let path = engine_state.cwd_as_string(Some(stack))?; let path = match nu_path::canonicalize_with(prefix, path) { Ok(path) => path, Err(e) if e.to_string().contains("os error 2") => // path we're trying to glob doesn't exist, { std::path::PathBuf::new() // user should get empty list not an error } Err(e) => { return Err(ShellError::GenericError { error: "error in canonicalize".into(), msg: format!("{e}"), span: Some(glob_span), help: None, inner: vec![], }); } }; let link_behavior = match follow_symlinks { true => wax::LinkBehavior::ReadTarget, false => wax::LinkBehavior::ReadFile, }; let result = if !not_patterns.is_empty() { let np: Vec<&str> = not_patterns.iter().map(|s| s as &str).collect(); let glob_results = glob .walk_with_behavior( path, WalkBehavior { depth: folder_depth, link: link_behavior, }, ) .into_owned() .not(np) .map_err(|err| ShellError::GenericError { error: "error with glob's not pattern".into(), msg: format!("{err}"), span: Some(not_pattern_span), help: None, inner: vec![], })? .flatten(); glob_to_value( engine_state.signals(), glob_results, no_dirs, no_files, no_symlinks, span, ) } else { let glob_results = glob .walk_with_behavior( path, WalkBehavior { depth: folder_depth, link: link_behavior, }, ) .into_owned() .flatten(); glob_to_value( engine_state.signals(), glob_results, no_dirs, no_files, no_symlinks, span, ) }; Ok(result.into_pipeline_data(span, engine_state.signals().clone())) } } #[cfg(windows)] fn patch_windows_glob_pattern(glob_pattern: String, glob_span: Span) -> Result<String, ShellError> { let mut chars = glob_pattern.chars(); match (chars.next(), chars.next(), chars.next()) { (Some(drive), Some(':'), Some('/' | '\\')) if drive.is_ascii_alphabetic() => { Ok(format!("{drive}\\:/{}", chars.as_str())) } (Some(drive), Some(':'), Some(_)) if drive.is_ascii_alphabetic() => { Err(ShellError::GenericError { error: "invalid Windows path format".into(), msg: "Windows paths with drive letters must include a path separator (/) after the colon".into(), span: Some(glob_span), help: Some("use format like 'C:/' instead of 'C:'".into()), inner: vec![], }) } _ => Ok(glob_pattern), } } fn convert_patterns(columns: &[Value]) -> Result<Vec<String>, ShellError> { let res = columns .iter() .map(|value| match &value { Value::String { val: s, .. } => Ok(s.clone()), _ => Err(ShellError::IncompatibleParametersSingle { msg: "Incorrect column format, Only string as column name".to_string(), span: value.span(), }), }) .collect::<Result<Vec<String>, _>>()?; Ok(res) } fn glob_to_value( signals: &Signals, glob_results: impl Iterator<Item = WalkEntry<'static>> + Send + 'static, no_dirs: bool, no_files: bool, no_symlinks: bool, span: Span, ) -> ListStream { let map_signals = signals.clone(); let result = glob_results.filter_map(move |entry| { if let Err(err) = map_signals.check(&span) { return Some(Value::error(err, span)); }; let file_type = entry.file_type(); if !(no_dirs && file_type.is_dir() || no_files && file_type.is_file() || no_symlinks && file_type.is_symlink()) { Some(Value::string( entry.into_path().to_string_lossy().to_string(), span, )) } else { None } }); ListStream::new(result, span, signals.clone()) } #[cfg(windows)] #[cfg(test)] mod windows_tests { use super::*; #[test] fn glob_pattern_with_drive_letter() { let pattern = "D:/*.mp4".to_string(); let result = patch_windows_glob_pattern(pattern, Span::test_data()).unwrap(); assert!(WaxGlob::new(&result).is_ok()); let pattern = "Z:/**/*.md".to_string(); let result = patch_windows_glob_pattern(pattern, Span::test_data()).unwrap(); assert!(WaxGlob::new(&result).is_ok()); let pattern = "C:/nested/**/escaped/path/<[_a-zA-Z\\-]>.md".to_string(); let result = patch_windows_glob_pattern(pattern, Span::test_data()).unwrap(); assert!(dbg!(WaxGlob::new(&result)).is_ok()); } #[test] fn glob_pattern_without_drive_letter() { let pattern = "/usr/bin/*.sh".to_string(); let result = patch_windows_glob_pattern(pattern.clone(), Span::test_data()).unwrap(); assert_eq!(result, pattern); assert!(WaxGlob::new(&result).is_ok()); let pattern = "a".to_string(); let result = patch_windows_glob_pattern(pattern.clone(), Span::test_data()).unwrap(); assert_eq!(result, pattern); assert!(WaxGlob::new(&result).is_ok()); } #[test] fn invalid_path_format() { let invalid = "C:lol".to_string(); let result = patch_windows_glob_pattern(invalid, Span::test_data()); assert!(result.is_err()); } #[test] fn unpatched_patterns() { let unpatched = "C:/Users/*.txt".to_string(); assert!(WaxGlob::new(&unpatched).is_err()); let patched = patch_windows_glob_pattern(unpatched, Span::test_data()).unwrap(); assert!(WaxGlob::new(&patched).is_ok()); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/umkdir.rs
crates/nu-command/src/filesystem/umkdir.rs
#[allow(deprecated)] use nu_engine::{command_prelude::*, current_dir}; use nu_protocol::NuGlob; use uu_mkdir::mkdir; #[cfg(not(windows))] use uucore::mode; use uucore::{localized_help_template, translate}; #[derive(Clone)] pub struct UMkdir; const IS_RECURSIVE: bool = true; const DEFAULT_MODE: u32 = 0o777; #[cfg(not(windows))] fn get_mode() -> u32 { !mode::get_umask() & DEFAULT_MODE } #[cfg(windows)] fn get_mode() -> u32 { DEFAULT_MODE } impl Command for UMkdir { fn name(&self) -> &str { "mkdir" } fn description(&self) -> &str { "Create directories, with intermediary directories if required using uutils/coreutils mkdir." } fn search_terms(&self) -> Vec<&str> { vec!["directory", "folder", "create", "make_dirs", "coreutils"] } fn signature(&self) -> Signature { Signature::build("mkdir") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .rest( "rest", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::Directory]), "The name(s) of the path(s) to create.", ) .switch( "verbose", "print a message for each created directory.", Some('v'), ) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // setup the uutils error translation let _ = localized_help_template("mkdir"); #[allow(deprecated)] let cwd = current_dir(engine_state, stack)?; let mut directories = call .rest::<Spanned<NuGlob>>(engine_state, stack, 0)? .into_iter() .map(|dir| nu_path::expand_path_with(dir.item.as_ref(), &cwd, dir.item.is_expand())) .peekable(); let is_verbose = call.has_flag(engine_state, stack, "verbose")?; if directories.peek().is_none() { return Err(ShellError::MissingParameter { param_name: "requires directory paths".to_string(), span: call.head, }); } let config = uu_mkdir::Config { recursive: IS_RECURSIVE, mode: get_mode(), verbose: is_verbose, set_selinux_context: false, context: None, }; let mut verbose_out = String::new(); for dir in directories { if let Err(error) = mkdir(&dir, &config) { return Err(ShellError::GenericError { error: format!("{error}"), msg: translate!(&error.to_string()), span: None, help: None, inner: vec![], }); } if is_verbose { verbose_out.push_str( format!( "{} ", &dir.as_path() .file_name() .unwrap_or_default() .to_string_lossy() ) .as_str(), ); } } if is_verbose { Ok(PipelineData::value( Value::string(verbose_out.trim(), call.head), None, )) } else { Ok(PipelineData::empty()) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Make a directory named foo", example: "mkdir foo", result: None, }, Example { description: "Make multiple directories and show the paths created", example: "mkdir -v foo/bar foo2", 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/filesystem/util.rs
crates/nu-command/src/filesystem/util.rs
use dialoguer::Input; use std::error::Error; pub fn try_interaction( interactive: bool, prompt: String, ) -> (Result<Option<bool>, Box<dyn Error>>, bool) { let interaction = if interactive { match get_interactive_confirmation(prompt) { Ok(i) => Ok(Some(i)), Err(e) => Err(e), } } else { Ok(None) }; let confirmed = match interaction { Ok(maybe_input) => maybe_input.unwrap_or(false), Err(_) => false, }; (interaction, confirmed) } fn get_interactive_confirmation(prompt: String) -> Result<bool, Box<dyn Error>> { let input = Input::new() .with_prompt(prompt) .validate_with(|c_input: &String| -> Result<(), String> { if c_input.len() == 1 && (c_input == "y" || c_input == "Y" || c_input == "n" || c_input == "N") { Ok(()) } else if c_input.len() > 1 { Err("Enter only one letter (Y/N)".to_string()) } else { Err("Input not valid".to_string()) } }) .default("Y/N".into()) .interact_text()?; if input == "y" || input == "Y" { Ok(true) } else { Ok(false) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/watch.rs
crates/nu-command/src/filesystem/watch.rs
use itertools::{Either, Itertools}; use notify_debouncer_full::{ DebouncedEvent, Debouncer, FileIdMap, new_debouncer, notify::{ self, EventKind, RecommendedWatcher, RecursiveMode, Watcher, event::{DataChange, ModifyKind, RenameMode}, }, }; use nu_engine::{ClosureEval, command_prelude::*}; use nu_protocol::{ DeprecationEntry, DeprecationType, ReportMode, Signals, engine::Closure, report_shell_error, shell_error::io::IoError, }; use std::{ borrow::Cow, path::{Path, PathBuf}, sync::mpsc::{Receiver, RecvTimeoutError, channel}, time::Duration, }; // durations chosen mostly arbitrarily const CHECK_CTRL_C_FREQUENCY: Duration = Duration::from_millis(100); const DEFAULT_WATCH_DEBOUNCE_DURATION: Duration = Duration::from_millis(100); #[derive(Clone)] pub struct Watch; impl Command for Watch { fn name(&self) -> &str { "watch" } fn description(&self) -> &str { "Watch for file changes and execute Nu code when they happen." } fn extra_description(&self) -> &str { "When run without a closure, `watch` returns a stream of events instead." } fn search_terms(&self) -> Vec<&str> { vec!["watcher", "reload", "filesystem"] } fn deprecation_info(&self) -> Vec<DeprecationEntry> { vec![DeprecationEntry { ty: DeprecationType::Flag("debounce-ms".into()), report_mode: ReportMode::FirstUse, since: Some("0.107.0".into()), expected_removal: Some("0.109.0".into()), help: Some("`--debounce-ms` will be removed in favour of `--debounce`".into()), }] } fn signature(&self) -> nu_protocol::Signature { Signature::build("watch") .input_output_types(vec![ (Type::Nothing, Type::Nothing), ( Type::Nothing, Type::Table(vec![ ("operation".into(), Type::String), ("path".into(), Type::String), ("new_path".into(), Type::String), ].into_boxed_slice()) ), ]) .required("path", SyntaxShape::Filepath, "The path to watch. Can be a file or directory.") .optional( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::String, SyntaxShape::String, SyntaxShape::String])), "Some Nu code to run whenever a file changes. The closure will be passed `operation`, `path`, and `new_path` (for renames only) arguments in that order.", ) .named( "debounce-ms", SyntaxShape::Int, "Debounce changes for this many milliseconds (default: 100). Adjust if you find that single writes are reported as multiple events (deprecated)", Some('d'), ) .named( "debounce", SyntaxShape::Duration, "Debounce changes for this duration (default: 100ms). Adjust if you find that single writes are reported as multiple events", None, ) .named( "glob", SyntaxShape::String, // SyntaxShape::GlobPattern gets interpreted relative to cwd, so use String instead "Only report changes for files that match this glob pattern (default: all files)", Some('g'), ) .named( "recursive", SyntaxShape::Boolean, "Watch all directories under `<path>` recursively. Will be ignored if `<path>` is a file (default: true)", Some('r'), ) .switch("quiet", "Hide the initial status message (default: false)", Some('q')) .switch("verbose", "Operate in verbose mode (default: false)", Some('v')) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let cwd = engine_state.cwd_as_string(Some(stack))?; let path_arg: Spanned<String> = call.req(engine_state, stack, 0)?; let path_no_whitespace = path_arg .item .trim_end_matches(|x| matches!(x, '\x09'..='\x0d')); let path = nu_path::canonicalize_with(path_no_whitespace, cwd).map_err(|err| { ShellError::Io(IoError::new( err, path_arg.span, PathBuf::from(path_no_whitespace), )) })?; let closure: Option<Closure> = call.opt(engine_state, stack, 1)?; let verbose = call.has_flag(engine_state, stack, "verbose")?; let quiet = call.has_flag(engine_state, stack, "quiet")?; let debounce_duration: Duration = resolve_duration_arguments( call.get_flag(engine_state, stack, "debounce-ms")?, call.get_flag(engine_state, stack, "debounce")?, )?; let glob_flag: Option<Spanned<String>> = call.get_flag(engine_state, stack, "glob")?; let glob_pattern = glob_flag .map(|glob| { let absolute_path = path.join(glob.item); if verbose { eprintln!("Absolute glob path: {absolute_path:?}"); } nu_glob::Pattern::new(&absolute_path.to_string_lossy()).map_err(|_| { ShellError::TypeMismatch { err_message: "Glob pattern is invalid".to_string(), span: glob.span, } }) }) .transpose()?; let recursive_flag: Option<Spanned<bool>> = call.get_flag(engine_state, stack, "recursive")?; let recursive_mode = match recursive_flag { Some(recursive) => { if recursive.item { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive } } None => RecursiveMode::Recursive, }; let (tx, rx) = channel(); let mut debouncer = new_debouncer(debounce_duration, None, tx).map_err(|err| ShellError::GenericError { error: "Failed to create watcher".to_string(), msg: err.to_string(), span: Some(call.head), help: None, inner: vec![], })?; if let Err(err) = debouncer.watcher().watch(&path, recursive_mode) { return Err(ShellError::GenericError { error: "Failed to create watcher".to_string(), msg: err.to_string(), span: Some(call.head), help: None, inner: vec![], }); } // need to cache to make sure that rename event works. debouncer.cache().add_root(&path, recursive_mode); if !quiet { eprintln!("Now watching files at {path:?}. Press ctrl+c to abort."); } let iter = WatchIterator::new(debouncer, rx, engine_state.signals().clone()); if let Some(closure) = closure { let mut closure = ClosureEval::new(engine_state, stack, closure); for events in iter { for event in events? { let matches_glob = match &glob_pattern { Some(glob) => glob.matches_path(&event.path), None => true, }; if verbose && glob_pattern.is_some() { eprintln!("Matches glob: {matches_glob}"); } if matches_glob { let result = closure .add_arg(event.operation.into_value(head)) .add_arg(event.path.to_string_lossy().into_value(head)) .add_arg( event .new_path .as_deref() .map(Path::to_string_lossy) .into_value(head), ) .run_with_input(PipelineData::empty()); match result { Ok(val) => val.print_table(engine_state, stack, false, false)?, Err(err) => report_shell_error(Some(stack), engine_state, &err), }; } } } Ok(PipelineData::empty()) } else { fn glob_filter(glob: Option<&nu_glob::Pattern>, path: &Path) -> bool { let Some(glob) = glob else { return true }; glob.matches_path(path) } let out = iter .flat_map(|e| match e { Ok(events) => Either::Right(events.into_iter().map(Ok)), Err(err) => Either::Left(std::iter::once(Err(err))), }) .filter_map(move |e| match e { Ok(ev) => glob_filter(glob_pattern.as_ref(), &ev.path) .then(|| WatchEventRecord::from(&ev).into_value(head)), Err(err) => Some(Value::error(err, head)), }) .into_pipeline_data(head, engine_state.signals().clone()); Ok(out) } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Run `cargo test` whenever a Rust file changes", example: r#"watch . --glob=**/*.rs {|| cargo test }"#, result: None, }, Example { description: "Watch all changes in the current directory", example: r#"watch . { |op, path, new_path| $"($op) ($path) ($new_path)"}"#, result: None, }, Example { description: "`watch` (when run without a closure) can also emit a stream of events it detects.", example: r#"watch /foo/bar | where operation == Create | first 5 | each {|e| $"New file!: ($e.path)" } | to text | save --append changes_in_bar.log"#, result: None, }, Example { description: "Print file changes with a debounce time of 5 minutes", example: r#"watch /foo/bar --debounce 5min { |op, path| $"Registered ($op) on ($path)" | print }"#, result: None, }, Example { description: "Note: if you are looking to run a command every N units of time, this can be accomplished with a loop and sleep", example: r#"loop { command; sleep duration }"#, result: None, }, ] } } fn resolve_duration_arguments( debounce_duration_flag_ms: Option<Spanned<i64>>, debounce_duration_flag: Option<Spanned<Duration>>, ) -> Result<Duration, ShellError> { match (debounce_duration_flag, debounce_duration_flag_ms) { (None, None) => Ok(DEFAULT_WATCH_DEBOUNCE_DURATION), (Some(l), Some(r)) => Err(ShellError::IncompatibleParameters { left_message: "Here".to_string(), left_span: l.span, right_message: "and here".to_string(), right_span: r.span, }), (None, Some(val)) => match u64::try_from(val.item) { Ok(v) => Ok(Duration::from_millis(v)), Err(_) => Err(ShellError::TypeMismatch { err_message: "Debounce duration is invalid".to_string(), span: val.span, }), }, (Some(v), None) => Ok(v.item), } } struct WatchEvent { operation: &'static str, path: PathBuf, new_path: Option<PathBuf>, } #[derive(IntoValue)] struct WatchEventRecord<'a> { operation: &'static str, path: Cow<'a, str>, new_path: Option<Cow<'a, str>>, } impl<'a> From<&'a WatchEvent> for WatchEventRecord<'a> { fn from(value: &'a WatchEvent) -> Self { Self { operation: value.operation, path: value.path.to_string_lossy(), new_path: value.new_path.as_deref().map(Path::to_string_lossy), } } } impl TryFrom<DebouncedEvent> for WatchEvent { type Error = (); fn try_from(mut ev: DebouncedEvent) -> Result<Self, Self::Error> { // TODO: Maybe we should handle all event kinds? match ev.event.kind { EventKind::Create(_) => ev.paths.pop().map(|p| WatchEvent { operation: "Create", path: p, new_path: None, }), EventKind::Remove(_) => ev.paths.pop().map(|p| WatchEvent { operation: "Remove", path: p, new_path: None, }), EventKind::Modify( ModifyKind::Data(DataChange::Content | DataChange::Any) | ModifyKind::Any, ) => ev.paths.pop().map(|p| WatchEvent { operation: "Write", path: p, new_path: None, }), EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => ev .paths .drain(..) .rev() .next_array() .map(|[from, to]| WatchEvent { operation: "Rename", path: from, new_path: Some(to), }), _ => None, } .ok_or(()) } } struct WatchIterator { /// Debouncer needs to be kept alive for `rx` to keep receiving events. _debouncer: Debouncer<RecommendedWatcher, FileIdMap>, rx: Option<Receiver<Result<Vec<DebouncedEvent>, Vec<notify::Error>>>>, signals: Signals, } impl WatchIterator { fn new( debouncer: Debouncer<RecommendedWatcher, FileIdMap>, rx: Receiver<Result<Vec<DebouncedEvent>, Vec<notify::Error>>>, signals: Signals, ) -> Self { Self { _debouncer: debouncer, rx: Some(rx), signals, } } } impl Iterator for WatchIterator { type Item = Result<Vec<WatchEvent>, ShellError>; fn next(&mut self) -> Option<Self::Item> { let rx = self.rx.as_ref()?; while !self.signals.interrupted() { let x = match rx.recv_timeout(CHECK_CTRL_C_FREQUENCY) { Ok(x) => x, Err(RecvTimeoutError::Timeout) => continue, Err(RecvTimeoutError::Disconnected) => { self.rx = None; return Some(Err(ShellError::GenericError { error: "Disconnected".to_string(), msg: "Unexpected disconnect from file watcher".into(), span: None, help: None, inner: vec![], })); } }; let Ok(events) = x else { self.rx = None; return Some(Err(ShellError::GenericError { error: "Receiving events failed".to_string(), msg: "Unexpected errors when receiving events".into(), span: None, help: None, inner: vec![], })); }; let watch_events = events .into_iter() .filter_map(|ev| WatchEvent::try_from(ev).ok()) .collect::<Vec<_>>(); return Some(Ok(watch_events)); } self.rx = None; None } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/umv.rs
crates/nu-command/src/filesystem/umv.rs
#[allow(deprecated)] use nu_engine::{command_prelude::*, current_dir}; use nu_glob::MatchOptions; use nu_path::expand_path_with; use nu_protocol::{ NuGlob, shell_error::{self, io::IoError}, }; use std::{ffi::OsString, path::PathBuf}; use uu_mv::{BackupMode, UpdateMode}; use uucore::{localized_help_template, translate}; #[derive(Clone)] pub struct UMv; impl Command for UMv { fn name(&self) -> &str { "mv" } fn description(&self) -> &str { "Move files or directories using uutils/coreutils mv." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Rename a file", example: "mv before.txt after.txt", result: None, }, Example { description: "Move a file into a directory", example: "mv test.txt my/subdirectory", result: None, }, Example { description: "Move only if source file is newer than target file", example: "mv -u new/test.txt old/", result: None, }, Example { description: "Move many files into a directory", example: "mv *.txt my/subdirectory", result: None, }, Example { description: r#"Move a file into the "my" directory two levels up in the directory tree"#, example: "mv test.txt .../my/", result: None, }, ] } fn search_terms(&self) -> Vec<&str> { vec!["move", "file", "files", "coreutils"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("mv") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .switch("force", "do not prompt before overwriting", Some('f')) .switch("verbose", "explain what is being done.", Some('v')) .switch("progress", "display a progress bar", Some('p')) .switch("interactive", "prompt before overwriting", Some('i')) .switch( "update", "move and overwrite only when the SOURCE file is newer than the destination file or when the destination file is missing", Some('u') ) .switch("no-clobber", "do not overwrite an existing file", Some('n')) .switch("all", "move hidden files if '*' is provided", Some('a')) .rest( "paths", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]), "Rename SRC to DST, or move SRC to DIR.", ) .allow_variants_without_examples(true) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // setup the uutils error translation let _ = localized_help_template("mv"); let interactive = call.has_flag(engine_state, stack, "interactive")?; let no_clobber = call.has_flag(engine_state, stack, "no-clobber")?; let progress = call.has_flag(engine_state, stack, "progress")?; let verbose = call.has_flag(engine_state, stack, "verbose")?; let all = call.has_flag(engine_state, stack, "all")?; let overwrite = if no_clobber { uu_mv::OverwriteMode::NoClobber } else if interactive { uu_mv::OverwriteMode::Interactive } else { uu_mv::OverwriteMode::Force }; let update = if call.has_flag(engine_state, stack, "update")? { UpdateMode::IfOlder } else { UpdateMode::All }; #[allow(deprecated)] let cwd = current_dir(engine_state, stack)?; let mut paths = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; if paths.is_empty() { return Err(ShellError::GenericError { error: "Missing file operand".into(), msg: "Missing file operand".into(), span: Some(call.head), help: Some("Please provide source and destination paths".into()), inner: Vec::new(), }); } if paths.len() == 1 { // expand path for better error message return Err(ShellError::GenericError { error: "Missing destination path".into(), msg: format!( "Missing destination path operand after {}", expand_path_with(paths[0].item.as_ref(), cwd, paths[0].item.is_expand()) .to_string_lossy() ), span: Some(paths[0].span), help: None, inner: Vec::new(), }); } // Do not glob target let spanned_target = paths.pop().ok_or(ShellError::NushellFailedSpanned { msg: "Missing file operand".into(), label: "Missing file operand".into(), span: call.head, })?; let mut files: Vec<(Vec<PathBuf>, bool)> = Vec::new(); let glob_options = if all { None } else { let glob_options = MatchOptions { require_literal_leading_dot: true, ..Default::default() }; Some(glob_options) }; for mut p in paths { p.item = p.item.strip_ansi_string_unlikely(); let exp_files: Vec<Result<PathBuf, ShellError>> = nu_engine::glob_from( &p, &cwd, call.head, glob_options, engine_state.signals().clone(), ) .map(|f| f.1)? .collect(); if exp_files.is_empty() { return Err(ShellError::Io(IoError::new( shell_error::io::ErrorKind::FileNotFound, p.span, PathBuf::from(p.item.to_string()), ))); }; let mut app_vals: Vec<PathBuf> = Vec::new(); for v in exp_files { match v { Ok(path) => { app_vals.push(path); } Err(e) => return Err(e), } } files.push((app_vals, p.item.is_expand())); } // Make sure to send absolute paths to avoid uu_cp looking for cwd in std::env which is not // supported in Nushell for (files, need_expand_tilde) in files.iter_mut() { for src in files.iter_mut() { if !src.is_absolute() { *src = nu_path::expand_path_with(&*src, &cwd, *need_expand_tilde); } } } let mut files: Vec<PathBuf> = files.into_iter().flat_map(|x| x.0).collect(); // Add back the target after globbing let abs_target_path = expand_path_with( nu_utils::strip_ansi_string_unlikely(spanned_target.item.to_string()), &cwd, matches!(spanned_target.item, NuGlob::Expand(..)), ); files.push(abs_target_path.clone()); let files = files .into_iter() .map(|p| p.into_os_string()) .collect::<Vec<OsString>>(); let options = uu_mv::Options { overwrite, progress_bar: progress, verbose, suffix: String::from("~"), backup: BackupMode::None, update, target_dir: None, no_target_dir: false, strip_slashes: false, debug: false, context: None, }; if let Err(error) = uu_mv::mv(&files, &options) { return Err(ShellError::GenericError { error: format!("{error}"), msg: translate!(&error.to_string()), span: None, help: None, inner: Vec::new(), }); } Ok(PipelineData::empty()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/mod.rs
crates/nu-command/src/filesystem/mod.rs
mod cd; mod du; mod glob; mod ls; mod mktemp; mod open; mod rm; mod save; mod start; mod ucp; mod umkdir; mod umv; mod util; mod utouch; mod watch; pub use self::open::Open; pub use cd::Cd; pub use du::Du; pub use glob::Glob; pub use ls::Ls; pub use mktemp::Mktemp; pub use rm::Rm; pub use save::Save; pub use start::Start; pub use ucp::UCp; pub use umkdir::UMkdir; pub use umv::UMv; pub use utouch::UTouch; pub use watch::Watch;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/save.rs
crates/nu-command/src/filesystem/save.rs
use crate::progress_bar; use nu_engine::get_eval_block; #[allow(deprecated)] use nu_engine::{command_prelude::*, current_dir}; use nu_path::{expand_path_with, is_windows_device_path}; use nu_protocol::{ ByteStreamSource, DataSource, OutDest, PipelineMetadata, Signals, ast, byte_stream::copy_with_signals, process::ChildPipe, shell_error::io::IoError, }; use std::{ borrow::Cow, fs::File, io::{self, BufRead, BufReader, Read, Write}, path::{Path, PathBuf}, thread, time::{Duration, Instant}, }; #[derive(Clone)] pub struct Save; impl Command for Save { fn name(&self) -> &str { "save" } fn description(&self) -> &str { "Save a file." } fn search_terms(&self) -> Vec<&str> { vec![ "write", "write_file", "append", "redirection", "file", "io", ">", ">>", ] } fn signature(&self) -> nu_protocol::Signature { Signature::build("save") .input_output_types(vec![(Type::Any, Type::Nothing)]) .required("filename", SyntaxShape::Filepath, "The filename to use.") .named( "stderr", SyntaxShape::Filepath, "the filename used to save stderr, only works with `-r` flag", Some('e'), ) .switch("raw", "save file as raw binary", Some('r')) .switch("append", "append input to the end of the file", Some('a')) .switch("force", "overwrite the destination", Some('f')) .switch("progress", "enable progress bar", Some('p')) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let raw = call.has_flag(engine_state, stack, "raw")?; let append = call.has_flag(engine_state, stack, "append")?; let force = call.has_flag(engine_state, stack, "force")?; let progress = call.has_flag(engine_state, stack, "progress")?; let span = call.head; #[allow(deprecated)] let cwd = current_dir(engine_state, stack)?; let path_arg = call.req::<Spanned<PathBuf>>(engine_state, stack, 0)?; let path = Spanned { item: expand_path_with(path_arg.item, &cwd, true), span: path_arg.span, }; let stderr_path = call .get_flag::<Spanned<PathBuf>>(engine_state, stack, "stderr")? .map(|arg| Spanned { item: expand_path_with(arg.item, cwd, true), span: arg.span, }); let from_io_error = IoError::factory(span, path.item.as_path()); match input { PipelineData::ByteStream(stream, metadata) => { check_saving_to_source_file(metadata.as_ref(), &path, stderr_path.as_ref())?; let (file, stderr_file) = get_files(engine_state, &path, stderr_path.as_ref(), append, force)?; let size = stream.known_size(); let signals = engine_state.signals(); match stream.into_source() { ByteStreamSource::Read(read) => { stream_to_file(read, size, signals, file, span, progress)?; } ByteStreamSource::File(source) => { stream_to_file(source, size, signals, file, span, progress)?; } #[cfg(feature = "os")] ByteStreamSource::Child(mut child) => { fn write_or_consume_stderr( stderr: ChildPipe, file: Option<File>, span: Span, signals: &Signals, progress: bool, ) -> Result<(), ShellError> { if let Some(file) = file { match stderr { ChildPipe::Pipe(pipe) => { stream_to_file(pipe, None, signals, file, span, progress) } ChildPipe::Tee(tee) => { stream_to_file(tee, None, signals, file, span, progress) } }? } else { match stderr { ChildPipe::Pipe(mut pipe) => { io::copy(&mut pipe, &mut io::stderr()) } ChildPipe::Tee(mut tee) => { io::copy(&mut tee, &mut io::stderr()) } } .map_err(|err| IoError::new(err, span, None))?; } Ok(()) } match (child.stdout.take(), child.stderr.take()) { (Some(stdout), stderr) => { // delegate a thread to redirect stderr to result. let handler = stderr .map(|stderr| { let signals = signals.clone(); thread::Builder::new().name("stderr saver".into()).spawn( move || { write_or_consume_stderr( stderr, stderr_file, span, &signals, progress, ) }, ) }) .transpose() .map_err(&from_io_error)?; let res = match stdout { ChildPipe::Pipe(pipe) => { stream_to_file(pipe, None, signals, file, span, progress) } ChildPipe::Tee(tee) => { stream_to_file(tee, None, signals, file, span, progress) } }; if let Some(h) = handler { h.join().map_err(|err| ShellError::ExternalCommand { label: "Fail to receive external commands stderr message" .to_string(), help: format!("{err:?}"), span, })??; } res?; } (None, Some(stderr)) => { write_or_consume_stderr( stderr, stderr_file, span, signals, progress, )?; } (None, None) => {} }; child.wait()?; } } Ok(PipelineData::empty()) } PipelineData::ListStream(ls, pipeline_metadata) if raw || prepare_path(&path, append, force)?.0.extension().is_none() => { check_saving_to_source_file( pipeline_metadata.as_ref(), &path, stderr_path.as_ref(), )?; let (mut file, _) = get_files(engine_state, &path, stderr_path.as_ref(), append, force)?; for val in ls { file.write_all(&value_to_bytes(val)?) .map_err(&from_io_error)?; file.write_all("\n".as_bytes()).map_err(&from_io_error)?; } file.flush().map_err(&from_io_error)?; Ok(PipelineData::empty()) } input => { // It's not necessary to check if we are saving to the same file if this is a // collected value, and not a stream if !matches!(input, PipelineData::Value(..) | PipelineData::Empty) { check_saving_to_source_file( input.metadata().as_ref(), &path, stderr_path.as_ref(), )?; } // Try to convert the input pipeline into another type if we know the extension let ext = extract_extension(&input, &path.item, raw); let converted = match ext { None => input, Some(ext) => convert_to_extension(engine_state, &ext, stack, input, span)?, }; // Save custom value however they implement saving if let PipelineData::Value(v @ Value::Custom { .. }, ..) = converted { let val_span = v.span(); let val = v.into_custom_value()?; return val .save( Spanned { item: &path.item, span: path.span, }, val_span, span, ) .map(|()| PipelineData::empty()); } let bytes = value_to_bytes(converted.into_value(span)?)?; // Only open file after successful conversion let (mut file, _) = get_files(engine_state, &path, stderr_path.as_ref(), append, force)?; file.write_all(&bytes).map_err(&from_io_error)?; file.flush().map_err(&from_io_error)?; Ok(PipelineData::empty()) } } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Save a string to foo.txt in the current directory", example: r#"'save me' | save foo.txt"#, result: None, }, Example { description: "Append a string to the end of foo.txt", example: r#"'append me' | save --append foo.txt"#, result: None, }, Example { description: "Save a record to foo.json in the current directory", example: r#"{ a: 1, b: 2 } | save foo.json"#, result: None, }, Example { description: "Save a running program's stderr to foo.txt", example: r#"do -i {} | save foo.txt --stderr foo.txt"#, result: None, }, Example { description: "Save a running program's stderr to separate file", example: r#"do -i {} | save foo.txt --stderr bar.txt"#, result: None, }, Example { description: "Show the extensions for which the `save` command will automatically serialize", example: r#"scope commands | where name starts-with "to " | insert extension { get name | str replace -r "^to " "" | $"*.($in)" } | select extension name | rename extension command "#, result: None, }, ] } fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) { (Some(OutDest::PipeSeparate), Some(OutDest::PipeSeparate)) } } fn saving_to_source_file_error(dest: &Spanned<PathBuf>) -> ShellError { ShellError::GenericError { error: "pipeline input and output are the same file".into(), msg: format!( "can't save output to '{}' while it's being read", dest.item.display() ), span: Some(dest.span), help: Some( "insert a `collect` command in the pipeline before `save` (see `help collect`).".into(), ), inner: vec![], } } fn check_saving_to_source_file( metadata: Option<&PipelineMetadata>, dest: &Spanned<PathBuf>, stderr_dest: Option<&Spanned<PathBuf>>, ) -> Result<(), ShellError> { let Some(DataSource::FilePath(source)) = metadata.map(|meta| &meta.data_source) else { return Ok(()); }; if &dest.item == source { return Err(saving_to_source_file_error(dest)); } if let Some(dest) = stderr_dest && &dest.item == source { return Err(saving_to_source_file_error(dest)); } Ok(()) } /// Extract extension for conversion. fn extract_extension<'e>(input: &PipelineData, path: &'e Path, raw: bool) -> Option<Cow<'e, str>> { match (raw, input) { (true, _) | (_, PipelineData::ByteStream(..)) | (_, PipelineData::Value(Value::String { .. }, ..)) => None, _ => path.extension().map(|name| name.to_string_lossy()), } } /// Convert given data into content of file of specified extension if /// corresponding `to` command exists. Otherwise attempt to convert /// data to bytes as is fn convert_to_extension( engine_state: &EngineState, extension: &str, stack: &mut Stack, input: PipelineData, span: Span, ) -> Result<PipelineData, ShellError> { if let Some(decl_id) = engine_state.find_decl(format!("to {extension}").as_bytes(), &[]) { let decl = engine_state.get_decl(decl_id); if let Some(block_id) = decl.block_id() { let block = engine_state.get_block(block_id); let eval_block = get_eval_block(engine_state); eval_block(engine_state, stack, block, input).map(|p| p.body) } else { let call = ast::Call::new(span); decl.run(engine_state, stack, &(&call).into(), input) } } else { Ok(input) } } /// Convert [`Value::String`] [`Value::Binary`] or [`Value::List`] into [`Vec`] of bytes /// /// Propagates [`Value::Error`] and creates error otherwise fn value_to_bytes(value: Value) -> Result<Vec<u8>, ShellError> { match value { Value::String { val, .. } => Ok(val.into_bytes()), Value::Binary { val, .. } => Ok(val), Value::List { vals, .. } => { let val = vals .into_iter() .map(Value::coerce_into_string) .collect::<Result<Vec<String>, ShellError>>()? .join("\n") + "\n"; Ok(val.into_bytes()) } // Propagate errors by explicitly matching them before the final case. Value::Error { error, .. } => Err(*error), other => Ok(other.coerce_into_string()?.into_bytes()), } } /// Convert string path to [`Path`] and [`Span`] and check if this path /// can be used with given flags fn prepare_path( path: &Spanned<PathBuf>, append: bool, force: bool, ) -> Result<(&Path, Span), ShellError> { let span = path.span; let path = &path.item; if !(force || append) && path.exists() { Err(ShellError::GenericError { error: "Destination file already exists".into(), msg: format!( "Destination file '{}' already exists", path.to_string_lossy() ), span: Some(span), help: Some("you can use -f, --force to force overwriting the destination".into()), inner: vec![], }) } else { Ok((path, span)) } } fn open_file( engine_state: &EngineState, path: &Path, span: Span, append: bool, ) -> Result<File, ShellError> { let file: std::io::Result<File> = match (append, path.exists() || is_windows_device_path(path)) { (true, true) => std::fs::OpenOptions::new().append(true).open(path), _ => { // This is a temporary solution until `std::fs::File::create` is fixed on Windows (rust-lang/rust#134893) // A TOCTOU problem exists here, which may cause wrong error message to be shown #[cfg(target_os = "windows")] if path.is_dir() { #[allow( deprecated, reason = "we don't get a IsADirectory error, so we need to provide it" )] Err(std::io::ErrorKind::IsADirectory.into()) } else { std::fs::File::create(path) } #[cfg(not(target_os = "windows"))] std::fs::File::create(path) } }; match file { Ok(file) => Ok(file), Err(err) => { // In caase of NotFound, search for the missing parent directory. // This also presents a TOCTOU (or TOUTOC, technically?) if err.kind() == std::io::ErrorKind::NotFound && let Some(missing_component) = path.ancestors().skip(1).filter(|dir| !dir.exists()).last() { // By looking at the postfix to remove, rather than the prefix // to keep, we are able to handle relative paths too. let components_to_remove = path .strip_prefix(missing_component) .expect("Stripping ancestor from a path should never fail") .as_os_str() .as_encoded_bytes(); return Err(ShellError::Io(IoError::new( ErrorKind::DirectoryNotFound, engine_state .span_match_postfix(span, components_to_remove) .map(|(pre, _post)| pre) .unwrap_or(span), PathBuf::from(missing_component), ))); } Err(ShellError::Io(IoError::new(err, span, PathBuf::from(path)))) } } } /// Get output file and optional stderr file fn get_files( engine_state: &EngineState, path: &Spanned<PathBuf>, stderr_path: Option<&Spanned<PathBuf>>, append: bool, force: bool, ) -> Result<(File, Option<File>), ShellError> { // First check both paths let (path, path_span) = prepare_path(path, append, force)?; let stderr_path_and_span = stderr_path .as_ref() .map(|stderr_path| prepare_path(stderr_path, append, force)) .transpose()?; // Only if both files can be used open and possibly truncate them let file = open_file(engine_state, path, path_span, append)?; let stderr_file = stderr_path_and_span .map(|(stderr_path, stderr_path_span)| { if path == stderr_path { Err(ShellError::GenericError { error: "input and stderr input to same file".into(), msg: "can't save both input and stderr input to the same file".into(), span: Some(stderr_path_span), help: Some("you should use `o+e> file` instead".into()), inner: vec![], }) } else { open_file(engine_state, stderr_path, stderr_path_span, append) } }) .transpose()?; Ok((file, stderr_file)) } fn stream_to_file( source: impl Read, known_size: Option<u64>, signals: &Signals, mut file: File, span: Span, progress: bool, ) -> Result<(), ShellError> { // TODO: maybe we can get a path in here let from_io_error = IoError::factory(span, None); // https://github.com/nushell/nushell/pull/9377 contains the reason for not using `BufWriter` if progress { let mut bytes_processed = 0; let mut bar = progress_bar::NuProgressBar::new(known_size); let mut last_update = Instant::now(); let mut reader = BufReader::new(source); let res = loop { if let Err(err) = signals.check(&span) { bar.abandoned_msg("# Cancelled #".to_owned()); return Err(err); } match reader.fill_buf() { Ok(&[]) => break Ok(()), Ok(buf) => { file.write_all(buf).map_err(&from_io_error)?; let len = buf.len(); reader.consume(len); bytes_processed += len as u64; if last_update.elapsed() >= Duration::from_millis(75) { bar.update_bar(bytes_processed); last_update = Instant::now(); } } Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, Err(e) => break Err(e), } }; // If the process failed, stop the progress bar with an error message. if let Err(err) = res { let _ = file.flush(); bar.abandoned_msg("# Error while saving #".to_owned()); Err(from_io_error(err).into()) } else { file.flush().map_err(&from_io_error)?; Ok(()) } } else { copy_with_signals(source, file, span, signals)?; Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/du.rs
crates/nu-command/src/filesystem/du.rs
use crate::{DirBuilder, DirInfo, FileInfo}; #[allow(deprecated)] use nu_engine::{command_prelude::*, current_dir}; use nu_glob::{MatchOptions, Pattern}; use nu_protocol::{NuGlob, Signals}; use serde::Deserialize; use std::path::Path; #[derive(Clone)] pub struct Du; #[derive(Deserialize, Clone, Debug)] pub struct DuArgs { path: Option<Spanned<NuGlob>>, deref: bool, long: bool, all: bool, exclude: Option<Spanned<NuGlob>>, #[serde(rename = "max-depth")] max_depth: Option<Spanned<i64>>, #[serde(rename = "min-size")] min_size: Option<Spanned<i64>>, } impl Command for Du { fn name(&self) -> &str { "du" } fn description(&self) -> &str { "Find disk usage sizes of specified items." } fn signature(&self) -> Signature { Signature::build("du") .input_output_types(vec![(Type::Nothing, Type::table())]) .allow_variants_without_examples(true) .rest( "path", SyntaxShape::OneOf(vec![SyntaxShape::GlobPattern, SyntaxShape::String]), "Starting directory.", ) .switch( "deref", "Dereference symlinks to their targets for size", Some('r'), ) .switch( "long", "Get underlying directories and files for each entry", Some('l'), ) .named( "exclude", SyntaxShape::GlobPattern, "Exclude these file names", Some('x'), ) .named( "max-depth", SyntaxShape::Int, "Directory recursion limit", Some('d'), ) .named( "min-size", SyntaxShape::Int, "Exclude files below this size", Some('m'), ) .switch("all", "move hidden files if '*' is provided", Some('a')) .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let tag = call.head; let min_size: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "min-size")?; let max_depth: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "max-depth")?; if let Some(ref max_depth) = max_depth && max_depth.item < 0 { return Err(ShellError::NeedsPositiveValue { span: max_depth.span, }); } if let Some(ref min_size) = min_size && min_size.item < 0 { return Err(ShellError::NeedsPositiveValue { span: min_size.span, }); } let deref = call.has_flag(engine_state, stack, "deref")?; let long = call.has_flag(engine_state, stack, "long")?; let exclude = call.get_flag(engine_state, stack, "exclude")?; #[allow(deprecated)] let current_dir = current_dir(engine_state, stack)?; let all = call.has_flag(engine_state, stack, "all")?; let paths = call.rest::<Spanned<NuGlob>>(engine_state, stack, 0)?; let paths = if !call.has_positional_args(stack, 0) { None } else { Some(paths) }; match paths { None => { let args = DuArgs { path: None, deref, long, all, exclude, max_depth, min_size, }; Ok( du_for_one_pattern(args, &current_dir, tag, engine_state.signals().clone())? .into_pipeline_data(tag, engine_state.signals().clone()), ) } Some(paths) => { let mut result_iters = vec![]; for p in paths { let args = DuArgs { path: Some(p), deref, long, all, exclude: exclude.clone(), max_depth, min_size, }; result_iters.push(du_for_one_pattern( args, &current_dir, tag, engine_state.signals().clone(), )?) } // chain all iterators on result. Ok(result_iters .into_iter() .flatten() .into_pipeline_data(tag, engine_state.signals().clone())) } } } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Disk usage of the current directory", example: "du", result: None, }] } } fn du_for_one_pattern( args: DuArgs, current_dir: &Path, span: Span, signals: Signals, ) -> Result<impl Iterator<Item = Value> + Send + use<>, ShellError> { let exclude = args.exclude.map_or(Ok(None), move |x| { Pattern::new(x.item.as_ref()) .map(Some) .map_err(|e| ShellError::InvalidGlobPattern { msg: e.msg.into(), span: x.span, }) })?; let glob_options = if args.all { None } else { let glob_options = MatchOptions { require_literal_leading_dot: true, ..Default::default() }; Some(glob_options) }; let paths = match args.path { Some(p) => nu_engine::glob_from(&p, current_dir, span, glob_options, signals.clone()), // The * pattern should never fail. None => nu_engine::glob_from( &Spanned { item: NuGlob::Expand("*".into()), span: Span::unknown(), }, current_dir, span, None, signals.clone(), ), } .map(|f| f.1)?; let deref = args.deref; let long = args.long; let max_depth = args.max_depth.map(|f| f.item as u64); let min_size = args.min_size.map(|f| f.item as u64); let params = DirBuilder { tag: span, min: min_size, deref, exclude, long, }; Ok(paths.filter_map(move |p| match p { Ok(a) => { if a.is_dir() { match DirInfo::new(a, &params, max_depth, span, &signals) { Ok(v) => Some(Value::from(v)), Err(_) => None, } } else { match FileInfo::new(a, deref, span, params.long) { Ok(v) => Some(Value::from(v)), Err(_) => None, } } } Err(e) => Some(Value::error(e, span)), })) } #[cfg(test)] mod tests { use super::Du; #[test] fn examples_work_as_expected() { use crate::test_examples; test_examples(Du {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/start.rs
crates/nu-command/src/filesystem/start.rs
use itertools::Itertools; use nu_engine::{command_prelude::*, env_to_strings}; use nu_protocol::ShellError; use std::{ ffi::{OsStr, OsString}, process::Stdio, }; #[derive(Clone)] pub struct Start; impl Command for Start { fn name(&self) -> &str { "start" } fn description(&self) -> &str { "Open a folder, file, or website in the default application or viewer." } fn search_terms(&self) -> Vec<&str> { vec!["load", "folder", "directory", "run", "open"] } fn signature(&self) -> nu_protocol::Signature { Signature::build("start") .input_output_types(vec![(Type::Nothing, Type::Any)]) .required("path", SyntaxShape::String, "Path or URL to open.") .category(Category::FileSystem) } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let path = call.req::<Spanned<String>>(engine_state, stack, 0)?; let path = Spanned { item: nu_utils::strip_ansi_string_unlikely(path.item), span: path.span, }; let path_no_whitespace = path.item.trim_end_matches(|x| matches!(x, '\x09'..='\x0d')); // Attempt to parse the input as a URL if let Ok(url) = url::Url::parse(path_no_whitespace) { open_path(url.as_str(), engine_state, stack, path.span)?; return Ok(PipelineData::empty()); } // If it's not a URL, treat it as a file path let cwd = engine_state.cwd(Some(stack))?; let full_path = nu_path::expand_path_with(path_no_whitespace, &cwd, true); // Check if the path exists or if it's a valid file/directory if full_path.exists() { open_path(full_path, engine_state, stack, path.span)?; return Ok(PipelineData::empty()); } // If neither file nor URL, return an error Err(ShellError::GenericError { error: format!("Cannot find file or URL: {}", &path.item), msg: "".into(), span: Some(path.span), help: Some("Ensure the path or URL is correct and try again.".into()), inner: vec![], }) } fn examples(&self) -> Vec<nu_protocol::Example<'_>> { vec![ Example { description: "Open a text file with the default text editor", example: "start file.txt", result: None, }, Example { description: "Open an image with the default image viewer", example: "start file.jpg", result: None, }, Example { description: "Open the current directory with the default file manager", example: "start .", result: None, }, Example { description: "Open a PDF with the default PDF viewer", example: "start file.pdf", result: None, }, Example { description: "Open a website with the default browser", example: "start https://www.nushell.sh", result: None, }, Example { description: "Open an application-registered protocol URL", example: "start obsidian://open?vault=Test", result: None, }, ] } } fn open_path( path: impl AsRef<OsStr>, engine_state: &EngineState, stack: &Stack, span: Span, ) -> Result<(), ShellError> { try_commands(open::commands(path), engine_state, stack, span) } fn try_commands( commands: Vec<std::process::Command>, engine_state: &EngineState, stack: &Stack, span: Span, ) -> Result<(), ShellError> { let env_vars_str = env_to_strings(engine_state, stack)?; let mut last_err = None; for mut cmd in commands { let status = cmd .envs(&env_vars_str) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .status(); match status { Ok(status) if status.success() => return Ok(()), Ok(status) => { last_err = Some(format!( "Command `{}` failed with exit code: {}", format_command(&cmd), status.code().unwrap_or(-1) )); } Err(err) => { last_err = Some(format!( "Command `{}` failed with error: {}", format_command(&cmd), err )); } } } Err(ShellError::ExternalCommand { label: "Failed to start the specified path or URL".to_string(), help: format!( "Try a different path or install the appropriate application.\n{}", last_err.unwrap_or_default() ), span, }) } fn format_command(command: &std::process::Command) -> String { let parts_iter = std::iter::once(command.get_program()).chain(command.get_args()); Itertools::intersperse(parts_iter, OsStr::new(" ")) .collect::<OsString>() .to_string_lossy() .into_owned() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/filesystem/mktemp.rs
crates/nu-command/src/filesystem/mktemp.rs
#[allow(deprecated)] use nu_engine::{command_prelude::*, env::current_dir}; use std::path::PathBuf; use uucore::{localized_help_template, translate}; #[derive(Clone)] pub struct Mktemp; impl Command for Mktemp { fn name(&self) -> &str { "mktemp" } fn description(&self) -> &str { "Create temporary files or directories using uutils/coreutils mktemp." } fn search_terms(&self) -> Vec<&str> { vec![ "create", "directory", "file", "folder", "temporary", "coreutils", ] } fn signature(&self) -> Signature { Signature::build("mktemp") .input_output_types(vec![(Type::Nothing, Type::String)]) .optional( "template", SyntaxShape::String, "Optional pattern from which the name of the file or directory is derived. Must contain at least three 'X's in last component.", ) .named("suffix", SyntaxShape::String, "Append suffix to template; must not contain a slash.", None) .named("tmpdir-path", SyntaxShape::Filepath, "Interpret TEMPLATE relative to tmpdir-path. If tmpdir-path is not set use $TMPDIR", Some('p')) .switch("tmpdir", "Interpret TEMPLATE relative to the system temporary directory.", Some('t')) .switch("directory", "Create a directory instead of a file.", Some('d')) .switch("dry", "Don't create a file and just return the path that would have been created.", None) .category(Category::FileSystem) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Make a temporary file with the given suffix in the current working directory.", example: "mktemp --suffix .txt", result: Some(Value::test_string("<WORKING_DIR>/tmp.lekjbhelyx.txt")), }, Example { description: "Make a temporary file named testfile.XXX with the 'X's as random characters in the current working directory.", example: "mktemp testfile.XXX", result: Some(Value::test_string("<WORKING_DIR>/testfile.4kh")), }, Example { description: "Make a temporary file with a template in the system temp directory.", example: "mktemp -t testfile.XXX", result: Some(Value::test_string("/tmp/testfile.4kh")), }, Example { description: "Make a temporary directory with randomly generated name in the temporary directory.", example: "mktemp -d", result: Some(Value::test_string("/tmp/tmp.NMw9fJr8K0")), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // setup the uutils error translation let _ = localized_help_template("mktemp"); let span = call.head; let template = call .rest(engine_state, stack, 0)? .first() .cloned() .map(|i: Spanned<String>| i.item) .unwrap_or("tmp.XXXXXXXXXX".to_string()); // same as default in coreutils let directory = call.has_flag(engine_state, stack, "directory")?; let dry_run = call.has_flag(engine_state, stack, "dry")?; let suffix = call.get_flag(engine_state, stack, "suffix")?; let tmpdir = call.has_flag(engine_state, stack, "tmpdir")?; let tmpdir_path = call .get_flag(engine_state, stack, "tmpdir-path")? .map(|i: Spanned<PathBuf>| i.item); let tmpdir = if tmpdir_path.is_some() { tmpdir_path } else if directory || tmpdir { Some(std::env::temp_dir()) } else { #[allow(deprecated)] Some(current_dir(engine_state, stack)?) }; let options = uu_mktemp::Options { directory, dry_run, quiet: false, suffix, template: template.into(), tmpdir, treat_as_template: true, }; let res = match uu_mktemp::mktemp(&options) { Ok(res) => res .into_os_string() .into_string() .map_err(|_| ShellError::NonUtf8 { span })?, Err(error) => { return Err(ShellError::GenericError { error: format!("{error}"), msg: translate!(&error.to_string()), span: None, help: None, inner: vec![], }); } }; Ok(PipelineData::value(Value::string(res, span), None)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/nu_xml_format.rs
crates/nu-command/src/formats/nu_xml_format.rs
pub const COLUMN_TAG_NAME: &str = "tag"; pub const COLUMN_ATTRS_NAME: &str = "attributes"; pub const COLUMN_CONTENT_NAME: &str = "content";
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/mod.rs
crates/nu-command/src/formats/mod.rs
mod from; mod nu_xml_format; mod to; pub use from::*; pub use to::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/from/xlsx.rs
crates/nu-command/src/formats/from/xlsx.rs
use calamine::*; use chrono::{Local, LocalResult, Offset, TimeZone, Utc}; use indexmap::IndexMap; use nu_engine::command_prelude::*; use std::io::Cursor; #[derive(Clone)] pub struct FromXlsx; impl Command for FromXlsx { fn name(&self) -> &str { "from xlsx" } fn signature(&self) -> Signature { Signature::build("from xlsx") .input_output_types(vec![(Type::Binary, Type::table())]) .allow_variants_without_examples(true) .named( "sheets", SyntaxShape::List(Box::new(SyntaxShape::String)), "Only convert specified sheets", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Parse binary Excel(.xlsx) data and create table." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let sel_sheets = if let Some(Value::List { vals: columns, .. }) = call.get_flag(engine_state, stack, "sheets")? { convert_columns(columns.as_slice())? } else { vec![] }; let metadata = input.metadata().map(|md| md.with_content_type(None)); from_xlsx(input, head, sel_sheets).map(|pd| pd.set_metadata(metadata)) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert binary .xlsx data to a table", example: "open --raw test.xlsx | from xlsx", result: None, }, Example { description: "Convert binary .xlsx data to a table, specifying the tables", example: "open --raw test.xlsx | from xlsx --sheets [Spreadsheet1]", result: None, }, ] } } fn convert_columns(columns: &[Value]) -> Result<Vec<String>, ShellError> { let res = columns .iter() .map(|value| match &value { Value::String { val: s, .. } => Ok(s.clone()), _ => Err(ShellError::IncompatibleParametersSingle { msg: "Incorrect column format, Only string as column name".to_string(), span: value.span(), }), }) .collect::<Result<Vec<String>, _>>()?; Ok(res) } fn collect_binary(input: PipelineData, span: Span) -> Result<Vec<u8>, ShellError> { if let PipelineData::ByteStream(stream, ..) = input { stream.into_bytes() } else { let mut bytes = vec![]; let mut values = input.into_iter(); loop { match values.next() { Some(Value::Binary { val: b, .. }) => { bytes.extend_from_slice(&b); } Some(x) => { return Err(ShellError::UnsupportedInput { msg: "Expected binary from pipeline".to_string(), input: "value originates from here".into(), msg_span: span, input_span: x.span(), }); } None => break, } } Ok(bytes) } } fn from_xlsx( input: PipelineData, head: Span, sel_sheets: Vec<String>, ) -> Result<PipelineData, ShellError> { let span = input.span(); let bytes = collect_binary(input, head)?; let buf: Cursor<Vec<u8>> = Cursor::new(bytes); let mut xlsx = Xlsx::<_>::new(buf).map_err(|_| ShellError::UnsupportedInput { msg: "Could not load XLSX file".to_string(), input: "value originates from here".into(), msg_span: head, input_span: span.unwrap_or(head), })?; let mut dict = IndexMap::new(); let mut sheet_names = xlsx.sheet_names(); if !sel_sheets.is_empty() { sheet_names.retain(|e| sel_sheets.contains(e)); } let tz = match Local.timestamp_opt(0, 0) { LocalResult::Single(tz) => *tz.offset(), _ => Utc.fix(), }; for sheet_name in sheet_names { let mut sheet_output = vec![]; if let Ok(current_sheet) = xlsx.worksheet_range(&sheet_name) { for row in current_sheet.rows() { let record = row .iter() .enumerate() .map(|(i, cell)| { let value = match cell { Data::Empty => Value::nothing(head), Data::String(s) => Value::string(s, head), Data::Float(f) => Value::float(*f, head), Data::Int(i) => Value::int(*i, head), Data::Bool(b) => Value::bool(*b, head), Data::DateTime(d) => d .as_datetime() .and_then(|d| match tz.from_local_datetime(&d) { LocalResult::Single(d) => Some(d), _ => None, }) .map(|d| Value::date(d, head)) .unwrap_or(Value::nothing(head)), _ => Value::nothing(head), }; (format!("column{i}"), value) }) .collect(); sheet_output.push(Value::record(record, head)); } dict.insert(sheet_name, Value::list(sheet_output, head)); } else { return Err(ShellError::UnsupportedInput { msg: "Could not load sheet".to_string(), input: "value originates from here".into(), msg_span: head, input_span: span.unwrap_or(head), }); } } Ok(PipelineData::value( Value::record(dict.into_iter().collect(), head), None, )) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromXlsx {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/from/nuon.rs
crates/nu-command/src/formats/from/nuon.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct FromNuon; impl Command for FromNuon { fn name(&self) -> &str { "from nuon" } fn description(&self) -> &str { "Convert from nuon to structured data." } fn signature(&self) -> nu_protocol::Signature { Signature::build("from nuon") .input_output_types(vec![(Type::String, Type::Any)]) .category(Category::Formats) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "'{ a:1 }' | from nuon", description: "Converts nuon formatted string to table", result: Some(Value::test_record(record! { "a" => Value::test_int(1), })), }, Example { example: "'{ a:1, b: [1, 2] }' | from nuon", description: "Converts nuon formatted string to table", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_list(vec![Value::test_int(1), Value::test_int(2)]), })), }, Example { example: "'{a:1,b:[1,2]}' | from nuon", description: "Converts raw nuon formatted string to table", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_list(vec![Value::test_int(1), 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 (string_input, _span, metadata) = input.collect_string_strict(head)?; match nuon::from_nuon(&string_input, Some(head)) { Ok(result) => Ok(result .into_pipeline_data_with_metadata(metadata.map(|md| md.with_content_type(None)))), Err(err) => Err(ShellError::GenericError { error: "error when loading nuon text".into(), msg: "could not load nuon text".into(), span: Some(head), help: None, inner: vec![err], }), } } } #[cfg(test)] mod test { use nu_cmd_lang::eval_pipeline_without_terminal_expression; use crate::Reject; use crate::{Metadata, MetadataSet}; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromNuon {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromNuon {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#"'[[a, b]; [1, 2]]' | metadata set --content-type 'application/x-nuon' --datasource-ls | from nuon | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/msgpack.rs
crates/nu-command/src/formats/from/msgpack.rs
// Credit to https://github.com/hulthe/nu_plugin_msgpack for the original idea, though the // implementation here is unique. use std::{ error::Error, io::{self, Cursor, ErrorKind}, string::FromUtf8Error, }; use byteorder::{BigEndian, ReadBytesExt}; use chrono::{TimeZone, Utc}; use nu_engine::command_prelude::*; use nu_protocol::Signals; use rmp::decode::{self as mp, ValueReadError}; /// Max recursion depth const MAX_DEPTH: usize = 50; #[derive(Clone)] pub struct FromMsgpack; impl Command for FromMsgpack { fn name(&self) -> &str { "from msgpack" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Binary, Type::Any) .switch("objects", "Read multiple objects from input", None) .category(Category::Formats) } fn description(&self) -> &str { "Convert MessagePack data into Nu values." } fn extra_description(&self) -> &str { r#" Not all values are representable as MessagePack. The datetime extension type is read as dates. MessagePack binary values are read to their Nu equivalent. Most other types are read in an analogous way to `from json`, and may not convert to the exact same type if `to msgpack` was used originally to create the data. MessagePack: https://msgpack.org/ "# } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Read a list of values from MessagePack", example: "0x[93A3666F6F2AC2] | from msgpack", result: Some(Value::test_list(vec![ Value::test_string("foo"), Value::test_int(42), Value::test_bool(false), ])), }, Example { description: "Read a stream of multiple values from MessagePack", example: "0x[81A76E757368656C6CA5726F636B73A9736572696F75736C79] | from msgpack --objects", result: Some(Value::test_list(vec![ Value::test_record(record! { "nushell" => Value::test_string("rocks"), }), Value::test_string("seriously"), ])), }, Example { description: "Read a table from MessagePack", example: "0x[9282AA6576656E745F6E616D65B141706F6C6C6F203131204C616E64696E67A474696D65C70CFF00000000FFFFFFFFFF2CAB5B82AA6576656E745F6E616D65B44E757368656C6C20666972737420636F6D6D6974A474696D65D6FF5CD5ADE0] | from msgpack", result: Some(Value::test_list(vec![ Value::test_record(record! { "event_name" => Value::test_string("Apollo 11 Landing"), "time" => Value::test_date(Utc.with_ymd_and_hms( 1969, 7, 24, 16, 50, 35, ).unwrap().into()) }), Value::test_record(record! { "event_name" => Value::test_string("Nushell first commit"), "time" => Value::test_date(Utc.with_ymd_and_hms( 2019, 5, 10, 16, 59, 12, ).unwrap().into()) }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let objects = call.has_flag(engine_state, stack, "objects")?; let opts = Opts { span: call.head, objects, signals: engine_state.signals().clone(), }; let metadata = input.metadata().map(|md| md.with_content_type(None)); let out = match input { // Deserialize from a byte buffer PipelineData::Value(Value::Binary { val: bytes, .. }, _) => { read_msgpack(Cursor::new(bytes), opts) } // Deserialize from a raw stream directly without having to collect it PipelineData::ByteStream(stream, ..) => { let span = stream.span(); if let Some(reader) = stream.reader() { read_msgpack(reader, opts) } else { Err(ShellError::PipelineMismatch { exp_input_type: "binary or byte stream".into(), dst_span: call.head, src_span: span, }) } } input => Err(ShellError::PipelineMismatch { exp_input_type: "binary or byte stream".into(), dst_span: call.head, src_span: input.span().unwrap_or(call.head), }), }; out.map(|pd| pd.set_metadata(metadata)) } } #[derive(Debug)] pub(crate) enum ReadError { MaxDepth(Span), Io(io::Error, Span), TypeMismatch(rmp::Marker, Span), Utf8(FromUtf8Error, Span), Shell(Box<ShellError>), } impl From<Box<ShellError>> for ReadError { fn from(v: Box<ShellError>) -> Self { Self::Shell(v) } } impl From<ShellError> for ReadError { fn from(value: ShellError) -> Self { Box::new(value).into() } } impl From<Spanned<ValueReadError>> for ReadError { fn from(value: Spanned<ValueReadError>) -> Self { match value.item { // All I/O errors: ValueReadError::InvalidMarkerRead(err) | ValueReadError::InvalidDataRead(err) => { ReadError::Io(err, value.span) } ValueReadError::TypeMismatch(marker) => ReadError::TypeMismatch(marker, value.span), } } } impl From<Spanned<io::Error>> for ReadError { fn from(value: Spanned<io::Error>) -> Self { ReadError::Io(value.item, value.span) } } impl From<Spanned<FromUtf8Error>> for ReadError { fn from(value: Spanned<FromUtf8Error>) -> Self { ReadError::Utf8(value.item, value.span) } } impl From<ReadError> for ShellError { fn from(value: ReadError) -> Self { match value { ReadError::MaxDepth(span) => ShellError::GenericError { error: "MessagePack data is nested too deeply".into(), msg: format!("exceeded depth limit ({MAX_DEPTH})"), span: Some(span), help: None, inner: vec![], }, ReadError::Io(err, span) => ShellError::GenericError { error: "Error while reading MessagePack data".into(), msg: err.to_string(), span: Some(span), help: None, // Take the inner ShellError inner: err .source() .and_then(|s| s.downcast_ref::<ShellError>()) .cloned() .into_iter() .collect(), }, ReadError::TypeMismatch(marker, span) => ShellError::GenericError { error: "Invalid marker while reading MessagePack data".into(), msg: format!("unexpected {marker:?} in data"), span: Some(span), help: None, inner: vec![], }, ReadError::Utf8(err, span) => ShellError::NonUtf8Custom { msg: format!("in MessagePack data: {err}"), span, }, ReadError::Shell(err) => *err, } } } pub(crate) struct Opts { pub span: Span, pub objects: bool, pub signals: Signals, } /// Read single or multiple values into PipelineData pub(crate) fn read_msgpack( mut input: impl io::Read + Send + 'static, opts: Opts, ) -> Result<PipelineData, ShellError> { let Opts { span, objects, signals, } = opts; if objects { // Make an iterator that reads multiple values from the reader let mut done = false; Ok(std::iter::from_fn(move || { if !done { let result = read_value(&mut input, span, 0); match result { Ok(value) => Some(value), // Any error should cause us to not read anymore Err(ReadError::Io(err, _)) if err.kind() == ErrorKind::UnexpectedEof => { done = true; None } Err(other_err) => { done = true; Some(Value::error(other_err.into(), span)) } } } else { None } }) .into_pipeline_data(span, signals)) } else { // Read a single value and then make sure it's EOF let result = read_value(&mut input, span, 0)?; assert_eof(&mut input, span)?; Ok(result.into_pipeline_data()) } } fn read_value(input: &mut impl io::Read, span: Span, depth: usize) -> Result<Value, ReadError> { // Prevent stack overflow if depth >= MAX_DEPTH { return Err(ReadError::MaxDepth(span)); } let marker = mp::read_marker(input) .map_err(ValueReadError::from) .err_span(span)?; // We decide what kind of value to make depending on the marker. rmp doesn't really provide us // a lot of utilities for reading the data after the marker, I think they assume you want to // use rmp-serde or rmpv, but we don't have that kind of serde implementation for Value and so // hand-written deserialization is going to be the fastest match marker { rmp::Marker::FixPos(num) => Ok(Value::int(num as i64, span)), rmp::Marker::FixNeg(num) => Ok(Value::int(num as i64, span)), rmp::Marker::Null => Ok(Value::nothing(span)), rmp::Marker::True => Ok(Value::bool(true, span)), rmp::Marker::False => Ok(Value::bool(false, span)), rmp::Marker::U8 => from_int(input.read_u8(), span), rmp::Marker::U16 => from_int(input.read_u16::<BigEndian>(), span), rmp::Marker::U32 => from_int(input.read_u32::<BigEndian>(), span), rmp::Marker::U64 => { // u64 can be too big let val_u64 = input.read_u64::<BigEndian>().err_span(span)?; val_u64 .try_into() .map(|val| Value::int(val, span)) .map_err(|err| { ShellError::GenericError { error: "MessagePack integer too big for Nushell".into(), msg: err.to_string(), span: Some(span), help: None, inner: vec![], } .into() }) } rmp::Marker::I8 => from_int(input.read_i8(), span), rmp::Marker::I16 => from_int(input.read_i16::<BigEndian>(), span), rmp::Marker::I32 => from_int(input.read_i32::<BigEndian>(), span), rmp::Marker::I64 => from_int(input.read_i64::<BigEndian>(), span), rmp::Marker::F32 => Ok(Value::float( input.read_f32::<BigEndian>().err_span(span)? as f64, span, )), rmp::Marker::F64 => Ok(Value::float( input.read_f64::<BigEndian>().err_span(span)?, span, )), rmp::Marker::FixStr(len) => read_str(input, len as usize, span), rmp::Marker::Str8 => { let len = input.read_u8().err_span(span)?; read_str(input, len as usize, span) } rmp::Marker::Str16 => { let len = input.read_u16::<BigEndian>().err_span(span)?; read_str(input, len as usize, span) } rmp::Marker::Str32 => { let len = input.read_u32::<BigEndian>().err_span(span)?; read_str(input, len as usize, span) } rmp::Marker::Bin8 => { let len = input.read_u8().err_span(span)?; read_bin(input, len as usize, span) } rmp::Marker::Bin16 => { let len = input.read_u16::<BigEndian>().err_span(span)?; read_bin(input, len as usize, span) } rmp::Marker::Bin32 => { let len = input.read_u32::<BigEndian>().err_span(span)?; read_bin(input, len as usize, span) } rmp::Marker::FixArray(len) => read_array(input, len as usize, span, depth), rmp::Marker::Array16 => { let len = input.read_u16::<BigEndian>().err_span(span)?; read_array(input, len as usize, span, depth) } rmp::Marker::Array32 => { let len = input.read_u32::<BigEndian>().err_span(span)?; read_array(input, len as usize, span, depth) } rmp::Marker::FixMap(len) => read_map(input, len as usize, span, depth), rmp::Marker::Map16 => { let len = input.read_u16::<BigEndian>().err_span(span)?; read_map(input, len as usize, span, depth) } rmp::Marker::Map32 => { let len = input.read_u32::<BigEndian>().err_span(span)?; read_map(input, len as usize, span, depth) } rmp::Marker::FixExt1 => read_ext(input, 1, span), rmp::Marker::FixExt2 => read_ext(input, 2, span), rmp::Marker::FixExt4 => read_ext(input, 4, span), rmp::Marker::FixExt8 => read_ext(input, 8, span), rmp::Marker::FixExt16 => read_ext(input, 16, span), rmp::Marker::Ext8 => { let len = input.read_u8().err_span(span)?; read_ext(input, len as usize, span) } rmp::Marker::Ext16 => { let len = input.read_u16::<BigEndian>().err_span(span)?; read_ext(input, len as usize, span) } rmp::Marker::Ext32 => { let len = input.read_u32::<BigEndian>().err_span(span)?; read_ext(input, len as usize, span) } mk @ rmp::Marker::Reserved => Err(ReadError::TypeMismatch(mk, span)), } } fn read_str(input: &mut impl io::Read, len: usize, span: Span) -> Result<Value, ReadError> { let mut buf = vec![0; len]; input.read_exact(&mut buf).err_span(span)?; Ok(Value::string(String::from_utf8(buf).err_span(span)?, span)) } fn read_bin(input: &mut impl io::Read, len: usize, span: Span) -> Result<Value, ReadError> { let mut buf = vec![0; len]; input.read_exact(&mut buf).err_span(span)?; Ok(Value::binary(buf, span)) } fn read_array( input: &mut impl io::Read, len: usize, span: Span, depth: usize, ) -> Result<Value, ReadError> { let vec = (0..len) .map(|_| read_value(input, span, depth + 1)) .collect::<Result<Vec<Value>, ReadError>>()?; Ok(Value::list(vec, span)) } fn read_map( input: &mut impl io::Read, len: usize, span: Span, depth: usize, ) -> Result<Value, ReadError> { let rec = (0..len) .map(|_| { let key = read_value(input, span, depth + 1)? .into_string() .map_err(|_| ShellError::GenericError { error: "Invalid non-string value in MessagePack map".into(), msg: "only maps with string keys are supported".into(), span: Some(span), help: None, inner: vec![], })?; let val = read_value(input, span, depth + 1)?; Ok((key, val)) }) .collect::<Result<Record, ReadError>>()?; Ok(Value::record(rec, span)) } fn read_ext(input: &mut impl io::Read, len: usize, span: Span) -> Result<Value, ReadError> { let ty = input.read_i8().err_span(span)?; match (ty, len) { // "timestamp 32" - u32 seconds only (-1, 4) => { let seconds = input.read_u32::<BigEndian>().err_span(span)?; make_date(seconds as i64, 0, span) } // "timestamp 64" - nanoseconds + seconds packed into u64 (-1, 8) => { let packed = input.read_u64::<BigEndian>().err_span(span)?; let nanos = packed >> 34; let secs = packed & ((1 << 34) - 1); make_date(secs as i64, nanos as u32, span) } // "timestamp 96" - nanoseconds + seconds (-1, 12) => { let nanos = input.read_u32::<BigEndian>().err_span(span)?; let secs = input.read_i64::<BigEndian>().err_span(span)?; make_date(secs, nanos, span) } _ => Err(ShellError::GenericError { error: "Unknown MessagePack extension".into(), msg: format!("encountered extension type {ty}, length {len}"), span: Some(span), help: Some("only the timestamp extension (-1) is supported".into()), inner: vec![], } .into()), } } fn make_date(secs: i64, nanos: u32, span: Span) -> Result<Value, ReadError> { match Utc.timestamp_opt(secs, nanos) { chrono::offset::LocalResult::Single(dt) => Ok(Value::date(dt.into(), span)), _ => Err(ShellError::GenericError { error: "Invalid MessagePack timestamp".into(), msg: "datetime is out of supported range".into(), span: Some(span), help: Some("nanoseconds must be less than 1 billion".into()), inner: vec![], } .into()), } } fn from_int<T>(num: Result<T, std::io::Error>, span: Span) -> Result<Value, ReadError> where T: Into<i64>, { num.map(|num| Value::int(num.into(), span)) .map_err(|err| ReadError::Io(err, span)) } /// Return an error if this is not the end of file. /// /// This can help detect if parsing succeeded incorrectly, perhaps due to corruption. fn assert_eof(input: &mut impl io::Read, span: Span) -> Result<(), ShellError> { let mut buf = [0u8]; match input.read_exact(&mut buf) { // End of file Err(_) => Ok(()), // More bytes Ok(()) => Err(ShellError::GenericError { error: "Additional data after end of MessagePack object".into(), msg: "there was more data available after parsing".into(), span: Some(span), help: Some("this might be invalid data, but you can use `from msgpack --objects` to read multiple objects".into()), inner: vec![], }) } } #[cfg(test)] mod test { use nu_cmd_lang::eval_pipeline_without_terminal_expression; use crate::Reject; use crate::{Metadata, MetadataSet, ToMsgpack}; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromMsgpack {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(ToMsgpack {})); working_set.add_decl(Box::new(FromMsgpack {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#"{a: 1 b: 2} | to msgpack | metadata set --datasource-ls | from msgpack | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/command.rs
crates/nu-command/src/formats/from/command.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct From; impl Command for From { fn name(&self) -> &str { "from" } fn description(&self) -> &str { "Parse a string or binary data into structured data." } fn signature(&self) -> nu_protocol::Signature { Signature::build("from") .category(Category::Formats) .input_output_types(vec![(Type::Nothing, Type::String)]) } 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/formats/from/ods.rs
crates/nu-command/src/formats/from/ods.rs
use calamine::*; use indexmap::IndexMap; use nu_engine::command_prelude::*; use std::io::Cursor; #[derive(Clone)] pub struct FromOds; impl Command for FromOds { fn name(&self) -> &str { "from ods" } fn signature(&self) -> Signature { Signature::build("from ods") .input_output_types(vec![(Type::String, Type::table())]) .allow_variants_without_examples(true) .named( "sheets", SyntaxShape::List(Box::new(SyntaxShape::String)), "Only convert specified sheets", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Parse OpenDocument Spreadsheet(.ods) data and create table." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let sel_sheets = if let Some(Value::List { vals: columns, .. }) = call.get_flag(engine_state, stack, "sheets")? { convert_columns(columns.as_slice())? } else { vec![] }; let metadata = input.metadata().map(|md| md.with_content_type(None)); from_ods(input, head, sel_sheets).map(|pd| pd.set_metadata(metadata)) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert binary .ods data to a table", example: "open --raw test.ods | from ods", result: None, }, Example { description: "Convert binary .ods data to a table, specifying the tables", example: "open --raw test.ods | from ods --sheets [Spreadsheet1]", result: None, }, ] } } fn convert_columns(columns: &[Value]) -> Result<Vec<String>, ShellError> { let res = columns .iter() .map(|value| match &value { Value::String { val: s, .. } => Ok(s.clone()), _ => Err(ShellError::IncompatibleParametersSingle { msg: "Incorrect column format, Only string as column name".to_string(), span: value.span(), }), }) .collect::<Result<Vec<String>, _>>()?; Ok(res) } fn collect_binary(input: PipelineData, span: Span) -> Result<Vec<u8>, ShellError> { if let PipelineData::ByteStream(stream, ..) = input { stream.into_bytes() } else { let mut bytes = vec![]; let mut values = input.into_iter(); loop { match values.next() { Some(Value::Binary { val: b, .. }) => { bytes.extend_from_slice(&b); } Some(Value::Error { error, .. }) => return Err(*error), Some(x) => { return Err(ShellError::UnsupportedInput { msg: "Expected binary from pipeline".to_string(), input: "value originates from here".into(), msg_span: span, input_span: x.span(), }); } None => break, } } Ok(bytes) } } fn from_ods( input: PipelineData, head: Span, sel_sheets: Vec<String>, ) -> Result<PipelineData, ShellError> { let span = input.span(); let bytes = collect_binary(input, head)?; let buf: Cursor<Vec<u8>> = Cursor::new(bytes); let mut ods = Ods::<_>::new(buf).map_err(|_| ShellError::UnsupportedInput { msg: "Could not load ODS file".to_string(), input: "value originates from here".into(), msg_span: head, input_span: span.unwrap_or(head), })?; let mut dict = IndexMap::new(); let mut sheet_names = ods.sheet_names(); if !sel_sheets.is_empty() { sheet_names.retain(|e| sel_sheets.contains(e)); } for sheet_name in sheet_names { let mut sheet_output = vec![]; if let Ok(current_sheet) = ods.worksheet_range(&sheet_name) { for row in current_sheet.rows() { let record = row .iter() .enumerate() .map(|(i, cell)| { let value = match cell { Data::Empty => Value::nothing(head), Data::String(s) => Value::string(s, head), Data::Float(f) => Value::float(*f, head), Data::Int(i) => Value::int(*i, head), Data::Bool(b) => Value::bool(*b, head), _ => Value::nothing(head), }; (format!("column{i}"), value) }) .collect(); sheet_output.push(Value::record(record, head)); } dict.insert(sheet_name, Value::list(sheet_output, head)); } else { return Err(ShellError::UnsupportedInput { msg: "Could not load sheet".to_string(), input: "value originates from here".into(), msg_span: head, input_span: span.unwrap_or(head), }); } } Ok(PipelineData::value( Value::record(dict.into_iter().collect(), head), None, )) } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromOds {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/from/json.rs
crates/nu-command/src/formats/from/json.rs
use std::io::{BufRead, Cursor}; use nu_engine::command_prelude::*; use nu_protocol::{ListStream, Signals, shell_error::io::IoError}; #[derive(Clone)] pub struct FromJson; impl Command for FromJson { fn name(&self) -> &str { "from json" } fn description(&self) -> &str { "Convert from json to structured data." } fn signature(&self) -> nu_protocol::Signature { Signature::build("from json") .input_output_types(vec![(Type::String, Type::Any)]) .switch("objects", "treat each line as a separate value", Some('o')) .switch("strict", "follow the json specification exactly", Some('s')) .category(Category::Formats) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: r#"'{ "a": 1 }' | from json"#, description: "Converts json formatted string to table", result: Some(Value::test_record(record! { "a" => Value::test_int(1), })), }, Example { example: r#"'{ "a": 1, "b": [1, 2] }' | from json"#, description: "Converts json formatted string to table", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_list(vec![Value::test_int(1), Value::test_int(2)]), })), }, Example { example: r#"'{ "a": 1, "b": 2 }' | from json -s"#, description: "Parse json strictly which will error on comments and trailing commas", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_int(2), })), }, Example { example: r#"'{ "a": 1 } { "b": 2 }' | from json --objects"#, description: "Parse a stream of line-delimited JSON values", result: Some(Value::test_list(vec![ Value::test_record(record! {"a" => Value::test_int(1)}), Value::test_record(record! {"b" => Value::test_int(2)}), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; let strict = call.has_flag(engine_state, stack, "strict")?; let metadata = input.metadata().map(|md| md.with_content_type(None)); // TODO: turn this into a structured underline of the nu_json error if call.has_flag(engine_state, stack, "objects")? { // Return a stream of JSON values, one for each non-empty line match input { PipelineData::Value(Value::String { val, .. }, ..) => { Ok(PipelineData::list_stream( read_json_lines( Cursor::new(val), span, strict, engine_state.signals().clone(), ), metadata, )) } PipelineData::ByteStream(stream, ..) if stream.type_() != ByteStreamType::Binary => { if let Some(reader) = stream.reader() { Ok(PipelineData::list_stream( read_json_lines(reader, span, strict, Signals::empty()), metadata, )) } else { Ok(PipelineData::empty()) } } _ => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: input.get_type().to_string(), dst_span: call.head, src_span: input.span().unwrap_or(call.head), }), } } else { // Return a single JSON value let (string_input, span, ..) = input.collect_string_strict(span)?; if string_input.is_empty() { return Ok(Value::nothing(span).into_pipeline_data()); } if strict { Ok(convert_string_to_value_strict(&string_input, span)? .into_pipeline_data_with_metadata(metadata)) } else { Ok(convert_string_to_value(&string_input, span)? .into_pipeline_data_with_metadata(metadata)) } } } } /// Create a stream of values from a reader that produces line-delimited JSON fn read_json_lines( input: impl BufRead + Send + 'static, span: Span, strict: bool, signals: Signals, ) -> ListStream { let iter = input .lines() .filter(|line| line.as_ref().is_ok_and(|line| !line.trim().is_empty()) || line.is_err()) .map(move |line| { let line = line.map_err(|err| IoError::new(err, span, None))?; if strict { convert_string_to_value_strict(&line, span) } else { convert_string_to_value(&line, span) } }) .map(move |result| result.unwrap_or_else(|err| Value::error(err, span))); ListStream::new(iter, span, signals) } fn convert_nujson_to_value(value: nu_json::Value, span: Span) -> Value { match value { nu_json::Value::Array(array) => Value::list( array .into_iter() .map(|x| convert_nujson_to_value(x, span)) .collect(), span, ), nu_json::Value::Bool(b) => Value::bool(b, span), nu_json::Value::F64(f) => Value::float(f, span), nu_json::Value::I64(i) => Value::int(i, span), nu_json::Value::Null => Value::nothing(span), nu_json::Value::Object(k) => Value::record( k.into_iter() .map(|(k, v)| (k, convert_nujson_to_value(v, span))) .collect(), span, ), nu_json::Value::U64(u) => { if u > i64::MAX as u64 { Value::error( ShellError::CantConvert { to_type: "i64 sized integer".into(), from_type: "value larger than i64".into(), span, help: None, }, span, ) } else { Value::int(u as i64, span) } } nu_json::Value::String(s) => Value::string(s, span), } } pub(crate) fn convert_string_to_value(string_input: &str, span: Span) -> Result<Value, ShellError> { match nu_json::from_str(string_input) { Ok(value) => Ok(convert_nujson_to_value(value, span)), Err(x) => match x { nu_json::Error::Syntax(_, row, col) => { let label = x.to_string(); let label_span = Span::from_row_column(row, col, string_input); Err(ShellError::GenericError { error: "Error while parsing JSON text".into(), msg: "error parsing JSON text".into(), span: Some(span), help: None, inner: vec![ShellError::OutsideSpannedLabeledError { src: string_input.into(), error: "Error while parsing JSON text".into(), msg: label, span: label_span, }], }) } x => Err(ShellError::CantConvert { to_type: format!("structured json data ({x})"), from_type: "string".into(), span, help: None, }), }, } } fn convert_string_to_value_strict(string_input: &str, span: Span) -> Result<Value, ShellError> { match serde_json::from_str(string_input) { Ok(value) => Ok(convert_nujson_to_value(value, span)), Err(err) => Err(if err.is_syntax() { let label = err.to_string(); let label_span = Span::from_row_column(err.line(), err.column(), string_input); ShellError::GenericError { error: "Error while parsing JSON text".into(), msg: "error parsing JSON text".into(), span: Some(span), help: None, inner: vec![ShellError::OutsideSpannedLabeledError { src: string_input.into(), error: "Error while parsing JSON text".into(), msg: label, span: label_span, }], } } else { ShellError::CantConvert { to_type: format!("structured json data ({err})"), from_type: "string".into(), span, help: None, } }), } } #[cfg(test)] mod test { use nu_cmd_lang::eval_pipeline_without_terminal_expression; use crate::Reject; use crate::{Metadata, MetadataSet}; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromJson {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromJson {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#"'{"a":1,"b":2}' | metadata set --content-type 'application/json' --datasource-ls | from json | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/xml.rs
crates/nu-command/src/formats/from/xml.rs
use crate::formats::nu_xml_format::{COLUMN_ATTRS_NAME, COLUMN_CONTENT_NAME, COLUMN_TAG_NAME}; use indexmap::IndexMap; use nu_engine::command_prelude::*; use roxmltree::{NodeType, ParsingOptions, TextPos}; #[derive(Clone)] pub struct FromXml; impl Command for FromXml { fn name(&self) -> &str { "from xml" } fn signature(&self) -> Signature { Signature::build("from xml") .input_output_types(vec![(Type::String, Type::record())]) .switch("keep-comments", "add comment nodes to result", None) .switch( "allow-dtd", "allow parsing documents with DTDs (may result in exponential entity expansion)", None, ) .switch( "keep-pi", "add processing instruction nodes to result", None, ) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as .xml and create record." } fn extra_description(&self) -> &str { r#"Every XML entry is represented via a record with tag, attribute and content fields. To represent different types of entries different values are written to this fields: 1. Tag entry: `{tag: <tag name> attrs: {<attr name>: "<string value>" ...} content: [<entries>]}` 2. Comment entry: `{tag: '!' attrs: null content: "<comment string>"}` 3. Processing instruction (PI): `{tag: '?<pi name>' attrs: null content: "<pi content string>"}` 4. Text: `{tag: null attrs: null content: "<text>"}`. Unlike to xml command all null values are always present and text is never represented via plain string. This way content of every tag is always a table and is easier to parse"# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let keep_comments = call.has_flag(engine_state, stack, "keep-comments")?; let keep_processing_instructions = call.has_flag(engine_state, stack, "keep-pi")?; let allow_dtd = call.has_flag(engine_state, stack, "allow-dtd")?; let info = ParsingInfo { span: head, keep_comments, keep_processing_instructions, allow_dtd, }; from_xml(input, &info) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: r#"'<?xml version="1.0" encoding="UTF-8"?> <note> <remember>Event</remember> </note>' | from xml"#, description: "Converts xml formatted string to record", result: Some(Value::test_record(record! { COLUMN_TAG_NAME => Value::test_string("note"), COLUMN_ATTRS_NAME => Value::test_record(Record::new()), COLUMN_CONTENT_NAME => Value::test_list(vec![ Value::test_record(record! { COLUMN_TAG_NAME => Value::test_string("remember"), COLUMN_ATTRS_NAME => Value::test_record(Record::new()), COLUMN_CONTENT_NAME => Value::test_list(vec![ Value::test_record(record! { COLUMN_TAG_NAME => Value::test_nothing(), COLUMN_ATTRS_NAME => Value::test_nothing(), COLUMN_CONTENT_NAME => Value::test_string("Event"), })], ), })], ), })), }] } } struct ParsingInfo { span: Span, keep_comments: bool, keep_processing_instructions: bool, allow_dtd: bool, } fn from_attributes_to_value(attributes: &[roxmltree::Attribute], info: &ParsingInfo) -> Value { let mut collected = IndexMap::new(); for a in attributes { collected.insert(String::from(a.name()), Value::string(a.value(), info.span)); } Value::record(collected.into_iter().collect(), info.span) } fn element_to_value(n: &roxmltree::Node, info: &ParsingInfo) -> Value { let span = info.span; let mut node = IndexMap::new(); let tag = n.tag_name().name().trim().to_string(); let tag = Value::string(tag, span); let content: Vec<Value> = n .children() .filter_map(|node| from_node_to_value(&node, info)) .collect(); let content = Value::list(content, span); let attributes = from_attributes_to_value(&n.attributes().collect::<Vec<_>>(), info); node.insert(String::from(COLUMN_TAG_NAME), tag); node.insert(String::from(COLUMN_ATTRS_NAME), attributes); node.insert(String::from(COLUMN_CONTENT_NAME), content); Value::record(node.into_iter().collect(), span) } fn text_to_value(n: &roxmltree::Node, info: &ParsingInfo) -> Option<Value> { let span = info.span; let text = n.text().expect("Non-text node supplied to text_to_value"); let text = text.trim(); if text.is_empty() { None } else { let mut node = IndexMap::new(); let content = Value::string(String::from(text), span); node.insert(String::from(COLUMN_TAG_NAME), Value::nothing(span)); node.insert(String::from(COLUMN_ATTRS_NAME), Value::nothing(span)); node.insert(String::from(COLUMN_CONTENT_NAME), content); Some(Value::record(node.into_iter().collect(), span)) } } fn comment_to_value(n: &roxmltree::Node, info: &ParsingInfo) -> Option<Value> { if info.keep_comments { let span = info.span; let text = n .text() .expect("Non-comment node supplied to comment_to_value"); let mut node = IndexMap::new(); let content = Value::string(String::from(text), span); node.insert(String::from(COLUMN_TAG_NAME), Value::string("!", span)); node.insert(String::from(COLUMN_ATTRS_NAME), Value::nothing(span)); node.insert(String::from(COLUMN_CONTENT_NAME), content); Some(Value::record(node.into_iter().collect(), span)) } else { None } } fn processing_instruction_to_value(n: &roxmltree::Node, info: &ParsingInfo) -> Option<Value> { if info.keep_processing_instructions { let span = info.span; let pi = n.pi()?; let mut node = IndexMap::new(); // Add '?' before target to differentiate tags from pi targets let tag = format!("?{}", pi.target); let tag = Value::string(tag, span); let content = pi .value .map_or_else(|| Value::nothing(span), |x| Value::string(x, span)); node.insert(String::from(COLUMN_TAG_NAME), tag); node.insert(String::from(COLUMN_ATTRS_NAME), Value::nothing(span)); node.insert(String::from(COLUMN_CONTENT_NAME), content); Some(Value::record(node.into_iter().collect(), span)) } else { None } } fn from_node_to_value(n: &roxmltree::Node, info: &ParsingInfo) -> Option<Value> { match n.node_type() { NodeType::Element => Some(element_to_value(n, info)), NodeType::Text => text_to_value(n, info), NodeType::Comment => comment_to_value(n, info), NodeType::PI => processing_instruction_to_value(n, info), _ => None, } } fn from_document_to_value(d: &roxmltree::Document, info: &ParsingInfo) -> Value { element_to_value(&d.root_element(), info) } fn from_xml_string_to_value(s: &str, info: &ParsingInfo) -> Result<Value, roxmltree::Error> { let options = ParsingOptions { allow_dtd: info.allow_dtd, ..Default::default() }; let parsed = roxmltree::Document::parse_with_options(s, options)?; Ok(from_document_to_value(&parsed, info)) } fn from_xml(input: PipelineData, info: &ParsingInfo) -> Result<PipelineData, ShellError> { let (concat_string, span, metadata) = input.collect_string_strict(info.span)?; match from_xml_string_to_value(&concat_string, info) { Ok(x) => { Ok(x.into_pipeline_data_with_metadata(metadata.map(|md| md.with_content_type(None)))) } Err(err) => Err(process_xml_parse_error(concat_string, err, span)), } } fn process_xml_parse_error(source: String, err: roxmltree::Error, span: Span) -> ShellError { match err { roxmltree::Error::InvalidXmlPrefixUri(pos) => make_xml_error_spanned( "The `xmlns:xml` attribute must have an <http://www.w3.org/XML/1998/namespace> URI.", source, pos, ), roxmltree::Error::UnexpectedXmlUri(pos) => make_xml_error_spanned( "Only the xmlns:xml attribute can have the http://www.w3.org/XML/1998/namespace URI.", source, pos, ), roxmltree::Error::UnexpectedXmlnsUri(pos) => make_xml_error_spanned( "The http://www.w3.org/2000/xmlns/ URI must not be declared.", source, pos, ), roxmltree::Error::InvalidElementNamePrefix(pos) => { make_xml_error_spanned("xmlns can't be used as an element prefix.", source, pos) } roxmltree::Error::DuplicatedNamespace(namespace, pos) => make_xml_error_spanned( format!("Namespace {namespace} was already defined on this element."), source, pos, ), roxmltree::Error::UnknownNamespace(prefix, pos) => { make_xml_error_spanned(format!("Unknown prefix {prefix}"), source, pos) } roxmltree::Error::UnexpectedCloseTag(expected, actual, pos) => make_xml_error_spanned( format!("Unexpected close tag {actual}, expected {expected}"), source, pos, ), roxmltree::Error::UnexpectedEntityCloseTag(pos) => { make_xml_error_spanned("Entity value starts with a close tag.", source, pos) } roxmltree::Error::UnknownEntityReference(entity, pos) => make_xml_error_spanned( format!("Reference to unknown entity {entity} (was not defined in the DTD)"), source, pos, ), roxmltree::Error::MalformedEntityReference(pos) => { make_xml_error_spanned("Malformed entity reference.", source, pos) } roxmltree::Error::EntityReferenceLoop(pos) => { make_xml_error_spanned("Possible entity reference loop.", source, pos) } roxmltree::Error::InvalidAttributeValue(pos) => { make_xml_error_spanned("Attribute value cannot have a < character.", source, pos) } roxmltree::Error::DuplicatedAttribute(attribute, pos) => make_xml_error_spanned( format!("Element has a duplicated attribute: {attribute}"), source, pos, ), roxmltree::Error::NoRootNode => { make_xml_error("The XML document must have at least one element.", span) } roxmltree::Error::UnclosedRootNode => { make_xml_error("The root node was opened but never closed.", span) } roxmltree::Error::DtdDetected => make_xml_error( "XML document with DTD detected.\nDTDs are disabled by default to prevent denial-of-service attacks (use --allow-dtd to parse anyway)", span, ), roxmltree::Error::NodesLimitReached => make_xml_error("Node limit was reached.", span), roxmltree::Error::AttributesLimitReached => make_xml_error("Attribute limit reached", span), roxmltree::Error::NamespacesLimitReached => make_xml_error("Namespace limit reached", span), roxmltree::Error::UnexpectedDeclaration(pos) => make_xml_error_spanned( "An XML document can have only one XML declaration and it must be at the start of the document.", source, pos, ), roxmltree::Error::InvalidName(pos) => make_xml_error_spanned("Invalid name.", source, pos), roxmltree::Error::NonXmlChar(_, pos) => make_xml_error_spanned( "Non-XML character found. Valid characters are: <https://www.w3.org/TR/xml/#char32>", source, pos, ), roxmltree::Error::InvalidChar(expected, actual, pos) => make_xml_error_spanned( format!( "Unexpected character {}, expected {}", actual as char, expected as char ), source, pos, ), roxmltree::Error::InvalidChar2(expected, actual, pos) => make_xml_error_spanned( format!( "Unexpected character {}, expected {}", actual as char, expected ), source, pos, ), roxmltree::Error::InvalidString(_, pos) => { make_xml_error_spanned("Invalid/unexpected string in XML.", source, pos) } roxmltree::Error::InvalidExternalID(pos) => { make_xml_error_spanned("Invalid ExternalID in the DTD.", source, pos) } roxmltree::Error::InvalidComment(pos) => make_xml_error_spanned( "A comment cannot contain `--` or end with `-`.", source, pos, ), roxmltree::Error::InvalidCharacterData(pos) => make_xml_error_spanned( "Character Data node contains an invalid data. Currently, only `]]>` is not allowed.", source, pos, ), roxmltree::Error::UnknownToken(pos) => { make_xml_error_spanned("Unknown token in XML.", source, pos) } roxmltree::Error::UnexpectedEndOfStream => { make_xml_error("Unexpected end of stream while parsing XML.", span) } } } fn make_xml_error(msg: impl Into<String>, span: Span) -> ShellError { ShellError::GenericError { error: "Failed to parse XML".into(), msg: msg.into(), help: None, span: Some(span), inner: vec![], } } fn make_xml_error_spanned(msg: impl Into<String>, src: String, pos: TextPos) -> ShellError { let span = Span::from_row_column(pos.row as usize, pos.col as usize, &src); ShellError::OutsideSpannedLabeledError { src, error: "Failed to parse XML".into(), msg: msg.into(), span, } } #[cfg(test)] mod tests { use crate::Metadata; use crate::MetadataSet; use crate::Reject; use super::*; use indexmap::IndexMap; use indexmap::indexmap; use nu_cmd_lang::eval_pipeline_without_terminal_expression; fn string(input: impl Into<String>) -> Value { Value::test_string(input) } fn attributes(entries: IndexMap<&str, &str>) -> Value { Value::test_record( entries .into_iter() .map(|(k, v)| (k.into(), string(v))) .collect(), ) } fn table(list: &[Value]) -> Value { Value::list(list.to_vec(), Span::test_data()) } fn content_tag( tag: impl Into<String>, attrs: IndexMap<&str, &str>, content: &[Value], ) -> Value { Value::test_record(record! { COLUMN_TAG_NAME => string(tag), COLUMN_ATTRS_NAME => attributes(attrs), COLUMN_CONTENT_NAME => table(content), }) } fn content_string(value: impl Into<String>) -> Value { Value::test_record(record! { COLUMN_TAG_NAME => Value::nothing(Span::test_data()), COLUMN_ATTRS_NAME => Value::nothing(Span::test_data()), COLUMN_CONTENT_NAME => string(value), }) } fn parse(xml: &str) -> Result<Value, roxmltree::Error> { let info = ParsingInfo { span: Span::test_data(), keep_comments: false, keep_processing_instructions: false, allow_dtd: false, }; from_xml_string_to_value(xml, &info) } #[test] fn parses_empty_element() -> Result<(), roxmltree::Error> { let source = "<nu></nu>"; assert_eq!(parse(source)?, content_tag("nu", indexmap! {}, &[])); Ok(()) } #[test] fn parses_element_with_text() -> Result<(), roxmltree::Error> { let source = "<nu>La era de los tres caballeros</nu>"; assert_eq!( parse(source)?, content_tag( "nu", indexmap! {}, &[content_string("La era de los tres caballeros")] ) ); Ok(()) } #[test] fn parses_element_with_elements() -> Result<(), roxmltree::Error> { let source = "\ <nu> <dev>Andrés</dev> <dev>JT</dev> <dev>Yehuda</dev> </nu>"; assert_eq!( parse(source)?, content_tag( "nu", indexmap! {}, &[ content_tag("dev", indexmap! {}, &[content_string("Andrés")]), content_tag("dev", indexmap! {}, &[content_string("JT")]), content_tag("dev", indexmap! {}, &[content_string("Yehuda")]) ] ) ); Ok(()) } #[test] fn parses_element_with_attribute() -> Result<(), roxmltree::Error> { let source = "\ <nu version=\"2.0\"> </nu>"; assert_eq!( parse(source)?, content_tag("nu", indexmap! {"version" => "2.0"}, &[]) ); Ok(()) } #[test] fn parses_element_with_attribute_and_element() -> Result<(), roxmltree::Error> { let source = "\ <nu version=\"2.0\"> <version>2.0</version> </nu>"; assert_eq!( parse(source)?, content_tag( "nu", indexmap! {"version" => "2.0"}, &[content_tag( "version", indexmap! {}, &[content_string("2.0")] )] ) ); Ok(()) } #[test] fn parses_element_with_multiple_attributes() -> Result<(), roxmltree::Error> { let source = "\ <nu version=\"2.0\" age=\"25\"> </nu>"; assert_eq!( parse(source)?, content_tag("nu", indexmap! {"version" => "2.0", "age" => "25"}, &[]) ); Ok(()) } #[test] fn test_examples() { use crate::test_examples; test_examples(FromXml {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromXml {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#"'<?xml version="1.0" encoding="UTF-8"?> <note> <remember>Event</remember> </note>' | metadata set --content-type 'application/xml' --datasource-ls | from xml | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/msgpackz.rs
crates/nu-command/src/formats/from/msgpackz.rs
use std::io::Cursor; use nu_engine::command_prelude::*; use super::msgpack::{Opts, read_msgpack}; const BUFFER_SIZE: usize = 65536; #[derive(Clone)] pub struct FromMsgpackz; impl Command for FromMsgpackz { fn name(&self) -> &str { "from msgpackz" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Binary, Type::Any) .switch("objects", "Read multiple objects from input", None) .category(Category::Formats) } fn description(&self) -> &str { "Convert brotli-compressed MessagePack data into Nu values." } fn extra_description(&self) -> &str { "This is the format used by the plugin registry file ($nu.plugin-path)." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = input.span().unwrap_or(call.head); let objects = call.has_flag(engine_state, stack, "objects")?; let opts = Opts { span, objects, signals: engine_state.signals().clone(), }; let metadata = input.metadata().map(|md| md.with_content_type(None)); let out = match input { // Deserialize from a byte buffer PipelineData::Value(Value::Binary { val: bytes, .. }, _) => { let reader = brotli::Decompressor::new(Cursor::new(bytes), BUFFER_SIZE); read_msgpack(reader, opts) } // Deserialize from a raw stream directly without having to collect it PipelineData::ByteStream(stream, ..) => { let span = stream.span(); if let Some(reader) = stream.reader() { let reader = brotli::Decompressor::new(reader, BUFFER_SIZE); read_msgpack(reader, opts) } else { Err(ShellError::PipelineMismatch { exp_input_type: "binary or byte stream".into(), dst_span: call.head, src_span: span, }) } } _ => Err(ShellError::PipelineMismatch { exp_input_type: "binary or byte stream".into(), dst_span: call.head, src_span: span, }), }; out.map(|pd| pd.set_metadata(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/from/tsv.rs
crates/nu-command/src/formats/from/tsv.rs
use super::delimited::{DelimitedReaderConfig, from_delimited_data, trim_from_str}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct FromTsv; impl Command for FromTsv { fn name(&self) -> &str { "from tsv" } fn signature(&self) -> Signature { Signature::build("from tsv") .input_output_types(vec![(Type::String, Type::table())]) .named( "comment", SyntaxShape::String, "a comment character to ignore lines starting with it", Some('c'), ) .named( "quote", SyntaxShape::String, "a quote character to ignore separators in strings, defaults to '\"'", Some('q'), ) .named( "escape", SyntaxShape::String, "an escape character for strings containing the quote character", Some('e'), ) .switch( "noheaders", "don't treat the first row as column names", Some('n'), ) .switch( "flexible", "allow the number of fields in records to be variable", None, ) .switch("no-infer", "no field type inferencing", None) .param( Flag::new("trim") .short('t') .arg(SyntaxShape::String) .desc( "drop leading and trailing whitespaces around headers names and/or field \ values", ) .completion(Completion::new_list(&["all", "fields", "headers", "none"])), ) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as .tsv and create table." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { from_tsv(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert tab-separated data to a table", example: "\"ColA\tColB\n1\t2\" | from tsv", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_int(1), "ColB" => Value::test_int(2), })])), }, Example { description: "Convert comma-separated data to a table, allowing variable number of columns per row and ignoring headers", example: "\"value 1\nvalue 2\tdescription 2\" | from tsv --flexible --noheaders", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("value 1"), }), Value::test_record(record! { "column0" => Value::test_string("value 2"), "column1" => Value::test_string("description 2"), }), ])), }, Example { description: "Create a tsv file with header columns and open it", example: r#"$'c1(char tab)c2(char tab)c3(char nl)1(char tab)2(char tab)3' | save tsv-data | open tsv-data | from tsv"#, result: None, }, Example { description: "Create a tsv file without header columns and open it", example: r#"$'a1(char tab)b1(char tab)c1(char nl)a2(char tab)b2(char tab)c2' | save tsv-data | open tsv-data | from tsv --noheaders"#, result: None, }, Example { description: "Create a tsv file without header columns and open it, removing all unnecessary whitespaces", example: r#"$'a1(char tab)b1(char tab)c1(char nl)a2(char tab)b2(char tab)c2' | save tsv-data | open tsv-data | from tsv --trim all"#, result: None, }, Example { description: "Create a tsv file without header columns and open it, removing all unnecessary whitespaces in the header names", example: r#"$'a1(char tab)b1(char tab)c1(char nl)a2(char tab)b2(char tab)c2' | save tsv-data | open tsv-data | from tsv --trim headers"#, result: None, }, Example { description: "Create a tsv file without header columns and open it, removing all unnecessary whitespaces in the field values", example: r#"$'a1(char tab)b1(char tab)c1(char nl)a2(char tab)b2(char tab)c2' | save tsv-data | open tsv-data | from tsv --trim fields"#, result: None, }, ] } } fn from_tsv( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let name = call.head; let comment = call .get_flag(engine_state, stack, "comment")? .map(|v: Value| v.as_char()) .transpose()?; let quote = call .get_flag(engine_state, stack, "quote")? .map(|v: Value| v.as_char()) .transpose()? .unwrap_or('"'); let escape = call .get_flag(engine_state, stack, "escape")? .map(|v: Value| v.as_char()) .transpose()?; let no_infer = call.has_flag(engine_state, stack, "no-infer")?; let noheaders = call.has_flag(engine_state, stack, "noheaders")?; let flexible = call.has_flag(engine_state, stack, "flexible")?; let trim = trim_from_str(call.get_flag(engine_state, stack, "trim")?)?; let config = DelimitedReaderConfig { separator: '\t', comment, quote, escape, noheaders, flexible, no_infer, trim, }; from_delimited_data(config, input, name) } #[cfg(test)] mod test { use nu_cmd_lang::eval_pipeline_without_terminal_expression; use crate::Reject; use crate::{Metadata, MetadataSet}; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(FromTsv {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromTsv {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#""a\tb\n1\t2" | metadata set --content-type 'text/tab-separated-values' --datasource-ls | from tsv | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/mod.rs
crates/nu-command/src/formats/from/mod.rs
mod command; mod csv; mod delimited; mod json; mod msgpack; mod msgpackz; mod nuon; mod ods; mod ssv; mod toml; mod tsv; mod xlsx; mod xml; mod yaml; pub use self::csv::FromCsv; pub use self::toml::FromToml; pub use command::From; pub use json::FromJson; pub use msgpack::FromMsgpack; pub use msgpackz::FromMsgpackz; pub use nuon::FromNuon; pub use ods::FromOds; pub use ssv::FromSsv; pub use tsv::FromTsv; pub use xlsx::FromXlsx; pub use xml::FromXml; pub use yaml::FromYaml; pub use yaml::FromYml; #[cfg(feature = "sqlite")] pub(crate) use json::convert_string_to_value as convert_json_string_to_value;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/from/yaml.rs
crates/nu-command/src/formats/from/yaml.rs
use indexmap::IndexMap; use itertools::Itertools; use nu_engine::command_prelude::*; use serde::de::Deserialize; #[derive(Clone)] pub struct FromYaml; impl Command for FromYaml { fn name(&self) -> &str { "from yaml" } fn signature(&self) -> Signature { Signature::build("from yaml") .input_output_types(vec![(Type::String, Type::Any)]) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as .yaml/.yml and create table." } fn examples(&self) -> Vec<Example<'_>> { get_examples() } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; from_yaml(input, head) } } #[derive(Clone)] pub struct FromYml; impl Command for FromYml { fn name(&self) -> &str { "from yml" } fn signature(&self) -> Signature { Signature::build("from yml") .input_output_types(vec![(Type::String, Type::Any)]) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as .yaml/.yml and create table." } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; from_yaml(input, head) } fn examples(&self) -> Vec<Example<'_>> { get_examples() } } fn convert_yaml_value_to_nu_value( v: &serde_yaml::Value, span: Span, val_span: Span, ) -> Result<Value, ShellError> { let err_not_compatible_number = ShellError::UnsupportedInput { msg: "Expected a nu-compatible number in YAML input".to_string(), input: "value originates from here".into(), msg_span: span, input_span: val_span, }; Ok(match v { serde_yaml::Value::Bool(b) => Value::bool(*b, span), serde_yaml::Value::Number(n) if n.is_i64() => { Value::int(n.as_i64().ok_or(err_not_compatible_number)?, span) } serde_yaml::Value::Number(n) if n.is_f64() => { Value::float(n.as_f64().ok_or(err_not_compatible_number)?, span) } serde_yaml::Value::String(s) => Value::string(s.to_string(), span), serde_yaml::Value::Sequence(a) => { let result: Result<Vec<Value>, ShellError> = a .iter() .map(|x| convert_yaml_value_to_nu_value(x, span, val_span)) .collect(); Value::list(result?, span) } serde_yaml::Value::Mapping(t) => { // Using an IndexMap ensures consistent ordering let mut collected = IndexMap::new(); for (k, v) in t { // A ShellError that we re-use multiple times in the Mapping scenario let err_unexpected_map = ShellError::UnsupportedInput { msg: format!("Unexpected YAML:\nKey: {k:?}\nValue: {v:?}"), input: "value originates from here".into(), msg_span: span, input_span: val_span, }; match (k, v) { (serde_yaml::Value::Number(k), _) => { collected.insert( k.to_string(), convert_yaml_value_to_nu_value(v, span, val_span)?, ); } (serde_yaml::Value::Bool(k), _) => { collected.insert( k.to_string(), convert_yaml_value_to_nu_value(v, span, val_span)?, ); } (serde_yaml::Value::String(k), _) => { collected.insert( k.clone(), convert_yaml_value_to_nu_value(v, span, val_span)?, ); } // Hard-code fix for cases where "v" is a string without quotations with double curly braces // e.g. k = value // value: {{ something }} // Strangely, serde_yaml returns // "value" -> Mapping(Mapping { map: {Mapping(Mapping { map: {String("something"): Null} }): Null} }) (serde_yaml::Value::Mapping(m), serde_yaml::Value::Null) => { return m .iter() .take(1) .collect_vec() .first() .and_then(|e| match e { (serde_yaml::Value::String(s), serde_yaml::Value::Null) => { Some(Value::string("{{ ".to_owned() + s.as_str() + " }}", span)) } _ => None, }) .ok_or(err_unexpected_map); } (_, _) => { return Err(err_unexpected_map); } } } Value::record(collected.into_iter().collect(), span) } serde_yaml::Value::Tagged(t) => { let tag = &t.tag; match &t.value { serde_yaml::Value::String(s) => { let val = format!("{tag} {s}").trim().to_string(); Value::string(val, span) } serde_yaml::Value::Number(n) => { let val = format!("{tag} {n}").trim().to_string(); Value::string(val, span) } serde_yaml::Value::Bool(b) => { let val = format!("{tag} {b}").trim().to_string(); Value::string(val, span) } serde_yaml::Value::Null => { let val = format!("{tag}").trim().to_string(); Value::string(val, span) } v => convert_yaml_value_to_nu_value(v, span, val_span)?, } } serde_yaml::Value::Null => Value::nothing(span), x => unimplemented!("Unsupported YAML case: {:?}", x), }) } pub fn from_yaml_string_to_value(s: &str, span: Span, val_span: Span) -> Result<Value, ShellError> { let mut documents = vec![]; for document in serde_yaml::Deserializer::from_str(s) { let v: serde_yaml::Value = serde_yaml::Value::deserialize(document).map_err(|x| ShellError::UnsupportedInput { msg: format!("Could not load YAML: {x}"), input: "value originates from here".into(), msg_span: span, input_span: val_span, })?; documents.push(convert_yaml_value_to_nu_value(&v, span, val_span)?); } match documents.len() { 0 => Ok(Value::nothing(span)), 1 => Ok(documents.remove(0)), _ => Ok(Value::list(documents, span)), } } pub fn get_examples() -> Vec<Example<'static>> { vec![ Example { example: "'a: 1' | from yaml", description: "Converts yaml formatted string to table", result: Some(Value::test_record(record! { "a" => Value::test_int(1), })), }, Example { example: "'[ a: 1, b: [1, 2] ]' | from yaml", description: "Converts yaml formatted string to table", result: Some(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_int(1), }), Value::test_record(record! { "b" => Value::test_list( vec![Value::test_int(1), Value::test_int(2)],), }), ])), }, ] } fn from_yaml(input: PipelineData, head: Span) -> Result<PipelineData, ShellError> { let (concat_string, span, metadata) = input.collect_string_strict(head)?; match from_yaml_string_to_value(&concat_string, head, span) { Ok(x) => { Ok(x.into_pipeline_data_with_metadata(metadata.map(|md| md.with_content_type(None)))) } Err(other) => Err(other), } } #[cfg(test)] mod test { use crate::Reject; use crate::{Metadata, MetadataSet}; use super::*; use nu_cmd_lang::eval_pipeline_without_terminal_expression; use nu_protocol::Config; #[test] fn test_problematic_yaml() { struct TestCase { description: &'static str, input: &'static str, expected: Result<Value, ShellError>, } let tt: Vec<TestCase> = vec![ TestCase { description: "Double Curly Braces With Quotes", input: r#"value: "{{ something }}""#, expected: Ok(Value::test_record(record! { "value" => Value::test_string("{{ something }}"), })), }, TestCase { description: "Double Curly Braces Without Quotes", input: r#"value: {{ something }}"#, expected: Ok(Value::test_record(record! { "value" => Value::test_string("{{ something }}"), })), }, ]; let config = Config::default(); for tc in tt { let actual = from_yaml_string_to_value(tc.input, Span::test_data(), Span::test_data()); if actual.is_err() { assert!( tc.expected.is_err(), "actual is Err for test:\nTest Description {}\nErr: {:?}", tc.description, actual ); } else { assert_eq!( actual.unwrap().to_expanded_string("", &config), tc.expected.unwrap().to_expanded_string("", &config) ); } } } #[test] fn test_examples() { use crate::test_examples; test_examples(FromYaml {}) } #[test] fn test_consistent_mapping_ordering() { let test_yaml = "- a: b b: c - a: g b: h"; // Before the fix this test is verifying, the ordering of columns in the resulting // table was non-deterministic. It would take a few executions of the YAML conversion to // see this ordering difference. This loop should be far more than enough to catch a regression. for ii in 1..1000 { let actual = from_yaml_string_to_value(test_yaml, Span::test_data(), Span::test_data()); let expected: Result<Value, ShellError> = Ok(Value::test_list(vec![ Value::test_record(record! { "a" => Value::test_string("b"), "b" => Value::test_string("c"), }), Value::test_record(record! { "a" => Value::test_string("g"), "b" => Value::test_string("h"), }), ])); // Unfortunately the eq function for Value doesn't compare well enough to detect // ordering errors in List columns or values. assert!(actual.is_ok()); let actual = actual.ok().unwrap(); let expected = expected.ok().unwrap(); let actual_vals = actual.as_list().unwrap(); let expected_vals = expected.as_list().unwrap(); assert_eq!(expected_vals.len(), actual_vals.len(), "iteration {ii}"); for jj in 0..expected_vals.len() { let actual_record = actual_vals[jj].as_record().unwrap(); let expected_record = expected_vals[jj].as_record().unwrap(); let actual_columns = actual_record.columns(); let expected_columns = expected_record.columns(); assert!( expected_columns.eq(actual_columns), "record {jj}, iteration {ii}" ); let actual_vals = actual_record.values(); let expected_vals = expected_record.values(); assert!(expected_vals.eq(actual_vals), "record {jj}, iteration {ii}") } } } #[test] fn test_convert_yaml_value_to_nu_value_for_tagged_values() { struct TestCase { input: &'static str, expected: Result<Value, ShellError>, } let test_cases: Vec<TestCase> = vec![ TestCase { input: "Key: !Value ${TEST}-Test-role", expected: Ok(Value::test_record(record! { "Key" => Value::test_string("!Value ${TEST}-Test-role"), })), }, TestCase { input: "Key: !Value test-${TEST}", expected: Ok(Value::test_record(record! { "Key" => Value::test_string("!Value test-${TEST}"), })), }, TestCase { input: "Key: !Value", expected: Ok(Value::test_record(record! { "Key" => Value::test_string("!Value"), })), }, TestCase { input: "Key: !True", expected: Ok(Value::test_record(record! { "Key" => Value::test_string("!True"), })), }, TestCase { input: "Key: !123", expected: Ok(Value::test_record(record! { "Key" => Value::test_string("!123"), })), }, ]; for test_case in test_cases { let doc = serde_yaml::Deserializer::from_str(test_case.input); let v: serde_yaml::Value = serde_yaml::Value::deserialize(doc.last().unwrap()).unwrap(); let result = convert_yaml_value_to_nu_value(&v, Span::test_data(), Span::test_data()); assert!(result.is_ok()); assert!(result.ok().unwrap() == test_case.expected.ok().unwrap()); } } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromYaml {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#""a: 1\nb: 2" | metadata set --content-type 'application/yaml' --datasource-ls | from yaml | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/csv.rs
crates/nu-command/src/formats/from/csv.rs
use super::delimited::{DelimitedReaderConfig, from_delimited_data, trim_from_str}; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct FromCsv; impl Command for FromCsv { fn name(&self) -> &str { "from csv" } fn signature(&self) -> Signature { Signature::build("from csv") .input_output_types(vec![ (Type::String, Type::table()), ]) .named( "separator", SyntaxShape::String, "a character to separate columns (either single char or 4 byte unicode sequence), defaults to ','", Some('s'), ) .named( "comment", SyntaxShape::String, "a comment character to ignore lines starting with it", Some('c'), ) .named( "quote", SyntaxShape::String, "a quote character to ignore separators in strings, defaults to '\"'", Some('q'), ) .named( "escape", SyntaxShape::String, "an escape character for strings containing the quote character", Some('e'), ) .switch( "noheaders", "don't treat the first row as column names", Some('n'), ) .switch( "flexible", "allow the number of fields in records to be variable", None, ) .switch("no-infer", "no field type inferencing", None) .param( Flag::new("trim") .short('t') .arg(SyntaxShape::String) .desc( "drop leading and trailing whitespaces around headers names and/or field \ values", ) .completion(Completion::new_list(&["all", "fields", "headers", "none"])), ) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as .csv and create table." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { from_csv(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert comma-separated data to a table", example: "\"ColA,ColB\n1,2\" | from csv", result: Some(Value::test_list(vec![Value::test_record(record! { "ColA" => Value::test_int(1), "ColB" => Value::test_int(2), })])), }, Example { description: "Convert comma-separated data to a table, allowing variable number of columns per row", example: "\"ColA,ColB\n1,2\n3,4,5\n6\" | from csv --flexible", result: Some(Value::test_list(vec![ Value::test_record(record! { "ColA" => Value::test_int(1), "ColB" => Value::test_int(2), }), Value::test_record(record! { "ColA" => Value::test_int(3), "ColB" => Value::test_int(4), "column2" => Value::test_int(5), }), Value::test_record(record! { "ColA" => Value::test_int(6), }), ])), }, Example { description: "Convert comma-separated data to a table, ignoring headers", example: "open data.txt | from csv --noheaders", result: None, }, Example { description: "Convert semicolon-separated data to a table", example: "open data.txt | from csv --separator ';'", result: None, }, Example { description: "Convert comma-separated data to a table, ignoring lines starting with '#'", example: "open data.txt | from csv --comment '#'", result: None, }, Example { description: "Convert comma-separated data to a table, dropping all possible whitespaces around header names and field values", example: "open data.txt | from csv --trim all", result: None, }, Example { description: "Convert comma-separated data to a table, dropping all possible whitespaces around header names", example: "open data.txt | from csv --trim headers", result: None, }, Example { description: "Convert comma-separated data to a table, dropping all possible whitespaces around field values", example: "open data.txt | from csv --trim fields", result: None, }, ] } } fn from_csv( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let name = call.head; if let PipelineData::Value(Value::List { .. }, _) = input { return Err(ShellError::TypeMismatch { err_message: "received list stream, did you forget to open file with --raw flag?" .into(), span: name, }); } let separator = match call.get_flag::<String>(engine_state, stack, "separator")? { Some(sep) => { if sep.len() == 1 { sep.chars().next().unwrap_or(',') } else if sep.len() == 4 { let unicode_sep = u32::from_str_radix(&sep, 16); char::from_u32(unicode_sep.unwrap_or(b'\x1f' as u32)).unwrap_or(',') } else { return Err(ShellError::NonUtf8Custom { msg: "separator should be a single char or a 4-byte unicode".into(), span: call.span(), }); } } None => ',', }; let comment = call .get_flag(engine_state, stack, "comment")? .map(|v: Value| v.as_char()) .transpose()?; let quote = call .get_flag(engine_state, stack, "quote")? .map(|v: Value| v.as_char()) .transpose()? .unwrap_or('"'); let escape = call .get_flag(engine_state, stack, "escape")? .map(|v: Value| v.as_char()) .transpose()?; let no_infer = call.has_flag(engine_state, stack, "no-infer")?; let noheaders = call.has_flag(engine_state, stack, "noheaders")?; let flexible = call.has_flag(engine_state, stack, "flexible")?; let trim = trim_from_str(call.get_flag(engine_state, stack, "trim")?)?; let config = DelimitedReaderConfig { separator, comment, quote, escape, noheaders, flexible, no_infer, trim, }; from_delimited_data(config, input, name) } #[cfg(test)] mod test { use nu_cmd_lang::eval_pipeline_without_terminal_expression; use super::*; use crate::Reject; use crate::{Metadata, MetadataSet}; #[test] fn test_examples() { use crate::test_examples; test_examples(FromCsv {}) } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromCsv {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#""a,b\n1,2" | metadata set --content-type 'text/csv' --datasource-ls | from csv | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/from/ssv.rs
crates/nu-command/src/formats/from/ssv.rs
use indexmap::IndexMap; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct FromSsv; const DEFAULT_MINIMUM_SPACES: usize = 2; impl Command for FromSsv { fn name(&self) -> &str { "from ssv" } fn signature(&self) -> Signature { Signature::build("from ssv") .input_output_types(vec![(Type::String, Type::table())]) .switch( "noheaders", "don't treat the first row as column names", Some('n'), ) .switch("aligned-columns", "assume columns are aligned", Some('a')) .named( "minimum-spaces", SyntaxShape::Int, "the minimum spaces to separate columns", Some('m'), ) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as space-separated values and create a table. The default minimum number of spaces counted as a separator is 2." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: r#"'FOO BAR 1 2' | from ssv"#, description: "Converts ssv formatted string to table", result: Some(Value::test_list(vec![Value::test_record(record! { "FOO" => Value::test_string("1"), "BAR" => Value::test_string("2"), })])), }, Example { example: r#"'FOO BAR 1 2' | from ssv --noheaders"#, description: "Converts ssv formatted string to table but not treating the first row as column names", result: Some(Value::test_list(vec![ Value::test_record(record! { "column0" => Value::test_string("FOO"), "column1" => Value::test_string("BAR"), }), Value::test_record(record! { "column0" => Value::test_string("1"), "column1" => Value::test_string("2"), }), ])), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { from_ssv(engine_state, stack, call, input) } } enum HeaderOptions<'a> { WithHeaders(&'a str), WithoutHeaders, } fn parse_aligned_columns<'a>( lines: impl Iterator<Item = &'a str>, headers: HeaderOptions, separator: &str, ) -> Vec<Vec<(String, String)>> { fn construct<'a>( lines: impl Iterator<Item = &'a str>, headers: Vec<(String, usize)>, ) -> Vec<Vec<(String, String)>> { lines .map(|l| { headers .iter() .enumerate() .map(|(i, (header_name, start_position))| { let char_index_start = match l.char_indices().nth(*start_position) { Some(idx) => idx.0, None => *start_position, }; let val = match headers.get(i + 1) { Some((_, end)) => { if *end < l.len() { let char_index_end = match l.char_indices().nth(*end) { Some(idx) => idx.0, None => *end, }; l.get(char_index_start..char_index_end) } else { l.get(char_index_start..) } } None => l.get(char_index_start..), } .unwrap_or("") .trim() .into(); (header_name.clone(), val) }) .collect() }) .collect() } let find_indices = |line: &str| { let values = line .split(&separator) .map(str::trim) .filter(|s| !s.is_empty()); values .fold( (0, vec![]), |(current_pos, mut indices), value| match line[current_pos..].find(value) { None => (current_pos, indices), Some(index) => { let absolute_index = current_pos + index; indices.push(absolute_index); (absolute_index + value.len(), indices) } }, ) .1 }; let parse_with_headers = |lines, headers_raw: &str| { let indices = find_indices(headers_raw); let headers = headers_raw .split(&separator) .map(str::trim) .filter(|s| !s.is_empty()) .map(String::from) .zip(indices); let columns = headers.collect::<Vec<(String, usize)>>(); construct(lines, columns) }; let parse_without_headers = |ls: Vec<&str>| { let mut indices = ls .iter() .flat_map(|s| find_indices(s)) .collect::<Vec<usize>>(); indices.sort_unstable(); indices.dedup(); let headers: Vec<(String, usize)> = indices .iter() .enumerate() .map(|(i, position)| (format!("column{i}"), *position)) .collect(); construct(ls.iter().map(|s| s.to_owned()), headers) }; match headers { HeaderOptions::WithHeaders(headers_raw) => parse_with_headers(lines, headers_raw), HeaderOptions::WithoutHeaders => parse_without_headers(lines.collect()), } } fn parse_separated_columns<'a>( lines: impl Iterator<Item = &'a str>, headers: HeaderOptions, separator: &str, ) -> Vec<Vec<(String, String)>> { fn collect<'a>( headers: Vec<String>, rows: impl Iterator<Item = &'a str>, separator: &str, ) -> Vec<Vec<(String, String)>> { rows.map(|r| { headers .iter() .zip(r.split(separator).map(str::trim).filter(|s| !s.is_empty())) .map(|(a, b)| (a.to_owned(), b.to_owned())) .collect() }) .collect() } let parse_with_headers = |lines, headers_raw: &str| { let headers = headers_raw .split(&separator) .map(str::trim) .map(str::to_owned) .filter(|s| !s.is_empty()) .collect(); collect(headers, lines, separator) }; let parse_without_headers = |ls: Vec<&str>| { let num_columns = ls.iter().map(|r| r.len()).max().unwrap_or(0); let headers = (0..=num_columns) .map(|i| format!("column{i}")) .collect::<Vec<String>>(); collect(headers, ls.into_iter(), separator) }; match headers { HeaderOptions::WithHeaders(headers_raw) => parse_with_headers(lines, headers_raw), HeaderOptions::WithoutHeaders => parse_without_headers(lines.collect()), } } fn string_to_table( s: &str, noheaders: bool, aligned_columns: bool, split_at: usize, ) -> Vec<Vec<(String, String)>> { let mut lines = s .lines() .filter(|l| !l.trim().is_empty() && !l.trim().starts_with('#')); let separator = " ".repeat(std::cmp::max(split_at, 1)); let (ls, header_options) = if noheaders { (lines, HeaderOptions::WithoutHeaders) } else { match lines.next() { Some(header) => (lines, HeaderOptions::WithHeaders(header)), None => return vec![], } }; let f = if aligned_columns { parse_aligned_columns } else { parse_separated_columns }; f(ls, header_options, &separator) } fn from_ssv_string_to_value( s: &str, noheaders: bool, aligned_columns: bool, split_at: usize, span: Span, ) -> Value { let rows = string_to_table(s, noheaders, aligned_columns, split_at) .into_iter() .map(|row| { let mut dict = IndexMap::new(); for (col, entry) in row { dict.insert(col, Value::string(entry, span)); } Value::record(dict.into_iter().collect(), span) }) .collect(); Value::list(rows, span) } fn from_ssv( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let name = call.head; let noheaders = call.has_flag(engine_state, stack, "noheaders")?; let aligned_columns = call.has_flag(engine_state, stack, "aligned-columns")?; let minimum_spaces: Option<Spanned<usize>> = call.get_flag(engine_state, stack, "minimum-spaces")?; let (concat_string, _span, metadata) = input.collect_string_strict(name)?; let split_at = match minimum_spaces { Some(number) => number.item, None => DEFAULT_MINIMUM_SPACES, }; Ok( from_ssv_string_to_value(&concat_string, noheaders, aligned_columns, split_at, name) .into_pipeline_data_with_metadata(metadata), ) } #[cfg(test)] mod tests { use super::*; fn owned(x: &str, y: &str) -> (String, String) { (String::from(x), String::from(y)) } #[test] fn it_filters_comment_lines() { let input = r#" a b 1 2 3 4 #comment line "#; let result = string_to_table(input, false, true, 1); assert_eq!( result, vec![ vec![owned("a", "1"), owned("b", "2")], vec![owned("a", "3"), owned("b", "4")] ] ); } #[test] fn it_trims_empty_and_whitespace_only_lines() { let input = r#" a b 1 2 3 4 "#; let result = string_to_table(input, false, true, 1); assert_eq!( result, vec![ vec![owned("a", "1"), owned("b", "2")], vec![owned("a", "3"), owned("b", "4")] ] ); } #[test] fn it_deals_with_single_column_input() { let input = r#" a 1 2 "#; let result = string_to_table(input, false, true, 1); assert_eq!(result, vec![vec![owned("a", "1")], vec![owned("a", "2")]]); } #[test] fn it_uses_first_row_as_data_when_noheaders() { let input = r#" a b 1 2 3 4 "#; let result = string_to_table(input, true, true, 1); assert_eq!( result, vec![ vec![owned("column0", "a"), owned("column1", "b")], vec![owned("column0", "1"), owned("column1", "2")], vec![owned("column0", "3"), owned("column1", "4")] ] ); } #[test] fn it_allows_a_predefined_number_of_spaces() { let input = r#" column a column b entry 1 entry number 2 3 four "#; let result = string_to_table(input, false, true, 3); assert_eq!( result, vec![ vec![ owned("column a", "entry 1"), owned("column b", "entry number 2") ], vec![owned("column a", "3"), owned("column b", "four")] ] ); } #[test] fn it_trims_remaining_separator_space() { let input = r#" colA colB colC val1 val2 val3 "#; let trimmed = |s: &str| s.trim() == s; let result = string_to_table(input, false, true, 2); assert!( result .iter() .all(|row| row.iter().all(|(a, b)| trimmed(a) && trimmed(b))) ); } #[test] fn it_keeps_empty_columns() { let input = r#" colA col B col C val2 val3 val4 val 5 val 6 val7 val8 "#; let result = string_to_table(input, false, true, 2); assert_eq!( result, vec![ vec![ owned("colA", ""), owned("col B", "val2"), owned("col C", "val3") ], vec![ owned("colA", "val4"), owned("col B", "val 5"), owned("col C", "val 6") ], vec![ owned("colA", "val7"), owned("col B", ""), owned("col C", "val8") ], ] ); } #[test] fn it_can_produce_an_empty_stream_for_header_only_input() { let input = "colA col B"; let result = string_to_table(input, false, true, 2); let expected: Vec<Vec<(String, String)>> = vec![]; assert_eq!(expected, result); } #[test] fn it_uses_the_full_final_column() { let input = r#" colA col B val1 val2 trailing value that should be included "#; let result = string_to_table(input, false, true, 2); assert_eq!( result, vec![vec![ owned("colA", "val1"), owned("col B", "val2 trailing value that should be included"), ]] ); } #[test] fn it_handles_empty_values_when_noheaders_and_aligned_columns() { let input = r#" a multi-word value b d 1 3-3 4 last "#; let result = string_to_table(input, true, true, 2); assert_eq!( result, vec![ vec![ owned("column0", "a multi-word value"), owned("column1", "b"), owned("column2", ""), owned("column3", "d"), owned("column4", "") ], vec![ owned("column0", "1"), owned("column1", ""), owned("column2", "3-3"), owned("column3", "4"), owned("column4", "") ], vec![ owned("column0", ""), owned("column1", ""), owned("column2", ""), owned("column3", ""), owned("column4", "last") ], ] ); } #[test] fn input_is_parsed_correctly_if_either_option_works() { let input = r#" docker-registry docker-registry=default docker-registry=default 172.30.78.158 5000/TCP kubernetes component=apiserver,provider=kubernetes <none> 172.30.0.2 443/TCP kubernetes-ro component=apiserver,provider=kubernetes <none> 172.30.0.1 80/TCP "#; let aligned_columns_noheaders = string_to_table(input, true, true, 2); let separator_noheaders = string_to_table(input, true, false, 2); let aligned_columns_with_headers = string_to_table(input, false, true, 2); let separator_with_headers = string_to_table(input, false, false, 2); assert_eq!(aligned_columns_noheaders, separator_noheaders); assert_eq!(aligned_columns_with_headers, separator_with_headers); } #[test] fn test_examples() { use crate::test_examples; test_examples(FromSsv {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/from/delimited.rs
crates/nu-command/src/formats/from/delimited.rs
use csv::{ReaderBuilder, Trim}; use nu_protocol::{ByteStream, ListStream, PipelineData, ShellError, Signals, Span, Value}; fn from_csv_error(err: csv::Error, span: Span) -> ShellError { ShellError::DelimiterError { msg: err.to_string(), span, } } fn from_delimited_stream( DelimitedReaderConfig { separator, comment, quote, escape, noheaders, flexible, no_infer, trim, }: DelimitedReaderConfig, input: ByteStream, span: Span, ) -> Result<ListStream, ShellError> { let input_reader = if let Some(stream) = input.reader() { stream } else { return Ok(ListStream::new(std::iter::empty(), span, Signals::empty())); }; let mut reader = ReaderBuilder::new() .has_headers(!noheaders) .flexible(flexible) .delimiter(separator as u8) .comment(comment.map(|c| c as u8)) .quote(quote as u8) .escape(escape.map(|c| c as u8)) .trim(trim) .from_reader(input_reader); let headers = if noheaders { vec![] } else { reader .headers() .map_err(|err| from_csv_error(err, span))? .iter() .map(String::from) .collect() }; let n = headers.len(); let columns = headers .into_iter() .chain((n..).map(|i| format!("column{i}"))); let iter = reader.into_records().map(move |row| { let row = match row { Ok(row) => row, Err(err) => return Value::error(from_csv_error(err, span), span), }; let columns = columns.clone(); let values = row.into_iter().map(|s| { if no_infer { Value::string(s, span) } else if let Ok(i) = s.parse() { Value::int(i, span) } else if let Ok(f) = s.parse() { Value::float(f, span) } else { Value::string(s, span) } }); Value::record(columns.zip(values).collect(), span) }); Ok(ListStream::new(iter, span, Signals::empty())) } pub(super) struct DelimitedReaderConfig { pub separator: char, pub comment: Option<char>, pub quote: char, pub escape: Option<char>, pub noheaders: bool, pub flexible: bool, pub no_infer: bool, pub trim: Trim, } pub(super) fn from_delimited_data( config: DelimitedReaderConfig, input: PipelineData, name: Span, ) -> Result<PipelineData, ShellError> { let metadata = input.metadata().map(|md| md.with_content_type(None)); match input { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(value, ..) => { let string = value.into_string()?; let byte_stream = ByteStream::read_string(string, name, Signals::empty()); Ok(PipelineData::list_stream( from_delimited_stream(config, byte_stream, name)?, metadata, )) } PipelineData::ListStream(list_stream, _) => Err(ShellError::OnlySupportsThisInputType { exp_input_type: "string".into(), wrong_type: "list".into(), dst_span: name, src_span: list_stream.span(), }), PipelineData::ByteStream(byte_stream, ..) => Ok(PipelineData::list_stream( from_delimited_stream(config, byte_stream, name)?, metadata, )), } } pub fn trim_from_str(trim: Option<Value>) -> Result<Trim, ShellError> { match trim { Some(v) => { let span = v.span(); match v { Value::String {val: item, ..} => match item.as_str() { "all" => Ok(Trim::All), "headers" => Ok(Trim::Headers), "fields" => Ok(Trim::Fields), "none" => Ok(Trim::None), _ => Err(ShellError::TypeMismatch { err_message: "the only possible values for trim are 'all', 'headers', 'fields' and 'none'" .into(), span, }), } _ => Ok(Trim::None), } } _ => Ok(Trim::None), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/from/toml.rs
crates/nu-command/src/formats/from/toml.rs
use nu_engine::command_prelude::*; use toml::value::{Datetime, Offset}; #[derive(Clone)] pub struct FromToml; impl Command for FromToml { fn name(&self) -> &str { "from toml" } fn signature(&self) -> Signature { Signature::build("from toml") .input_output_types(vec![(Type::String, Type::record())]) .category(Category::Formats) } fn description(&self) -> &str { "Parse text as .toml and create record." } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; let (mut string_input, span, metadata) = input.collect_string_strict(span)?; string_input.push('\n'); Ok(convert_string_to_value(string_input, span)? .into_pipeline_data_with_metadata(metadata.map(|md| md.with_content_type(None)))) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "'a = 1' | from toml", description: "Converts toml formatted string to record", result: Some(Value::test_record(record! { "a" => Value::test_int(1), })), }, Example { example: "'a = 1 b = [1, 2]' | from toml", description: "Converts toml formatted string to record", result: Some(Value::test_record(record! { "a" => Value::test_int(1), "b" => Value::test_list(vec![ Value::test_int(1), Value::test_int(2)],), })), }, ] } } fn convert_toml_datetime_to_value(dt: &Datetime, span: Span) -> Value { match &dt.clone() { toml::value::Datetime { date: Some(_), time: _, offset: _, } => (), _ => return Value::string(dt.to_string(), span), } let date = match dt.date { Some(date) => { chrono::NaiveDate::from_ymd_opt(date.year.into(), date.month.into(), date.day.into()) } None => Some(chrono::NaiveDate::default()), }; let time = match dt.time { Some(time) => chrono::NaiveTime::from_hms_nano_opt( time.hour.into(), time.minute.into(), time.second.into(), time.nanosecond, ), None => Some(chrono::NaiveTime::default()), }; let tz = match dt.offset { Some(offset) => match offset { Offset::Z => chrono::FixedOffset::east_opt(0), Offset::Custom { minutes: min } => chrono::FixedOffset::east_opt(min as i32 * 60), }, None => chrono::FixedOffset::east_opt(0), }; let datetime = match (date, time, tz) { (Some(date), Some(time), Some(tz)) => chrono::NaiveDateTime::new(date, time) .and_local_timezone(tz) .earliest(), _ => None, }; match datetime { Some(datetime) => Value::date(datetime, span), None => Value::string(dt.to_string(), span), } } fn convert_toml_to_value(value: &toml::Value, span: Span) -> Value { match value { toml::Value::Array(array) => { let v: Vec<Value> = array .iter() .map(|x| convert_toml_to_value(x, span)) .collect(); Value::list(v, span) } toml::Value::Boolean(b) => Value::bool(*b, span), toml::Value::Float(f) => Value::float(*f, span), toml::Value::Integer(i) => Value::int(*i, span), toml::Value::Table(k) => Value::record( k.iter() .map(|(k, v)| (k.clone(), convert_toml_to_value(v, span))) .collect(), span, ), toml::Value::String(s) => Value::string(s.clone(), span), toml::Value::Datetime(dt) => convert_toml_datetime_to_value(dt, span), } } pub fn convert_string_to_value(string_input: String, span: Span) -> Result<Value, ShellError> { let result: Result<toml::Value, toml::de::Error> = toml::from_str(&string_input); match result { Ok(value) => Ok(convert_toml_to_value(&value, span)), Err(err) => Err(ShellError::CantConvert { to_type: "structured toml data".into(), from_type: "string".into(), span, help: Some(err.to_string()), }), } } #[cfg(test)] mod tests { use crate::Reject; use crate::{Metadata, MetadataSet}; use super::*; use chrono::TimeZone; use nu_cmd_lang::eval_pipeline_without_terminal_expression; use toml::value::Datetime; #[test] fn test_examples() { use crate::test_examples; test_examples(FromToml {}) } #[test] fn from_toml_creates_correct_date() { let toml_date = toml::Value::Datetime(Datetime { date: Option::from(toml::value::Date { year: 1980, month: 10, day: 12, }), time: Option::from(toml::value::Time { hour: 10, minute: 12, second: 44, nanosecond: 0, }), offset: Option::from(toml::value::Offset::Custom { minutes: 120 }), }); let span = Span::test_data(); let reference_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 result = convert_toml_to_value(&toml_date, span); //positive test (from toml returns a nushell date) assert_eq!(result, reference_date); } #[test] fn string_to_toml_value_passes() { let input_string = String::from( r#" command.build = "go build" [command.deploy] script = "./deploy.sh" "#, ); let span = Span::test_data(); let result = convert_string_to_value(input_string, span); assert!(result.is_ok()); } #[test] fn string_to_toml_value_fails() { let input_string = String::from( r#" command.build = [command.deploy] script = "./deploy.sh" "#, ); let span = Span::test_data(); let result = convert_string_to_value(input_string, span); assert!(result.is_err()); } #[test] fn convert_toml_datetime_to_value_date_time_offset() { let toml_date = Datetime { date: Option::from(toml::value::Date { year: 2000, month: 1, day: 1, }), time: Option::from(toml::value::Time { hour: 12, minute: 12, second: 12, nanosecond: 0, }), offset: Option::from(toml::value::Offset::Custom { minutes: 120 }), }; let span = Span::test_data(); let reference_date = Value::date( chrono::FixedOffset::east_opt(60 * 120) .unwrap() .with_ymd_and_hms(2000, 1, 1, 12, 12, 12) .unwrap(), span, ); let result = convert_toml_datetime_to_value(&toml_date, span); assert_eq!(result, reference_date); } #[test] fn convert_toml_datetime_to_value_date_time() { let toml_date = Datetime { date: Option::from(toml::value::Date { year: 2000, month: 1, day: 1, }), time: Option::from(toml::value::Time { hour: 12, minute: 12, second: 12, nanosecond: 0, }), offset: None, }; let span = Span::test_data(); let reference_date = Value::date( chrono::FixedOffset::east_opt(0) .unwrap() .with_ymd_and_hms(2000, 1, 1, 12, 12, 12) .unwrap(), span, ); let result = convert_toml_datetime_to_value(&toml_date, span); assert_eq!(result, reference_date); } #[test] fn convert_toml_datetime_to_value_date() { let toml_date = Datetime { date: Option::from(toml::value::Date { year: 2000, month: 1, day: 1, }), time: None, offset: None, }; let span = Span::test_data(); let reference_date = Value::date( chrono::FixedOffset::east_opt(0) .unwrap() .with_ymd_and_hms(2000, 1, 1, 0, 0, 0) .unwrap(), span, ); let result = convert_toml_datetime_to_value(&toml_date, span); assert_eq!(result, reference_date); } #[test] fn convert_toml_datetime_to_value_only_time() { let toml_date = Datetime { date: None, time: Option::from(toml::value::Time { hour: 12, minute: 12, second: 12, nanosecond: 0, }), offset: None, }; let span = Span::test_data(); let reference_date = Value::string(toml_date.to_string(), span); let result = convert_toml_datetime_to_value(&toml_date, span); assert_eq!(result, reference_date); } #[test] fn test_content_type_metadata() { let mut engine_state = Box::new(EngineState::new()); let delta = { let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FromToml {})); working_set.add_decl(Box::new(Metadata {})); working_set.add_decl(Box::new(MetadataSet {})); working_set.add_decl(Box::new(Reject {})); working_set.render() }; engine_state .merge_delta(delta) .expect("Error merging delta"); let cmd = r#""[a]\nb = 1\nc = 1" | metadata set --content-type 'text/x-toml' --datasource-ls | from toml | metadata | reject span | $in"#; let result = eval_pipeline_without_terminal_expression( cmd, std::env::temp_dir().as_ref(), &mut engine_state, ); assert_eq!( Value::test_record(record!("source" => Value::test_string("ls"))), 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/nuon.rs
crates/nu-command/src/formats/to/nuon.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct ToNuon; impl Command for ToNuon { fn name(&self) -> &str { "to nuon" } fn signature(&self) -> Signature { Signature::build("to nuon") .input_output_types(vec![(Type::Any, Type::String)]) .switch( "raw", "remove all of the whitespace (overwrites -i and -t)", Some('r'), ) .named( "indent", SyntaxShape::Number, "specify indentation width", Some('i'), ) .named( "tabs", SyntaxShape::Number, "specify indentation tab quantity", Some('t'), ) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Converts table data into Nuon (Nushell Object Notation) text." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input .metadata() .unwrap_or_default() .with_content_type(Some("application/x-nuon".into())); let serialize_types = call.has_flag(engine_state, stack, "serialize")?; let style = if call.has_flag(engine_state, stack, "raw")? { nuon::ToStyle::Raw } else if let Some(t) = call.get_flag(engine_state, stack, "tabs")? { nuon::ToStyle::Tabs(t) } else if let Some(i) = call.get_flag(engine_state, stack, "indent")? { nuon::ToStyle::Spaces(i) } else { nuon::ToStyle::Default }; let span = call.head; let value = input.into_value(span)?; match nuon::to_nuon(engine_state, &value, style, Some(span), serialize_types) { Ok(serde_nuon_string) => Ok(Value::string(serde_nuon_string, span) .into_pipeline_data_with_metadata(Some(metadata))), Err(error) => { Ok(Value::error(error, span).into_pipeline_data_with_metadata(Some(metadata))) } } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs a NUON string representing the contents of this list, compact by default", example: "[1 2 3] | to nuon", result: Some(Value::test_string("[1, 2, 3]")), }, Example { description: "Outputs a NUON array of ints, with pretty indentation", example: "[1 2 3] | to nuon --indent 2", result: Some(Value::test_string("[\n 1,\n 2,\n 3\n]")), }, Example { description: "Overwrite any set option with --raw", example: "[1 2 3] | to nuon --indent 2 --raw", result: Some(Value::test_string("[1,2,3]")), }, Example { description: "A more complex record with multiple data types", example: "{date: 2000-01-01, data: [1 [2 3] 4.56]} | to nuon --indent 2", result: Some(Value::test_string( "{\n date: 2000-01-01T00:00:00+00:00,\n data: [\n 1,\n [\n 2,\n 3\n ],\n 4.56\n ]\n}", )), }, Example { description: "A more complex record with --raw", example: "{date: 2000-01-01, data: [1 [2 3] 4.56]} | to nuon --raw", result: Some(Value::test_string( "{date:2000-01-01T00:00:00+00:00,data:[1,[2,3],4.56]}", )), }, ] } } #[cfg(test)] mod test { use super::*; use nu_cmd_lang::eval_pipeline_without_terminal_expression; use crate::{Get, Metadata}; #[test] fn test_examples() { use super::ToNuon; use crate::test_examples; test_examples(ToNuon {}) } #[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(ToNuon {})); 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 nuon | 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/x-nuon"), 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/msgpack.rs
crates/nu-command/src/formats/to/msgpack.rs
// Credit to https://github.com/hulthe/nu_plugin_msgpack for the original idea, though the // implementation here is unique. use std::io; use byteorder::{BigEndian, WriteBytesExt}; use nu_engine::command_prelude::*; use nu_protocol::{Signals, Spanned, ast::PathMember, shell_error::io::IoError}; use rmp::encode as mp; /// Max recursion depth const MAX_DEPTH: usize = 50; #[derive(Clone)] pub struct ToMsgpack; impl Command for ToMsgpack { fn name(&self) -> &str { "to msgpack" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, Type::Binary) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Convert Nu values into MessagePack." } fn extra_description(&self) -> &str { r#" Not all values are representable as MessagePack. The datetime extension type is used for dates. Binaries are represented with the native MessagePack binary type. Most other types are represented in an analogous way to `to json`, and may not convert to the exact same type when deserialized with `from msgpack`. MessagePack: https://msgpack.org/ "# .trim() } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Convert a list of values to MessagePack", example: "[foo, 42, false] | to msgpack", result: Some(Value::test_binary(b"\x93\xA3\x66\x6F\x6F\x2A\xC2")), }, Example { description: "Convert a range to a MessagePack array", example: "1..10 | to msgpack", result: Some(Value::test_binary(b"\x9A\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A")) }, Example { description: "Convert a table to MessagePack", example: "[ [event_name time]; ['Apollo 11 Landing' 1969-07-24T16:50:35] ['Nushell first commit' 2019-05-10T09:59:12-07:00] ] | to msgpack", result: Some(Value::test_binary(b"\x92\x82\xAA\x65\x76\x65\x6E\x74\x5F\x6E\x61\x6D\x65\xB1\x41\x70\x6F\x6C\x6C\x6F\x20\x31\x31\x20\x4C\x61\x6E\x64\x69\x6E\x67\xA4\x74\x69\x6D\x65\xC7\x0C\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\x2C\xAB\x5B\x82\xAA\x65\x76\x65\x6E\x74\x5F\x6E\x61\x6D\x65\xB4\x4E\x75\x73\x68\x65\x6C\x6C\x20\x66\x69\x72\x73\x74\x20\x63\x6F\x6D\x6D\x69\x74\xA4\x74\x69\x6D\x65\xD6\xFF\x5C\xD5\xAD\xE0")), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let metadata = input .metadata() .unwrap_or_default() .with_content_type(Some("application/x-msgpack".into())); let value_span = input.span().unwrap_or(call.head); let value = input.into_value(value_span)?; let mut out = vec![]; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; write_value( &mut out, &value, 0, engine_state, call.head, serialize_types, )?; Ok(Value::binary(out, call.head).into_pipeline_data_with_metadata(Some(metadata))) } } #[derive(Debug)] pub(crate) enum WriteError { MaxDepth(Span), Rmp(mp::ValueWriteError<io::Error>, Span), Io(io::Error, Span), Shell(Box<ShellError>), } impl From<Spanned<mp::ValueWriteError<io::Error>>> for WriteError { fn from(v: Spanned<mp::ValueWriteError<io::Error>>) -> Self { Self::Rmp(v.item, v.span) } } impl From<Spanned<io::Error>> for WriteError { fn from(v: Spanned<io::Error>) -> Self { Self::Io(v.item, v.span) } } impl From<Box<ShellError>> for WriteError { fn from(v: Box<ShellError>) -> Self { Self::Shell(v) } } impl From<ShellError> for WriteError { fn from(value: ShellError) -> Self { Box::new(value).into() } } impl From<WriteError> for ShellError { fn from(value: WriteError) -> Self { match value { WriteError::MaxDepth(span) => ShellError::GenericError { error: "MessagePack data is nested too deeply".into(), msg: format!("exceeded depth limit ({MAX_DEPTH})"), span: Some(span), help: None, inner: vec![], }, WriteError::Rmp(err, span) => ShellError::GenericError { error: "Failed to encode MessagePack data".into(), msg: err.to_string(), span: Some(span), help: None, inner: vec![], }, WriteError::Io(err, span) => ShellError::Io(IoError::new(err, span, None)), WriteError::Shell(err) => *err, } } } pub(crate) fn write_value( out: &mut impl io::Write, value: &Value, depth: usize, engine_state: &EngineState, call_span: Span, serialize_types: bool, ) -> Result<(), WriteError> { use mp::ValueWriteError::InvalidMarkerWrite; let span = value.span(); // Prevent stack overflow if depth >= MAX_DEPTH { return Err(WriteError::MaxDepth(span)); } match value { Value::Bool { val, .. } => { mp::write_bool(out, *val) .map_err(InvalidMarkerWrite) .err_span(span)?; } Value::Int { val, .. } => { mp::write_sint(out, *val).err_span(span)?; } Value::Float { val, .. } => { mp::write_f64(out, *val).err_span(span)?; } Value::Filesize { val, .. } => { mp::write_sint(out, val.get()).err_span(span)?; } Value::Duration { val, .. } => { mp::write_sint(out, *val).err_span(span)?; } Value::Date { val, .. } => { if val.timestamp_subsec_nanos() == 0 && val.timestamp() >= 0 && val.timestamp() < u32::MAX as i64 { // Timestamp extension type, 32-bit. u32 seconds since UNIX epoch only. mp::write_ext_meta(out, 4, -1).err_span(span)?; out.write_u32::<BigEndian>(val.timestamp() as u32) .err_span(span)?; } else { // Timestamp extension type, 96-bit. u32 nanoseconds and i64 seconds. mp::write_ext_meta(out, 12, -1).err_span(span)?; out.write_u32::<BigEndian>(val.timestamp_subsec_nanos()) .err_span(span)?; out.write_i64::<BigEndian>(val.timestamp()).err_span(span)?; } } Value::Range { val, .. } => { // Convert range to list write_value( out, &Value::list(val.into_range_iter(span, Signals::empty()).collect(), span), depth, engine_state, call_span, serialize_types, )?; } Value::String { val, .. } => { mp::write_str(out, val).err_span(span)?; } Value::Glob { val, .. } => { mp::write_str(out, val).err_span(span)?; } Value::Record { val, .. } => { mp::write_map_len(out, convert(val.len(), span)?).err_span(span)?; for (k, v) in val.iter() { mp::write_str(out, k).err_span(span)?; write_value(out, v, depth + 1, engine_state, call_span, serialize_types)?; } } Value::List { vals, .. } => { mp::write_array_len(out, convert(vals.len(), span)?).err_span(span)?; for val in vals { write_value( out, val, depth + 1, engine_state, call_span, serialize_types, )?; } } Value::Nothing { .. } => { mp::write_nil(out) .map_err(InvalidMarkerWrite) .err_span(span)?; } Value::Closure { val, .. } => { if serialize_types { let closure_string = val .coerce_into_string(engine_state, span) .map_err(|err| WriteError::Shell(Box::new(err)))?; mp::write_str(out, &closure_string).err_span(span)?; } else { return Err(WriteError::Shell(Box::new(ShellError::UnsupportedInput { msg: "closures are currently not deserializable (use --serialize to serialize as a string)".into(), input: "value originates from here".into(), msg_span: call_span, input_span: span, }))); } } Value::Error { error, .. } => { return Err(WriteError::Shell(error.clone())); } Value::CellPath { val, .. } => { // Write as a list of strings/ints mp::write_array_len(out, convert(val.members.len(), span)?).err_span(span)?; for member in &val.members { match member { PathMember::String { val, .. } => { mp::write_str(out, val).err_span(span)?; } PathMember::Int { val, .. } => { mp::write_uint(out, *val as u64).err_span(span)?; } } } } Value::Binary { val, .. } => { mp::write_bin(out, val).err_span(span)?; } Value::Custom { val, .. } => { write_value( out, &val.to_base_value(span)?, depth, engine_state, call_span, serialize_types, )?; } } Ok(()) } fn convert<T, U>(value: T, span: Span) -> Result<U, ShellError> where U: TryFrom<T>, <U as TryFrom<T>>::Error: std::fmt::Display, { value .try_into() .map_err(|err: <U as TryFrom<T>>::Error| ShellError::GenericError { error: "Value not compatible with MessagePack".into(), msg: err.to_string(), span: Some(span), help: None, inner: vec![], }) } #[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(ToMsgpack {}) } #[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(ToMsgpack {})); 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 msgpack | 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/x-msgpack"), 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/command.rs
crates/nu-command/src/formats/to/command.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct To; impl Command for To { fn name(&self) -> &str { "to" } fn description(&self) -> &str { "Translate structured data to a format." } fn signature(&self) -> nu_protocol::Signature { Signature::build("to") .category(Category::Formats) .input_output_types(vec![(Type::Nothing, Type::String)]) } 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/formats/to/md.rs
crates/nu-command/src/formats/to/md.rs
use indexmap::IndexMap; use nu_cmd_base::formats::to::delimited::merge_descriptors; use nu_engine::command_prelude::*; use nu_protocol::{Config, ast::PathMember}; use std::collections::HashSet; #[derive(Clone)] pub struct ToMd; /// Defines how lists should be formatted in Markdown output #[derive(Clone, Copy, Default, PartialEq)] enum ListStyle { /// No list markers, just plain text separated by newlines None, /// Ordered list using "1. ", "2. ", etc. Ordered, /// Unordered list using "* " (default) #[default] Unordered, } impl ListStyle { const OPTIONS: &[&'static str] = &["ordered", "unordered", "none"]; fn from_str(s: &str) -> Option<Self> { match s.to_ascii_lowercase().as_str() { "ordered" => Some(Self::Ordered), "unordered" => Some(Self::Unordered), "none" => Some(Self::None), _ => None, } } } struct ToMdOptions { pretty: bool, per_element: bool, center: Option<Vec<CellPath>>, escape_md: bool, escape_html: bool, list_style: ListStyle, } /// Special markdown element types that can be represented as single-field records const SPECIAL_MARKDOWN_HEADERS: &[&str] = &["h1", "h2", "h3", "blockquote"]; /// Check if a record represents a special markdown element (h1, h2, h3, blockquote) fn is_special_markdown_record(record: &nu_protocol::Record) -> bool { record.len() == 1 && record.get_index(0).is_some_and(|(header, _)| { SPECIAL_MARKDOWN_HEADERS.contains(&header.to_ascii_lowercase().as_str()) }) } impl Command for ToMd { fn name(&self) -> &str { "to md" } fn signature(&self) -> Signature { Signature::build("to md") .input_output_types(vec![(Type::Any, Type::String)]) .switch( "pretty", "Formats the Markdown table to vertically align items", Some('p'), ) .switch( "per-element", "Treat each row as markdown syntax element", Some('e'), ) .named( "center", SyntaxShape::List(Box::new(SyntaxShape::CellPath)), "Formats the Markdown table to center given columns", Some('c'), ) .switch( "escape-md", "Escapes Markdown special characters", Some('m'), ) .switch("escape-html", "Escapes HTML special characters", Some('t')) .switch( "escape-all", "Escapes both Markdown and HTML special characters", Some('a'), ) .named( "list", SyntaxShape::String, "Format lists as 'ordered' (1. 2. 3.), 'unordered' (* * *), or 'none'. Default: unordered", Some('l'), ) .category(Category::Formats) } fn description(&self) -> &str { "Convert table into simple Markdown." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs an MD string representing the contents of this table", example: "[[foo bar]; [1 2]] | to md", result: Some(Value::test_string( "| foo | bar |\n| --- | --- |\n| 1 | 2 |", )), }, Example { description: "Optionally, output a formatted markdown string", example: "[[foo bar]; [1 2]] | to md --pretty", result: Some(Value::test_string( "| foo | bar |\n| --- | --- |\n| 1 | 2 |", )), }, Example { description: "Treat each row as a markdown element", example: r#"[{"H1": "Welcome to Nushell" } [[foo bar]; [1 2]]] | to md --per-element --pretty"#, result: Some(Value::test_string( "# Welcome to Nushell\n| foo | bar |\n| --- | --- |\n| 1 | 2 |", )), }, Example { description: "Render a list (unordered by default)", example: "[0 1 2] | to md", result: Some(Value::test_string("* 0\n* 1\n* 2")), }, Example { description: "Separate list into markdown tables", example: "[ {foo: 1, bar: 2} {foo: 3, bar: 4} {foo: 5}] | to md --per-element", result: Some(Value::test_string( "| foo | bar |\n| --- | --- |\n| 1 | 2 |\n| 3 | 4 |\n\n| foo |\n| --- |\n| 5 |", )), }, Example { description: "Center a column of a markdown table", example: "[ {foo: 1, bar: 2} {foo: 3, bar: 4}] | to md --pretty --center [bar]", result: Some(Value::test_string( "| foo | bar |\n| --- |:---:|\n| 1 | 2 |\n| 3 | 4 |", )), }, Example { description: "Escape markdown special characters", example: r#"[ {foo: "_1_", bar: "\# 2"} {foo: "[3]", bar: "4|5"}] | to md --escape-md"#, result: Some(Value::test_string( "| foo | bar |\n| --- | --- |\n| \\_1\\_ | \\# 2 |\n| \\[3\\] | 4\\|5 |", )), }, Example { description: "Escape html special characters", example: r#"[ {a: p, b: "<p>Welcome to nushell</p>"}] | to md --escape-html"#, result: Some(Value::test_string( "| a | b |\n| --- | --- |\n| p | &lt;p&gt;Welcome to nushell&lt;&#x2f;p&gt; |", )), }, Example { description: "Render a list as an ordered markdown list", example: "[one two three] | to md --list ordered", result: Some(Value::test_string("1. one\n2. two\n3. three")), }, Example { description: "Render a list without markers", example: "[one two three] | to md --list none", result: Some(Value::test_string("one\ntwo\nthree")), }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let pretty = call.has_flag(engine_state, stack, "pretty")?; let per_element = call.has_flag(engine_state, stack, "per-element")?; let escape_md = call.has_flag(engine_state, stack, "escape-md")?; let escape_html = call.has_flag(engine_state, stack, "escape-html")?; let escape_both = call.has_flag(engine_state, stack, "escape-all")?; let center: Option<Vec<CellPath>> = call.get_flag(engine_state, stack, "center")?; let list_style_str: Option<Spanned<String>> = call.get_flag(engine_state, stack, "list")?; let list_style = match &list_style_str { Some(spanned) => { ListStyle::from_str(&spanned.item).ok_or_else(|| ShellError::InvalidValue { valid: format!("one of {}", ListStyle::OPTIONS.join(", ")), actual: spanned.item.clone(), span: spanned.span, })? } None => ListStyle::default(), }; let config = stack.get_config(engine_state); to_md( input, ToMdOptions { pretty, per_element, center, escape_md: escape_md || escape_both, escape_html: escape_html || escape_both, list_style, }, &config, head, ) } } fn to_md( input: PipelineData, options: ToMdOptions, config: &Config, head: Span, ) -> Result<PipelineData, ShellError> { // text/markdown became a valid mimetype with rfc7763 let metadata = input .metadata() .unwrap_or_default() .with_content_type(Some("text/markdown".into())); // Collect input to check if it's a simple list (no records/tables) let values: Vec<Value> = input.into_iter().collect(); // Check if input is a simple list (no records, lists, or tables) // Tables in nushell can be represented as List of Records or List of Lists let is_simple_list = !values .iter() .any(|v| matches!(v, Value::Record { .. } | Value::List { .. })); // For simple lists, use list_style formatting if is_simple_list { let result = values .into_iter() .enumerate() .map(|(idx, val)| { format_list_item( val, idx, options.list_style, options.escape_md, options.escape_html, config, ) }) .collect::<Vec<String>>() .join("") .trim() .to_string(); return Ok(Value::string(result, head).into_pipeline_data_with_metadata(Some(metadata))); } // For tables/records, use the grouping logic let input = Value::list(values, head).into_pipeline_data(); let (grouped_input, single_list) = group_by(input, head, config); if options.per_element || single_list { return Ok(Value::string( grouped_input .into_iter() .scan(0usize, |list_idx, val| { Some(match &val { Value::List { .. } => { format!( "{}\n\n", table( val.into_pipeline_data(), options.pretty, &options.center, options.escape_md, options.escape_html, config ) ) } // For records, check if it's a special markdown element (h1, h2, etc.) Value::Record { val: record, .. } => { if is_special_markdown_record(record) { // Special markdown elements use fragment() directly fragment( val, options.pretty, &options.center, options.escape_md, options.escape_html, config, ) } else { // Regular records are rendered as tables format!( "{}\n\n", fragment( val, options.pretty, &options.center, options.escape_md, options.escape_html, config ) ) } } _ => { let result = format_list_item( val, *list_idx, options.list_style, options.escape_md, options.escape_html, config, ); *list_idx += 1; result } }) }) .collect::<Vec<String>>() .join("") .trim(), head, ) .into_pipeline_data_with_metadata(Some(metadata))); } Ok(Value::string( table( grouped_input, options.pretty, &options.center, options.escape_md, options.escape_html, config, ), head, ) .into_pipeline_data_with_metadata(Some(metadata))) } /// Formats a single list item with the appropriate list marker based on list_style fn format_list_item( input: Value, index: usize, list_style: ListStyle, escape_md: bool, escape_html: bool, config: &Config, ) -> String { let value_string = input.to_expanded_string("|", config); let escaped = escape_value(value_string, escape_md, escape_html, false); match list_style { ListStyle::Ordered => format!("{}. {}\n", index + 1, escaped), ListStyle::Unordered => format!("* {}\n", escaped), ListStyle::None => format!("{}\n", escaped), } } fn escape_markdown_characters(input: String, escape_md: bool, for_table: bool) -> String { let mut output = String::with_capacity(input.len()); for ch in input.chars() { let must_escape = match ch { '\\' => true, '|' if for_table => true, '`' | '*' | '_' | '{' | '}' | '[' | ']' | '(' | ')' | '<' | '>' | '#' | '+' | '-' | '.' | '!' if escape_md => { true } _ => false, }; if must_escape { output.push('\\'); } output.push(ch); } output } /// Escapes a value string with optional HTML and Markdown escaping fn escape_value(value: String, escape_md: bool, escape_html: bool, for_table: bool) -> String { escape_markdown_characters( if escape_html { v_htmlescape::escape(&value).to_string() } else { value }, escape_md, for_table, ) } fn fragment( input: Value, pretty: bool, center: &Option<Vec<CellPath>>, escape_md: bool, escape_html: bool, config: &Config, ) -> String { let mut out = String::new(); if let Value::Record { val, .. } = &input { match val.get_index(0) { Some((header, data)) if is_special_markdown_record(val) => { // SAFETY: is_special_markdown_record already validated the header matches one of these let markup = match header.to_ascii_lowercase().as_ref() { "h1" => "# ", "h2" => "## ", "h3" => "### ", "blockquote" => "> ", _ => "> ", // Fallback for any future validated headers not yet listed explicitly }; let value_string = data.to_expanded_string("|", config); out.push_str(markup); out.push_str(&escape_value(value_string, escape_md, escape_html, false)); } _ => { out = table( input.into_pipeline_data(), pretty, center, escape_md, escape_html, config, ) } } } else { let value_string = input.to_expanded_string("|", config); out = escape_value(value_string, escape_md, escape_html, false); } out.push('\n'); out } fn collect_headers(headers: &[String], escape_md: bool) -> (Vec<String>, Vec<usize>) { let mut escaped_headers: Vec<String> = Vec::new(); let mut column_widths: Vec<usize> = Vec::new(); if !headers.is_empty() && (headers.len() > 1 || !headers[0].is_empty()) { for header in headers { let escaped_header_string = escape_markdown_characters( v_htmlescape::escape(header).to_string(), escape_md, true, ); column_widths.push(escaped_header_string.len()); escaped_headers.push(escaped_header_string); } } else { column_widths = vec![0; headers.len()]; } (escaped_headers, column_widths) } fn table( input: PipelineData, pretty: bool, center: &Option<Vec<CellPath>>, escape_md: bool, escape_html: bool, config: &Config, ) -> String { let vec_of_values = input .into_iter() .flat_map(|val| match val { Value::List { vals, .. } => vals, other => vec![other], }) .collect::<Vec<Value>>(); let mut headers = merge_descriptors(&vec_of_values); let mut empty_header_index = 0; for value in &vec_of_values { if let Value::Record { val, .. } = value { for column in val.columns() { if column.is_empty() && !headers.contains(&String::new()) { headers.insert(empty_header_index, String::new()); empty_header_index += 1; break; } empty_header_index += 1; } } } let (escaped_headers, mut column_widths) = collect_headers(&headers, escape_md); let mut escaped_rows: Vec<Vec<String>> = Vec::new(); for row in vec_of_values { let mut escaped_row: Vec<String> = Vec::new(); let span = row.span(); match row.to_owned() { Value::Record { val: row, .. } => { for i in 0..headers.len() { let value_string = row .get(&headers[i]) .cloned() .unwrap_or_else(|| Value::nothing(span)) .to_expanded_string(", ", config); let escaped_string = escape_markdown_characters( if escape_html { v_htmlescape::escape(&value_string).to_string() } else { value_string }, escape_md, true, ); let new_column_width = escaped_string.len(); escaped_row.push(escaped_string); if column_widths[i] < new_column_width { column_widths[i] = new_column_width; } if column_widths[i] < 3 { column_widths[i] = 3; } } } p => { let value_string = v_htmlescape::escape(&p.to_abbreviated_string(config)).to_string(); escaped_row.push(value_string); } } escaped_rows.push(escaped_row); } if (column_widths.is_empty() || column_widths.iter().all(|x| *x == 0)) && escaped_rows.is_empty() { String::from("") } else { get_output_string( &escaped_headers, &escaped_rows, &column_widths, pretty, center, ) .trim() .to_string() } } pub fn group_by(values: PipelineData, head: Span, config: &Config) -> (PipelineData, bool) { let mut lists = IndexMap::new(); let mut single_list = false; for val in values { if let Value::Record { val: ref record, .. } = val { lists .entry(record.columns().map(|c| c.as_str()).collect::<String>()) .and_modify(|v: &mut Vec<Value>| v.push(val.clone())) .or_insert_with(|| vec![val.clone()]); } else { lists .entry(val.to_expanded_string(",", config)) .and_modify(|v: &mut Vec<Value>| v.push(val.clone())) .or_insert_with(|| vec![val.clone()]); } } let mut output = vec![]; for (_, mut value) in lists { if value.len() == 1 { output.push(value.pop().unwrap_or_else(|| Value::nothing(head))) } else { output.push(Value::list(value.to_vec(), head)) } } if output.len() == 1 { single_list = true; } (Value::list(output, head).into_pipeline_data(), single_list) } fn get_output_string( headers: &[String], rows: &[Vec<String>], column_widths: &[usize], pretty: bool, center: &Option<Vec<CellPath>>, ) -> String { let mut output_string = String::new(); let mut to_center: HashSet<String> = HashSet::new(); if let Some(center_vec) = center.as_ref() { for cell_path in center_vec { if let Some(PathMember::String { val, .. }) = cell_path .members .iter() .find(|member| matches!(member, PathMember::String { .. })) { to_center.insert(val.clone()); } } } if !headers.is_empty() { output_string.push('|'); for i in 0..headers.len() { output_string.push(' '); if pretty { if center.is_some() && to_center.contains(&headers[i]) { output_string.push_str(&get_centered_string( headers[i].clone(), column_widths[i], ' ', )); } else { output_string.push_str(&get_padded_string( headers[i].clone(), column_widths[i], ' ', )); } } else { output_string.push_str(&headers[i]); } output_string.push_str(" |"); } output_string.push_str("\n|"); for i in 0..headers.len() { let centered_column = center.is_some() && to_center.contains(&headers[i]); let border_char = if centered_column { ':' } else { ' ' }; if pretty { output_string.push(border_char); output_string.push_str(&get_padded_string( String::from("-"), column_widths[i], '-', )); output_string.push(border_char); } else if centered_column { output_string.push_str(":---:"); } else { output_string.push_str(" --- "); } output_string.push('|'); } output_string.push('\n'); } for row in rows { if !headers.is_empty() { output_string.push('|'); } for i in 0..row.len() { if !headers.is_empty() { output_string.push(' '); } if pretty && column_widths.get(i).is_some() { if center.is_some() && to_center.contains(&headers[i]) { output_string.push_str(&get_centered_string( row[i].clone(), column_widths[i], ' ', )); } else { output_string.push_str(&get_padded_string( row[i].clone(), column_widths[i], ' ', )); } } else { output_string.push_str(&row[i]); } if !headers.is_empty() { output_string.push_str(" |"); } } output_string.push('\n'); } output_string } fn get_centered_string(text: String, desired_length: usize, padding_character: char) -> String { let total_padding = if text.len() > desired_length { 0 } else { desired_length - text.len() }; let repeat_left = total_padding / 2; let repeat_right = total_padding - repeat_left; format!( "{}{}{}", padding_character.to_string().repeat(repeat_left), text, padding_character.to_string().repeat(repeat_right) ) } fn get_padded_string(text: String, desired_length: usize, padding_character: char) -> String { let repeat_length = if text.len() > desired_length { 0 } else { desired_length - text.len() }; format!( "{}{}", text, padding_character.to_string().repeat(repeat_length) ) } #[cfg(test)] mod tests { use crate::{Get, Metadata}; use super::*; use nu_cmd_lang::eval_pipeline_without_terminal_expression; use nu_protocol::{Config, IntoPipelineData, Value, casing::Casing, record}; fn one(string: &str) -> String { string .lines() .skip(1) .map(|line| line.trim()) .collect::<Vec<&str>>() .join("\n") .trim_end() .to_string() } #[test] fn test_examples() { use crate::test_examples; test_examples(ToMd {}) } #[test] fn render_h1() { let value = Value::test_record(record! { "H1" => Value::test_string("Ecuador"), }); assert_eq!( fragment(value, false, &None, false, false, &Config::default()), "# Ecuador\n" ); } #[test] fn render_h2() { let value = Value::test_record(record! { "H2" => Value::test_string("Ecuador"), }); assert_eq!( fragment(value, false, &None, false, false, &Config::default()), "## Ecuador\n" ); } #[test] fn render_h3() { let value = Value::test_record(record! { "H3" => Value::test_string("Ecuador"), }); assert_eq!( fragment(value, false, &None, false, false, &Config::default()), "### Ecuador\n" ); } #[test] fn render_blockquote() { let value = Value::test_record(record! { "BLOCKQUOTE" => Value::test_string("Ecuador"), }); assert_eq!( fragment(value, false, &None, false, false, &Config::default()), "> Ecuador\n" ); } #[test] fn render_table() { let value = Value::test_list(vec![ Value::test_record(record! { "country" => Value::test_string("Ecuador"), }), Value::test_record(record! { "country" => Value::test_string("New Zealand"), }), Value::test_record(record! { "country" => Value::test_string("USA"), }), ]); assert_eq!( table( value.clone().into_pipeline_data(), false, &None, false, false, &Config::default() ), one(r#" | country | | --- | | Ecuador | | New Zealand | | USA | "#) ); assert_eq!( table( value.into_pipeline_data(), true, &None, false, false, &Config::default() ), one(r#" | country | | ----------- | | Ecuador | | New Zealand | | USA | "#) ); } #[test] fn test_empty_column_header() { let value = Value::test_list(vec![ Value::test_record(record! { "" => Value::test_string("1"), "foo" => Value::test_string("2"), }), Value::test_record(record! { "" => Value::test_string("3"), "foo" => Value::test_string("4"), }), ]); assert_eq!( table( value.clone().into_pipeline_data(), false, &None, false, false, &Config::default() ), one(r#" | | foo | | --- | --- | | 1 | 2 | | 3 | 4 | "#) ); } #[test] fn test_empty_row_value() { let value = Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_string("1"), "bar" => Value::test_string("2"), }), Value::test_record(record! { "foo" => Value::test_string("3"), "bar" => Value::test_string("4"), }), Value::test_record(record! { "foo" => Value::test_string("5"), "bar" => Value::test_string(""), }), ]); assert_eq!( table( value.clone().into_pipeline_data(), false, &None, false, false, &Config::default() ), one(r#" | foo | bar | | --- | --- | | 1 | 2 | | 3 | 4 | | 5 | | "#) ); } #[test] fn test_center_column() { let value = Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_string("1"), "bar" => Value::test_string("2"), }), Value::test_record(record! { "foo" => Value::test_string("3"), "bar" => Value::test_string("4"), }), Value::test_record(record! { "foo" => Value::test_string("5"), "bar" => Value::test_string("6"), }), ]); let center_columns = Value::test_list(vec![Value::test_cell_path(CellPath { members: vec![PathMember::test_string( "bar".into(), false, Casing::Sensitive, )], })]); let cell_path: Vec<CellPath> = center_columns .into_list() .unwrap() .into_iter() .map(|v| v.into_cell_path().unwrap()) .collect(); let center: Option<Vec<CellPath>> = Some(cell_path); // With pretty assert_eq!( table( value.clone().into_pipeline_data(), true, &center, false, false, &Config::default() ), one(r#" | foo | bar | | --- |:---:| | 1 | 2 | | 3 | 4 | | 5 | 6 | "#) ); // Without pretty assert_eq!( table( value.clone().into_pipeline_data(), false, &center, false, false, &Config::default() ), one(r#" | foo | bar | | --- |:---:| | 1 | 2 | | 3 | 4 | | 5 | 6 | "#) ); } #[test] fn test_empty_center_column() { let value = Value::test_list(vec![ Value::test_record(record! { "foo" => Value::test_string("1"), "bar" => Value::test_string("2"), }), Value::test_record(record! { "foo" => Value::test_string("3"), "bar" => Value::test_string("4"), }), Value::test_record(record! { "foo" => Value::test_string("5"), "bar" => Value::test_string("6"), }), ]); let center: Option<Vec<CellPath>> = Some(vec![]); assert_eq!( table( value.clone().into_pipeline_data(), true, &center, false, false, &Config::default() ), one(r#" | foo | bar | | --- | --- | | 1 | 2 | | 3 | 4 | | 5 | 6 | "#) ); } #[test] fn test_center_multiple_columns() { let value = Value::test_list(vec![ Value::test_record(record! { "command" => Value::test_string("ls"),
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-command/src/formats/to/json.rs
crates/nu-command/src/formats/to/json.rs
use nu_engine::command_prelude::*; use nu_protocol::{PipelineMetadata, ast::PathMember}; #[derive(Clone)] pub struct ToJson; impl Command for ToJson { fn name(&self) -> &str { "to json" } fn signature(&self) -> Signature { Signature::build("to json") .input_output_types(vec![(Type::Any, Type::String)]) .switch( "raw", "remove all of the whitespace and trailing line ending", Some('r'), ) .named( "indent", SyntaxShape::Number, "specify indentation width", Some('i'), ) .named( "tabs", SyntaxShape::Number, "specify indentation tab quantity", Some('t'), ) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Converts table data into JSON text." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let raw = call.has_flag(engine_state, stack, "raw")?; let use_tabs = call.get_flag(engine_state, stack, "tabs")?; let indent = call.get_flag(engine_state, stack, "indent")?; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; let span = call.head; // allow ranges to expand and turn into array let input = input.try_expand_range()?; let value = input.into_value(span)?; let json_value = value_to_json_value(engine_state, &value, span, serialize_types)?; let json_result = if raw { nu_json::to_string_raw(&json_value) } else if let Some(tab_count) = use_tabs { nu_json::to_string_with_tab_indentation(&json_value, tab_count) } else if let Some(indent) = indent { nu_json::to_string_with_indent(&json_value, indent) } else { nu_json::to_string(&json_value) }; match json_result { Ok(serde_json_string) => { let res = Value::string(serde_json_string, span); let metadata = PipelineMetadata { data_source: nu_protocol::DataSource::None, content_type: Some(mime::APPLICATION_JSON.to_string()), ..Default::default() }; Ok(PipelineData::value(res, Some(metadata))) } _ => Err(ShellError::CantConvert { to_type: "JSON".into(), from_type: value.get_type().to_string(), span, help: None, }), } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs a JSON string, with default indentation, representing the contents of this table", example: "[a b c] | to json", result: Some(Value::test_string("[\n \"a\",\n \"b\",\n \"c\"\n]")), }, Example { description: "Outputs a JSON string, with 4-space indentation, representing the contents of this table", example: "[Joe Bob Sam] | to json --indent 4", result: Some(Value::test_string( "[\n \"Joe\",\n \"Bob\",\n \"Sam\"\n]", )), }, Example { description: "Outputs an unformatted JSON string representing the contents of this table", example: "[1 2 3] | to json -r", result: Some(Value::test_string("[1,2,3]")), }, ] } } pub fn value_to_json_value( engine_state: &EngineState, v: &Value, call_span: Span, serialize_types: bool, ) -> Result<nu_json::Value, ShellError> { let span = v.span(); Ok(match v { Value::Bool { val, .. } => nu_json::Value::Bool(*val), Value::Filesize { val, .. } => nu_json::Value::I64(val.get()), Value::Duration { val, .. } => nu_json::Value::I64(*val), Value::Date { val, .. } => nu_json::Value::String(val.to_string()), Value::Float { val, .. } => nu_json::Value::F64(*val), Value::Int { val, .. } => nu_json::Value::I64(*val), Value::Nothing { .. } => nu_json::Value::Null, Value::String { val, .. } => nu_json::Value::String(val.to_string()), Value::Glob { val, .. } => nu_json::Value::String(val.to_string()), Value::CellPath { val, .. } => nu_json::Value::Array( val.members .iter() .map(|x| match &x { PathMember::String { val, .. } => Ok(nu_json::Value::String(val.clone())), PathMember::Int { val, .. } => Ok(nu_json::Value::U64(*val as u64)), }) .collect::<Result<Vec<nu_json::Value>, ShellError>>()?, ), Value::List { vals, .. } => { nu_json::Value::Array(json_list(engine_state, vals, call_span, serialize_types)?) } Value::Error { error, .. } => return Err(*error.clone()), Value::Closure { val, .. } => { if serialize_types { let closure_string = val.coerce_into_string(engine_state, span)?; nu_json::Value::String(closure_string.to_string()) } else { return Err(ShellError::UnsupportedInput { msg: "closures are currently not deserializable (use --serialize to serialize as a string)".into(), input: "value originates from here".into(), msg_span: call_span, input_span: span, }); } } Value::Range { .. } => nu_json::Value::Null, Value::Binary { val, .. } => { nu_json::Value::Array(val.iter().map(|x| nu_json::Value::U64(*x as u64)).collect()) } Value::Record { val, .. } => { let mut m = nu_json::Map::new(); for (k, v) in &**val { m.insert( k.clone(), value_to_json_value(engine_state, v, call_span, serialize_types)?, ); } nu_json::Value::Object(m) } Value::Custom { val, .. } => { let collected = val.to_base_value(span)?; value_to_json_value(engine_state, &collected, call_span, serialize_types)? } }) } fn json_list( engine_state: &EngineState, input: &[Value], call_span: Span, serialize_types: bool, ) -> Result<Vec<nu_json::Value>, ShellError> { let mut out = vec![]; for value in input { out.push(value_to_json_value( engine_state, value, call_span, serialize_types, )?); } Ok(out) } #[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(ToJson {}) } #[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(ToJson {})); 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 json | 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/json"), 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/xml.rs
crates/nu-command/src/formats/to/xml.rs
use crate::formats::nu_xml_format::{COLUMN_ATTRS_NAME, COLUMN_CONTENT_NAME, COLUMN_TAG_NAME}; use indexmap::IndexMap; use nu_engine::command_prelude::*; use quick_xml::{ escape, events::{BytesEnd, BytesPI, BytesStart, BytesText, Event}, }; use std::{borrow::Cow, io::Cursor}; #[derive(Clone)] pub struct ToXml; impl Command for ToXml { fn name(&self) -> &str { "to xml" } fn signature(&self) -> Signature { Signature::build("to xml") .input_output_types(vec![(Type::record(), Type::String)]) .named( "indent", SyntaxShape::Int, "Formats the XML text with the provided indentation setting", Some('i'), ) .switch( "partial-escape", "Only escape mandatory characters in text and attributes", Some('p'), ) .switch( "self-closed", "Output empty tags as self closing", Some('s'), ) .category(Category::Formats) } fn extra_description(&self) -> &str { r#"Every XML entry is represented via a record with tag, attribute and content fields. To represent different types of entries different values must be written to this fields: 1. Tag entry: `{tag: <tag name> attributes: {<attr name>: "<string value>" ...} content: [<entries>]}` 2. Comment entry: `{tag: '!' attributes: null content: "<comment string>"}` 3. Processing instruction (PI): `{tag: '?<pi name>' attributes: null content: "<pi content string>"}` 4. Text: `{tag: null attributes: null content: "<text>"}`. Or as plain `<text>` instead of record. Additionally any field which is: empty record, empty list or null, can be omitted."# } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs an XML string representing the contents of this table", example: r#"{tag: note attributes: {} content : [{tag: remember attributes: {} content : [{tag: null attributes: null content : Event}]}]} | to xml"#, result: Some(Value::test_string( "<note><remember>Event</remember></note>", )), }, Example { description: "When formatting xml null and empty record fields can be omitted and strings can be written without a wrapping record", example: r#"{tag: note content : [{tag: remember content : [Event]}]} | to xml"#, result: Some(Value::test_string( "<note><remember>Event</remember></note>", )), }, Example { description: "Optionally, formats the text with a custom indentation setting", example: r#"{tag: note content : [{tag: remember content : [Event]}]} | to xml --indent 3"#, result: Some(Value::test_string( "<note>\n <remember>Event</remember>\n</note>", )), }, Example { description: "Produce less escaping sequences in resulting xml", example: r#"{tag: note attributes: {a: "'qwe'\\"} content: ["\"'"]} | to xml --partial-escape"#, result: Some(Value::test_string(r#"<note a="'qwe'\">"'</note>"#)), }, Example { description: "Save space using self-closed tags", example: r#"{tag: root content: [[tag]; [a] [b] [c]]} | to xml --self-closed"#, result: Some(Value::test_string(r#"<root><a/><b/><c/></root>"#)), }, ] } fn description(&self) -> &str { "Convert special record structure into .xml text." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let indent: Option<Spanned<i64>> = call.get_flag(engine_state, stack, "indent")?; let partial_escape = call.has_flag(engine_state, stack, "partial-escape")?; let self_closed = call.has_flag(engine_state, stack, "self-closed")?; let job = Job::new(indent, partial_escape, self_closed); let input = input.try_expand_range()?; job.run(input, head) } } struct Job { writer: quick_xml::Writer<Cursor<Vec<u8>>>, partial_escape: bool, self_closed: bool, } impl Job { fn new(indent: Option<Spanned<i64>>, partial_escape: bool, self_closed: bool) -> Self { let writer = indent.as_ref().map_or_else( || quick_xml::Writer::new(Cursor::new(Vec::new())), |p| quick_xml::Writer::new_with_indent(Cursor::new(Vec::new()), b' ', p.item as usize), ); Self { writer, partial_escape, self_closed, } } fn run(mut self, input: PipelineData, head: Span) -> Result<PipelineData, ShellError> { let metadata = input .metadata() .unwrap_or_default() .with_content_type(Some("application/xml".into())); let value = input.into_value(head)?; self.write_xml_entry(value, true).and_then(|_| { let b = self.writer.into_inner().into_inner(); let s = if let Ok(s) = String::from_utf8(b) { s } else { return Err(ShellError::NonUtf8 { span: head }); }; Ok(Value::string(s, head).into_pipeline_data_with_metadata(Some(metadata))) }) } fn add_attributes<'a>( &self, element: &mut BytesStart<'a>, attributes: &'a IndexMap<String, String>, ) { for (k, v) in attributes { if self.partial_escape { element.push_attribute((k.as_bytes(), Self::partial_escape_attribute(v).as_ref())) } else { element.push_attribute((k.as_bytes(), escape::escape(v).as_bytes())) }; } } fn partial_escape_attribute(raw: &str) -> Cow<'_, [u8]> { let bytes = raw.as_bytes(); let mut escaped: Vec<u8> = Vec::new(); let mut iter = bytes.iter().enumerate(); let mut pos = 0; while let Some((new_pos, byte)) = iter.find(|(_, ch)| matches!(ch, b'<' | b'>' | b'&' | b'"')) { escaped.extend_from_slice(&bytes[pos..new_pos]); match byte { b'<' => escaped.extend_from_slice(b"&lt;"), b'>' => escaped.extend_from_slice(b"&gt;"), b'&' => escaped.extend_from_slice(b"&amp;"), b'"' => escaped.extend_from_slice(b"&quot;"), _ => unreachable!("Only '<', '>','&', '\"' are escaped"), } pos = new_pos + 1; } if !escaped.is_empty() { if let Some(raw) = bytes.get(pos..) { escaped.extend_from_slice(raw); } Cow::Owned(escaped) } else { Cow::Borrowed(bytes) } } fn write_xml_entry(&mut self, entry: Value, top_level: bool) -> Result<(), ShellError> { let entry_span = entry.span(); let span = entry.span(); // Allow using strings directly as content. // So user can write // {tag: a content: ['qwe']} // instead of longer // {tag: a content: [{content: 'qwe'}]} if let (Value::String { val, .. }, false) = (&entry, top_level) { return self.write_xml_text(val.as_str(), span); } if let Value::Record { val: record, .. } = &entry { if let Some(bad_column) = Self::find_invalid_column(record) { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: "record".into(), span: entry_span, help: Some(format!( "Invalid column \"{bad_column}\" in xml entry. Only \"{COLUMN_TAG_NAME}\", \"{COLUMN_ATTRS_NAME}\" and \"{COLUMN_CONTENT_NAME}\" are permitted" )), }); } // If key is not found it is assumed to be nothing. This way // user can write a tag like {tag: a content: [...]} instead // of longer {tag: a attributes: {} content: [...]} let tag = record .get(COLUMN_TAG_NAME) .cloned() .unwrap_or_else(|| Value::nothing(Span::unknown())); let attrs = record .get(COLUMN_ATTRS_NAME) .cloned() .unwrap_or_else(|| Value::nothing(Span::unknown())); let content = record .get(COLUMN_CONTENT_NAME) .cloned() .unwrap_or_else(|| Value::nothing(Span::unknown())); let content_span = content.span(); let tag_span = tag.span(); match (tag, attrs, content) { (Value::Nothing { .. }, Value::Nothing { .. }, Value::String { val, .. }) => { // Strings can not appear on top level of document if top_level { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: entry.get_type().to_string(), span: entry_span, help: Some("Strings can not be a root element of document".into()), }); } self.write_xml_text(val.as_str(), content_span) } (Value::String { val: tag_name, .. }, attrs, children) => { self.write_tag_like(entry_span, tag_name, tag_span, attrs, children, top_level) } _ => Err(ShellError::CantConvert { to_type: "XML".into(), from_type: "record".into(), span: entry_span, help: Some("Tag missing or is not a string".into()), }), } } else { Err(ShellError::CantConvert { to_type: "XML".into(), from_type: entry.get_type().to_string(), span: entry_span, help: Some("Xml entry expected to be a record".into()), }) } } fn find_invalid_column(record: &Record) -> Option<&String> { const VALID_COLS: [&str; 3] = [COLUMN_TAG_NAME, COLUMN_ATTRS_NAME, COLUMN_CONTENT_NAME]; record .columns() .find(|col| !VALID_COLS.contains(&col.as_str())) } /// Convert record to tag-like entry: tag, PI, comment. fn write_tag_like( &mut self, entry_span: Span, tag: String, tag_span: Span, attrs: Value, content: Value, top_level: bool, ) -> Result<(), ShellError> { if tag == "!" { // Comments can not appear on top level of document if top_level { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: "record".into(), span: entry_span, help: Some("Comments can not be a root element of document".into()), }); } self.write_comment(entry_span, attrs, content) } else if let Some(tag) = tag.strip_prefix('?') { // PIs can not appear on top level of document if top_level { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: Type::record().to_string(), span: entry_span, help: Some("PIs can not be a root element of document".into()), }); } let content: String = match content { Value::String { val, .. } => val, Value::Nothing { .. } => "".into(), _ => { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: Type::record().to_string(), span: content.span(), help: Some("PI content expected to be a string".into()), }); } }; self.write_processing_instruction(entry_span, tag, attrs, content) } else { // Allow tag to have no attributes or content for short hand input // alternatives like {tag: a attributes: {} content: []}, {tag: a attributes: null // content: null}, {tag: a}. See to_xml_entry for more let attrs = match attrs { Value::Record { val, .. } => val.into_owned(), Value::Nothing { .. } => Record::new(), _ => { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: attrs.get_type().to_string(), span: attrs.span(), help: Some("Tag attributes expected to be a record".into()), }); } }; let content = match content { Value::List { vals, .. } => vals, Value::Nothing { .. } => Vec::new(), _ => { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: content.get_type().to_string(), span: content.span(), help: Some("Tag content expected to be a list".into()), }); } }; self.write_tag(entry_span, tag, tag_span, attrs, content) } } fn write_comment( &mut self, entry_span: Span, attrs: Value, content: Value, ) -> Result<(), ShellError> { match (attrs, content) { (Value::Nothing { .. }, Value::String { val, .. }) => { // Text in comments must NOT be escaped // https://www.w3.org/TR/xml/#sec-comments let comment_content = BytesText::from_escaped(val.as_str()); self.writer .write_event(Event::Comment(comment_content)) .map_err(|_| ShellError::CantConvert { to_type: "XML".to_string(), from_type: Type::record().to_string(), span: entry_span, help: Some("Failure writing comment to xml".into()), }) } (_, content) => Err(ShellError::CantConvert { to_type: "XML".into(), from_type: content.get_type().to_string(), span: entry_span, help: Some("Comment expected to have string content and no attributes".into()), }), } } fn write_processing_instruction( &mut self, entry_span: Span, tag: &str, attrs: Value, content: String, ) -> Result<(), ShellError> { if !matches!(attrs, Value::Nothing { .. }) { return Err(ShellError::CantConvert { to_type: "XML".into(), from_type: Type::record().to_string(), span: entry_span, help: Some("PIs do not have attributes".into()), }); } let content_text = format!("{tag} {content}"); // PI content must NOT be escaped // https://www.w3.org/TR/xml/#sec-pi let pi_content = BytesPI::new(content_text.as_str()); self.writer .write_event(Event::PI(pi_content)) .map_err(|_| ShellError::CantConvert { to_type: "XML".to_string(), from_type: Type::record().to_string(), span: entry_span, help: Some("Failure writing PI to xml".into()), }) } fn write_tag( &mut self, entry_span: Span, tag: String, tag_span: Span, attrs: Record, children: Vec<Value>, ) -> Result<(), ShellError> { if tag.starts_with('!') || tag.starts_with('?') { return Err(ShellError::CantConvert { to_type: "XML".to_string(), from_type: Type::record().to_string(), span: tag_span, help: Some(format!( "Incorrect tag name {tag}, tag name can not start with ! or ?" )), }); } let self_closed = self.self_closed && children.is_empty(); let attributes = Self::parse_attributes(attrs)?; let mut open_tag = BytesStart::new(tag.clone()); self.add_attributes(&mut open_tag, &attributes); let open_tag_event = if self_closed { Event::Empty(open_tag) } else { Event::Start(open_tag) }; self.writer .write_event(open_tag_event) .map_err(|_| ShellError::CantConvert { to_type: "XML".to_string(), from_type: Type::record().to_string(), span: entry_span, help: Some("Failure writing tag to xml".into()), })?; children .into_iter() .try_for_each(|child| self.write_xml_entry(child, false))?; if !self_closed { let close_tag_event = Event::End(BytesEnd::new(tag)); self.writer .write_event(close_tag_event) .map_err(|_| ShellError::CantConvert { to_type: "XML".to_string(), from_type: Type::record().to_string(), span: entry_span, help: Some("Failure writing tag to xml".into()), })?; } Ok(()) } fn parse_attributes(attrs: Record) -> Result<IndexMap<String, String>, ShellError> { let mut h = IndexMap::new(); for (k, v) in attrs { if let Value::String { val, .. } = v { h.insert(k, val); } else { return Err(ShellError::CantConvert { to_type: "XML".to_string(), from_type: v.get_type().to_string(), span: v.span(), help: Some("Attribute value expected to be a string".into()), }); } } Ok(h) } fn write_xml_text(&mut self, val: &str, span: Span) -> Result<(), ShellError> { let text = Event::Text(if self.partial_escape { BytesText::from_escaped(escape::partial_escape(val)) } else { BytesText::new(val) }); self.writer .write_event(text) .map_err(|_| ShellError::CantConvert { to_type: "XML".to_string(), from_type: Type::String.to_string(), span, help: Some("Failure writing string to xml".into()), }) } } #[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(ToXml {}) } #[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(ToXml {})); 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 = "{tag: note attributes: {} content : [{tag: remember attributes: {} content : [{tag: null attributes: null content : Event}]}]} | to xml | 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/xml"), 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/text.rs
crates/nu-command/src/formats/to/text.rs
use chrono::Datelike; use chrono_humanize::HumanTime; use nu_engine::command_prelude::*; use nu_protocol::{ByteStream, PipelineMetadata, format_duration, shell_error::io::IoError}; use nu_utils::ObviousFloat; use std::io::Write; const LINE_ENDING: &str = if cfg!(target_os = "windows") { "\r\n" } else { "\n" }; #[derive(Clone)] pub struct ToText; impl Command for ToText { fn name(&self) -> &str { "to text" } fn signature(&self) -> Signature { Signature::build("to text") .input_output_types(vec![(Type::Any, Type::String)]) .switch( "no-newline", "Do not append a newline to the end of the text", Some('n'), ) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Converts data into simple text." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let no_newline = call.has_flag(engine_state, stack, "no-newline")?; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; let input = input.try_expand_range()?; match input { PipelineData::Empty => Ok(Value::string(String::new(), head) .into_pipeline_data_with_metadata(update_metadata(None))), PipelineData::Value(value, ..) => { let add_trailing = !no_newline && match &value { Value::List { vals, .. } => !vals.is_empty(), Value::Record { val, .. } => !val.is_empty(), _ => false, }; let mut str = local_into_string(engine_state, value, LINE_ENDING, serialize_types); if add_trailing { str.push_str(LINE_ENDING); } Ok( Value::string(str, head) .into_pipeline_data_with_metadata(update_metadata(None)), ) } PipelineData::ListStream(stream, meta) => { let span = stream.span(); let from_io_error = IoError::factory(head, None); let stream = if no_newline { let mut first = true; let mut iter = stream.into_inner(); let engine_state_clone = engine_state.clone(); ByteStream::from_fn( span, engine_state.signals().clone(), ByteStreamType::String, move |buf| { let Some(val) = iter.next() else { return Ok(false); }; if first { first = false; } else { write!(buf, "{LINE_ENDING}").map_err(&from_io_error)?; } // TODO: write directly into `buf` instead of creating an intermediate // string. let str = local_into_string( &engine_state_clone, val, LINE_ENDING, serialize_types, ); write!(buf, "{str}").map_err(&from_io_error)?; Ok(true) }, ) } else { let engine_state_clone = engine_state.clone(); ByteStream::from_iter( stream.into_inner().map(move |val| { let mut str = local_into_string( &engine_state_clone, val, LINE_ENDING, serialize_types, ); str.push_str(LINE_ENDING); str }), span, engine_state.signals().clone(), ByteStreamType::String, ) }; Ok(PipelineData::byte_stream(stream, update_metadata(meta))) } PipelineData::ByteStream(stream, meta) => { Ok(PipelineData::byte_stream(stream, update_metadata(meta))) } } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs data as simple text with a trailing newline", example: "[1] | to text", result: Some(Value::test_string("1".to_string() + LINE_ENDING)), }, Example { description: "Outputs data as simple text without a trailing newline", example: "[1] | to text --no-newline", result: Some(Value::test_string("1")), }, Example { description: "Outputs external data as simple text", example: "git help -a | lines | find -r '^ ' | to text", result: None, }, Example { description: "Outputs records as simple text", example: "ls | to text", result: None, }, ] } } fn local_into_string( engine_state: &EngineState, value: Value, separator: &str, serialize_types: bool, ) -> String { let span = value.span(); match value { Value::Bool { val, .. } => val.to_string(), Value::Int { val, .. } => val.to_string(), Value::Float { val, .. } => ObviousFloat(val).to_string(), Value::Filesize { val, .. } => val.to_string(), Value::Duration { val, .. } => format_duration(val), Value::Date { val, .. } => { format!( "{} ({})", { if val.year() >= 0 { val.to_rfc2822() } else { val.to_rfc3339() } }, HumanTime::from(val) ) } Value::Range { val, .. } => val.to_string(), Value::String { val, .. } => val, Value::Glob { val, .. } => val, Value::List { vals: val, .. } => val .into_iter() .map(|x| local_into_string(engine_state, x, ", ", serialize_types)) .collect::<Vec<_>>() .join(separator), Value::Record { val, .. } => val .into_owned() .into_iter() .map(|(x, y)| { format!( "{}: {}", x, local_into_string(engine_state, y, ", ", serialize_types) ) }) .collect::<Vec<_>>() .join(separator), 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); contents_string.to_string() } else { format!( "unable to retrieve block contents for text block_id {}", val.block_id.get() ) } } else { format!("closure_{}", val.block_id.get()) } } Value::Nothing { .. } => String::new(), Value::Error { error, .. } => format!("{error:?}"), Value::Binary { val, .. } => format!("{val:?}"), Value::CellPath { val, .. } => val.to_string(), // If we fail to collapse the custom value, just print <{type_name}> - failure is not // that critical here Value::Custom { val, .. } => val .to_base_value(span) .map(|val| local_into_string(engine_state, val, separator, serialize_types)) .unwrap_or_else(|_| format!("<{}>", val.type_name())), } } fn update_metadata(metadata: Option<PipelineMetadata>) -> Option<PipelineMetadata> { metadata .map(|md| md.with_content_type(Some(mime::TEXT_PLAIN.to_string()))) .or_else(|| { Some(PipelineMetadata::default().with_content_type(Some(mime::TEXT_PLAIN.to_string()))) }) } #[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(ToText {}) } #[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(ToText {})); 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 text | 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/plain"), 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/msgpackz.rs
crates/nu-command/src/formats/to/msgpackz.rs
use std::io::Write; use nu_engine::command_prelude::*; use nu_protocol::shell_error::io::IoError; use super::msgpack::write_value; const BUFFER_SIZE: usize = 65536; const DEFAULT_QUALITY: u32 = 3; // 1 can be very bad const DEFAULT_WINDOW_SIZE: u32 = 20; #[derive(Clone)] pub struct ToMsgpackz; impl Command for ToMsgpackz { fn name(&self) -> &str { "to msgpackz" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, Type::Binary) .named( "quality", SyntaxShape::Int, "Quality of brotli compression (default 3)", Some('q'), ) .named( "window-size", SyntaxShape::Int, "Window size for brotli compression (default 20)", Some('w'), ) .switch( "serialize", "serialize nushell types that cannot be deserialized", Some('s'), ) .category(Category::Formats) } fn description(&self) -> &str { "Convert Nu values into brotli-compressed MessagePack." } fn extra_description(&self) -> &str { "This is the format used by the plugin registry file ($nu.plugin-path)." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { fn to_u32(n: Spanned<i64>) -> Result<Spanned<u32>, ShellError> { u32::try_from(n.item) .map_err(|err| ShellError::CantConvert { to_type: "u32".into(), from_type: "int".into(), span: n.span, help: Some(err.to_string()), }) .map(|o| o.into_spanned(n.span)) } let quality = call .get_flag(engine_state, stack, "quality")? .map(to_u32) .transpose()?; let window_size = call .get_flag(engine_state, stack, "window-size")? .map(to_u32) .transpose()?; let serialize_types = call.has_flag(engine_state, stack, "serialize")?; let value_span = input.span().unwrap_or(call.head); let value = input.into_value(value_span)?; let mut out_buf = vec![]; let mut out = brotli::CompressorWriter::new( &mut out_buf, BUFFER_SIZE, quality.map(|q| q.item).unwrap_or(DEFAULT_QUALITY), window_size.map(|w| w.item).unwrap_or(DEFAULT_WINDOW_SIZE), ); write_value( &mut out, &value, 0, engine_state, call.head, serialize_types, )?; out.flush() .map_err(|err| IoError::new(err, call.head, None))?; drop(out); Ok(Value::binary(out_buf, 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/formats/to/tsv.rs
crates/nu-command/src/formats/to/tsv.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 ToTsv; impl Command for ToTsv { fn name(&self) -> &str { "to tsv" } fn signature(&self) -> Signature { Signature::build("to tsv") .input_output_types(vec![ (Type::record(), Type::String), (Type::table(), Type::String), ]) .switch( "noheaders", "do not output the column 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 description(&self) -> &str { "Convert table into .tsv text." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Outputs a TSV string representing the contents of this table", example: "[[foo bar]; [1 2]] | to tsv", result: Some(Value::test_string("foo\tbar\n1\t2\n")), }, Example { description: "Outputs a TSV string representing the contents of this record", example: "{a: 1 b: 2} | to tsv", result: Some(Value::test_string("a\tb\n1\t2\n")), }, Example { description: "Outputs a TSV stream with column names pre-determined", example: "[[foo bar baz]; [1 2 3]] | to tsv --columns [baz foo]", result: Some(Value::test_string("baz\tfoo\n3\t1\n")), }, ] } 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 columns: Option<Vec<String>> = call.get_flag(engine_state, stack, "columns")?; let config = engine_state.config.clone(); to_tsv(input, noheaders, columns, head, config) } } fn to_tsv( input: PipelineData, noheaders: bool, columns: Option<Vec<String>>, head: Span, config: Arc<Config>, ) -> Result<PipelineData, ShellError> { let sep = Spanned { item: '\t', span: head, }; to_delimited_data( ToDelimitedDataArgs { noheaders, separator: sep, columns, format_name: "TSV", input, head, content_type: Some(mime::TEXT_TAB_SEPARATED_VALUES.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(ToTsv {}) } #[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(ToTsv {})); 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 tsv | 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/tab-separated-values"), 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/mod.rs
crates/nu-command/src/formats/to/mod.rs
mod command; mod csv; mod delimited; mod json; mod md; mod msgpack; mod msgpackz; mod nuon; mod text; mod toml; mod tsv; mod xml; mod yaml; pub use self::csv::ToCsv; pub use self::toml::ToToml; pub use command::To; pub use json::ToJson; pub use md::ToMd; pub use msgpack::ToMsgpack; pub use msgpackz::ToMsgpackz; pub use nuon::ToNuon; pub use text::ToText; pub use tsv::ToTsv; pub use xml::ToXml; pub use yaml::{ToYaml, ToYml}; #[cfg(any(feature = "network", feature = "sqlite"))] pub(crate) use json::value_to_json_value;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false