//! Pipelines of records: a command line's commands joined by `|`, each //! one's records the next one's input (`docs/terminal-and-agent.md`), and //! the filters that take a table or lines in and give them out changed: //! `where`, `sort`, `first` and `pick`. //! //! A filter works on rows under named columns. Text is rows too, a line //! each, under the one column `Line`, and leaves as text. Cells compare as //! quantities when both are one (`12`, `1.5 KB`, `3 MB`: a size as `ls` //! says it), else as text, case aside. use alloc::string::String; use alloc::vec::Vec; use core::cmp::Ordering; /// The filters, and what each does: the terminal's `help` lists them. pub const FILTERS: &[(&str, &str)] = &[ ( "where", "Only the rows that match: ls | where Size > 1 MB; where Name ~ txt; where word", ), ( "sort", "The rows in order of a column: ls | sort Size, sort Size down", ), ("first", "The first rows: ls | first 5"), ("last", "The last rows: log | last 20"), ("pick", "Only these columns: ls | pick Name Size"), ("count", "How many rows or lines: ls | count"), ( "unique", "Each row once, in the order they came: cat names.txt | unique", ), ( "save", "What comes in written to a file, as text (> and >> do it too): ps | save ps.txt", ), ]; /// Commands that read files, and after a `|` are the filter they are /// elsewhere: `head` is `first`, `tail` `last`, `grep` `where`, `wc` /// `count`. pub const AS_FILTERS: [&str; 4] = ["head", "tail", "grep", "wc"]; /// The environment variable a command in a pipeline, after the first, /// is started with: its stdin is the command before it. pub const PIPED: &str = "PIPED"; /// The column text is in. pub const LINE: &str = "Line"; /// The commands of `line`, split at each `|` outside quotes, each trimmed. /// One command when there is no `|`, and when the line is the agent's: its /// task is its own text. pub fn stages(line: &str) -> Vec<&str> { let line = line.trim(); if line.split_whitespace().next() == Some("agent") { return alloc::vec![line]; } split_outside(line, |rest| rest.starts_with('|').then_some(1)) .into_iter() .map(|(_, part)| part.trim()) .collect() } /// `line` split where `separator` (given what is left of the line, the /// length of the separator found there, if one is) finds one outside /// quotes: each part with the separator before it ("" for the first). fn split_outside(line: &str, separator: impl Fn(&str) -> Option) -> Vec<(&str, &str)> { let mut parts = Vec::new(); let (mut start, mut before) = (0, ""); let mut quote: Option = None; let mut chars = line.char_indices(); while let Some((i, c)) = chars.next() { match (quote, c) { (Some(q), _) if c == q => quote = None, (Some('"'), '\\') | (None, '\\') => { chars.next(); } (Some(_), _) => {} (None, '"' | '\'') => quote = Some(c), (None, _) => { if let Some(len) = separator(&line[i..]) { parts.push((before, &line[start..i])); before = &line[i..i + len]; start = i + len; // The separator's other characters are not looked at again. for _ in 1..line[i..i + len].chars().count() { chars.next(); } } } } } parts.push((before, &line[start..])); parts } /// How a command of a line is joined to the one before it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Join { /// `;`, or the first: it runs whatever the one before did. Then, /// `&&`: it runs only if the one before succeeded. IfDone, } /// The commands of `line`, run one after another: split at each `;` and /// `&&` outside quotes, empty ones left out. One for the agent's line, /// whose task is its own text. pub fn sequence(line: &str) -> Vec<(Join, &str)> { let line = line.trim(); if line.split_whitespace().next() == Some("agent") { return alloc::vec![(Join::Then, line)]; } let found = split_outside(line, |rest| match () { _ if rest.starts_with("&&") => Some(2), _ if rest.starts_with(';') => Some(1), _ => None, }); found .into_iter() .map(|(before, part)| { ( if before == "&&" { Join::IfDone } else { Join::Then }, part.trim(), ) }) .filter(|(_, part)| !part.is_empty()) .collect() } /// A word of a command, its quotes taken off; `quoted` when any of it /// was in quotes or escaped, so a `>` in it is a word, not a redirection. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Word { pub text: String, pub quoted: bool, } /// The words of a command: split at spaces outside quotes, `"…"` and /// `'…'` taken whole, a `\` keeping the character after it (in double /// quotes too, not in single). pub fn lex(command: &str) -> Vec { let mut words = Vec::new(); let mut word: Option = None; let mut quote: Option = None; let mut chars = command.chars(); while let Some(c) = chars.next() { let w = word.get_or_insert_with(|| Word { text: String::new(), quoted: false, }); match (quote, c) { (Some(q), _) if c == q => quote = None, (Some('"') | None, '\\') => { w.quoted = true; if let Some(next) = chars.next() { w.text.push(next); } } (Some(_), _) => w.text.push(c), (None, '"' | '\'') => { w.quoted = true; quote = Some(c); } (None, c) if c.is_whitespace() => { if let Some(w) = word.take().filter(|w| w.quoted || !w.text.is_empty()) { words.push(w); } } (None, c) => w.text.push(c), } } if let Some(w) = word.filter(|w| w.quoted || !w.text.is_empty()) { words.push(w); } words } /// The words of a command, as [`lex`] finds them. pub fn words(command: &str) -> Vec { lex(command).into_iter().map(|w| w.text).collect() } /// Where a command's output goes instead of the screen: `> file` /// (replaced) or `>> file` (added to) at its end, or `>file` as one word. /// The command's words without it, and the file and whether to add; `None` /// when there is no redirection. In `where Size > 1 MB` the `>` compares: /// a filter's operator is its third word. #[allow(clippy::type_complexity)] pub fn redirect(words: &[Word]) -> Result, String, bool)>, String> { let bare = |w: &Word, s: &str| !w.quoted && w.text == s; let operator = |i: usize| i == 2 && words.first().is_some_and(|w| w.text == "where"); let at = words.iter().enumerate().rposition(|(i, w)| { !w.quoted && w.text.starts_with('>') && !w.text.starts_with(">=") && !operator(i) }); let Some(at) = at else { return Ok(None) }; let w = &words[at]; let (append, joined) = match () { _ if bare(w, ">") => (false, None), _ if bare(w, ">>") => (true, None), _ if w.text.starts_with(">>") => (true, Some(&w.text[2..])), _ => (false, Some(&w.text[1..])), }; let (file, rest) = match joined { Some(file) => (String::from(file), &words[at + 1..]), None => match words.get(at + 1) { Some(f) => (f.text.clone(), &words[at + 2..]), None => return Err("> and a file to write to: ls > list.txt".into()), }, }; if !rest.is_empty() || file.is_empty() { return Err("> and one file, at the command's end: ls > list.txt".into()); } let before = words[..at].iter().map(|w| w.text.clone()).collect(); Ok(Some((before, file, append))) } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Op { Equal, NotEqual, Less, LessOrEqual, Greater, GreaterOrEqual, /// The cell holds the value, case aside. Contains, NotContains, } impl Op { fn parse(word: &str) -> Option { Some(match word { "=" | "==" | "is" => Op::Equal, "!=" | "not" => Op::NotEqual, "<" => Op::Less, "<=" => Op::LessOrEqual, ">" => Op::Greater, ">=" => Op::GreaterOrEqual, "~" | "has" => Op::Contains, "!~" => Op::NotContains, _ => return None, }) } fn holds(self, cell: &str, value: &str) -> bool { let lower = |s: &str| s.to_lowercase(); match self { Op::Contains => lower(cell).contains(&lower(value)), Op::NotContains => !lower(cell).contains(&lower(value)), Op::Equal => compare(cell, value) == Ordering::Equal, Op::NotEqual => compare(cell, value) != Ordering::Equal, // Order asks for like with like: no size is more than a name. _ if quantity(cell).is_some() != quantity(value).is_some() => false, Op::Less => compare(cell, value) == Ordering::Less, Op::LessOrEqual => compare(cell, value) != Ordering::Greater, Op::Greater => compare(cell, value) == Ordering::Greater, Op::GreaterOrEqual => compare(cell, value) != Ordering::Less, } } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum Filter { /// Rows whose `column` holds `op` `value`; with no column, rows with /// any cell containing `value`. Where { column: Option, op: Op, value: String, }, /// Rows in order of `column` (the first with none), smallest first or /// `down`. Sort { column: Option, down: bool, }, First(usize), Last(usize), Pick(Vec), /// How many rows: one cell. Count, /// Each row once, the first of its kind kept. Unique, } /// How many rows `head 5`, `head -n 5`, `head -5` or `head` ask for. fn how_many(name: &str, rest: &[&str]) -> Result { let n = match rest { [] => return Ok(10), ["-n", n] => *n, [n] => n.strip_prefix('-').unwrap_or(n), _ => return Err(alloc::format!("{name} and how many: {name} 5")), }; n.parse() .map_err(|_| alloc::format!("{name} and how many: {name} 5, not “{n}”")) } impl Filter { /// The filter a command's words ask for, its own name first; what is /// wrong with them, said, if they ask for none. pub fn parse(words: &[&str]) -> Result { let (name, rest) = words.split_first().ok_or("No filter")?; match (*name, rest) { ("where", []) => Err("where and what to keep: where Name ~ txt, where Size > 1 MB".into()), ("where", [value]) => Ok(Filter::Where { column: None, op: Op::Contains, value: String::from(*value), }), ("where", [column, op, value @ ..]) if Op::parse(op).is_some() && !value.is_empty() => { Ok(Filter::Where { column: Some(String::from(*column)), op: Op::parse(op).unwrap(), value: value.join(" "), }) } ("where", _) => { Err("where Column, then = != < <= > >= or ~ (holds), then a value: where Size > 1 MB".into()) } ("sort", []) => Ok(Filter::Sort { column: None, down: false, }), ("sort", [column]) | ("sort", [column, "up"]) => Ok(Filter::Sort { column: Some(String::from(*column)), down: false, }), ("sort", [column, "down"]) => Ok(Filter::Sort { column: Some(String::from(*column)), down: true, }), ("sort", _) => Err("sort, a column, and down for the largest first: sort Size down".into()), ("first" | "head", rest) => how_many(name, rest).map(Filter::First), ("last" | "tail", rest) => how_many(name, rest).map(Filter::Last), ("pick", []) => Err("pick and the columns to keep: pick Name Size".into()), ("pick", columns) => Ok(Filter::Pick(columns.iter().map(|&c| c.into()).collect())), ("count" | "wc", _) => Ok(Filter::Count), ("unique", []) => Ok(Filter::Unique), ("unique", _) => Err("unique takes nothing after it: ls | pick Size | unique".into()), // Case aside always, so -i asks for nothing more. ("grep", rest) => { let rest: Vec<&str> = rest.iter().copied().filter(|w| *w != "-i").collect(); match rest.as_slice() { ["-v", value] => Ok(Filter::Where { column: None, op: Op::NotContains, value: String::from(*value), }), [value] => Ok(Filter::Where { column: None, op: Op::Contains, value: String::from(*value), }), _ => Err("grep and what to look for (in quotes if it has spaces): grep error".into()), } } (other, _) => Err(alloc::format!("{other} is not a filter")), } } /// The table, filtered; what is wrong, said, when it names a column the /// table does not have. #[allow(clippy::type_complexity)] pub fn table( &self, columns: Vec, mut rows: Vec>, ) -> Result<(Vec, Vec>), String> { let find = |name: &str| { columns .iter() .position(|c| c.eq_ignore_ascii_case(name)) // A table without headers has its columns by number, from 1. .or_else(|| { name.parse::() .ok() .filter(|&n| n >= 1 && n <= columns.len()) .map(|n| n - 1) }) .ok_or_else(|| { let named: Vec<&str> = columns .iter() .map(String::as_str) .filter(|c| !c.is_empty()) .collect(); match named.is_empty() { true => alloc::format!( "No column “{name}”: these columns have no names, so 1 to {}", columns.len() ), false => alloc::format!("No column “{name}”: the columns are {}", named.join(", ")), } }) }; match self { Filter::Where { column: None, op, value, } => { let value = value.to_lowercase(); let keep = *op != Op::NotContains; rows.retain(|r| r.iter().any(|c| c.to_lowercase().contains(&value)) == keep); } Filter::Where { column: Some(column), op, value, } => { let i = find(column)?; rows.retain(|r| op.holds(cell(r, i), value)); } Filter::Sort { column, down } => { let i = column.as_deref().map_or(Ok(0), find)?; // Stable, so rows that tie keep the order they came in. rows.sort_by(|a, b| { let (a, b) = (cell(a, i), cell(b, i)); // Empty cells last, either way. match (a.is_empty(), b.is_empty()) { (true, false) => Ordering::Greater, (false, true) => Ordering::Less, _ if *down => compare(b, a), _ => compare(a, b), } }); } Filter::First(n) => rows.truncate(*n), Filter::Last(n) => { rows.drain(..rows.len().saturating_sub(*n)); } Filter::Count => { return Ok(( alloc::vec![String::from("Count")], alloc::vec![alloc::vec![alloc::format!("{}", rows.len())]], )); } Filter::Unique => { let mut seen = alloc::collections::BTreeSet::new(); rows.retain(|r| seen.insert(r.clone())); } Filter::Pick(wanted) => { let picked = wanted.iter().map(|w| find(w)).collect::, _>>()?; let columns = picked.iter().map(|&i| columns[i].clone()).collect(); let rows = rows .iter() .map(|r| picked.iter().map(|&i| String::from(cell(r, i))).collect()) .collect(); return Ok((columns, rows)); } } Ok((columns, rows)) } /// Lines of text, filtered as rows of the one column [`LINE`]; `pick` /// has nothing to pick from them but that. pub fn lines(&self, lines: Vec) -> Result, String> { let rows = lines.into_iter().map(|l| alloc::vec![l]).collect(); let (_, rows) = self.table(alloc::vec![String::from(LINE)], rows)?; Ok(rows.into_iter().map(|mut r| r.swap_remove(0)).collect()) } } /// Row `row`'s cell `i`, empty when it is short of one. fn cell(row: &[String], i: usize) -> &str { row.get(i).map_or("", String::as_str) } /// A cell as an amount: a number, and after it a size's unit (B, KB, MB, /// GB, TB, as `ls` says them) or nothing. pub fn quantity(cell: &str) -> Option { let cell = cell.trim(); let end = cell .char_indices() .find(|&(i, c)| !(c.is_ascii_digit() || c == '.' || (c == '-' && i == 0))) .map_or(cell.len(), |(i, _)| i); let number: f64 = cell[..end].parse().ok()?; let unit = match cell[end..].trim().to_ascii_uppercase().as_str() { "" | "B" => 1u64, "K" | "KB" => 1 << 10, "M" | "MB" => 1 << 20, "G" | "GB" => 1 << 30, "T" | "TB" => 1 << 40, _ => return None, }; Some(number * unit as f64) } /// Two cells in order: as amounts when both are, else as text, case aside. pub fn compare(a: &str, b: &str) -> Ordering { match (quantity(a), quantity(b)) { (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(Ordering::Equal), _ => a.to_lowercase().cmp(&b.to_lowercase()), } } #[cfg(test)] mod tests { use super::*; use alloc::vec; fn parse(line: &str) -> Filter { Filter::parse(&line.split_whitespace().collect::>()).unwrap() } fn ls() -> (Vec, Vec>) { let row = |n: &str, s: &str| vec![String::from(n), String::from(s), String::from("2026-11-28 10:00")]; ( vec!["Name".into(), "Size".into(), "Changed".into()], vec![ row("apps/", ""), row("LICENSE", "4.3 KB"), row("big.ttf", "1.2 MB"), row("small.ttf", "900 B"), row("notes.txt", "12 B"), ], ) } fn names(rows: &[Vec]) -> Vec<&str> { rows.iter().map(|r| r[0].as_str()).collect() } #[test] fn a_line_splits_at_its_bars() { assert_eq!(stages("ls | sort Size|first 2"), ["ls", "sort Size", "first 2"]); assert_eq!(stages("ls"), ["ls"]); assert_eq!(stages("ls |"), ["ls", ""]); assert_eq!( stages("agent say a | b"), ["agent say a | b"], "the agent's task is its own" ); } #[test] fn sizes_are_amounts() { assert_eq!(quantity("12"), Some(12.0)); assert_eq!(quantity("1.5 KB"), Some(1536.0)); assert_eq!(quantity("2MB"), Some(2.0 * 1048576.0)); assert_eq!(quantity("-3"), Some(-3.0)); assert_eq!(quantity(""), None); assert_eq!( quantity("2026-11-28 10:00"), None, "a date is text, which sorts as one" ); assert_eq!(quantity("12 apples"), None); assert_eq!(compare("900 B", "4.3 KB"), Ordering::Less); assert_eq!(compare("9", "10"), Ordering::Less, "not as text"); assert_eq!(compare("b", "A"), Ordering::Greater); } #[test] fn where_keeps_what_matches() { let (columns, rows) = ls(); let (_, kept) = parse("where Size > 1 KB") .table(columns.clone(), rows.clone()) .unwrap(); assert_eq!( names(&kept), ["LICENSE", "big.ttf"], "a folder has no size to compare" ); let (_, kept) = parse("where name ~ TTF") .table(columns.clone(), rows.clone()) .unwrap(); assert_eq!(names(&kept), ["big.ttf", "small.ttf"]); let (_, kept) = parse("where Size <= 900B") .table(columns.clone(), rows.clone()) .unwrap(); assert_eq!(names(&kept), ["small.ttf", "notes.txt"]); let (_, kept) = parse("where notes").table(columns.clone(), rows.clone()).unwrap(); assert_eq!(names(&kept), ["notes.txt"]); let (_, kept) = parse("where Name != license").table(columns, rows).unwrap(); assert_eq!(kept.len(), 4); } #[test] fn sort_orders_by_amount_or_text() { let (columns, rows) = ls(); let (_, sorted) = parse("sort Size").table(columns.clone(), rows.clone()).unwrap(); assert_eq!( names(&sorted), ["notes.txt", "small.ttf", "LICENSE", "big.ttf", "apps/"], "the folder, with no size, last" ); let (_, sorted) = parse("sort Size down") .table(columns.clone(), rows.clone()) .unwrap(); assert_eq!( names(&sorted), ["big.ttf", "LICENSE", "small.ttf", "notes.txt", "apps/"] ); let (_, sorted) = parse("sort").table(columns, rows).unwrap(); assert_eq!( names(&sorted), ["apps/", "big.ttf", "LICENSE", "notes.txt", "small.ttf"] ); } #[test] fn first_and_pick() { let (columns, rows) = ls(); let (_, two) = parse("first 2").table(columns.clone(), rows.clone()).unwrap(); assert_eq!(names(&two), ["apps/", "LICENSE"]); let (picked, rows) = parse("pick size NAME").table(columns, rows).unwrap(); assert_eq!(picked, ["Size", "Name"]); assert_eq!(rows[1], ["4.3 KB", "LICENSE"]); } #[test] fn a_wrong_column_is_named() { let (columns, rows) = ls(); let why = parse("sort Kind").table(columns, rows).unwrap_err(); assert_eq!(why, "No column “Kind”: the columns are Name, Size, Changed"); let unnamed = vec![String::new(), String::new()]; let rows = vec![vec!["b".into(), "1".into()], vec!["a".into(), "2".into()]]; let (_, sorted) = parse("sort 1").table(unnamed, rows).unwrap(); assert_eq!( sorted[0][0], "a", "a table without names has its columns by number" ); } #[test] fn lines_are_rows_of_one_column() { let lines = vec!["pear".into(), "apple".into(), "fig".into()]; assert_eq!( parse("sort").lines(lines.clone()).unwrap(), ["apple", "fig", "pear"] ); assert_eq!(parse("where p").lines(lines.clone()).unwrap(), ["pear", "apple"]); assert_eq!(parse("first 1").lines(lines).unwrap(), ["pear"]); } #[test] fn quotes_keep_words_whole() { assert_eq!(words(r#"grep "two words" a.txt"#), ["grep", "two words", "a.txt"]); assert_eq!(words("echo 'it''s' \"a \\\"b\\\"\""), ["echo", "its", "a \"b\""]); assert_eq!(words(r"cat my\ file"), ["cat", "my file"]); assert_eq!( words("touch ''"), ["touch", ""], "an empty word in quotes is a word" ); assert_eq!(words(" ls -r "), ["ls", "-r"]); assert_eq!( stages(r#"cat a | where Line ~ "x | y" | first 2"#), ["cat a", r#"where Line ~ "x | y""#, "first 2"], "a | in quotes is text" ); } #[test] fn a_line_runs_one_command_after_another() { assert_eq!( sequence("cd logs && ls; pwd"), [(Join::Then, "cd logs"), (Join::IfDone, "ls"), (Join::Then, "pwd")] ); assert_eq!(sequence("echo \"a; b\""), [(Join::Then, "echo \"a; b\"")]); assert_eq!(sequence("ls;;"), [(Join::Then, "ls")]); assert_eq!( sequence("agent do a; then b"), [(Join::Then, "agent do a; then b")] ); } #[test] fn a_redirection_is_found_at_the_end() { let r = |line: &str| redirect(&lex(line)); assert_eq!( r("ls > list.txt").unwrap(), Some((vec!["ls".into()], "list.txt".into(), false)) ); assert_eq!( r("ps >>ps.txt").unwrap(), Some((vec!["ps".into()], "ps.txt".into(), true)) ); assert_eq!(r("where Size > 1 MB").unwrap(), None, "a filter's > compares"); assert_eq!( r("where Size > 1MB > big.txt").unwrap(), Some(( vec!["where".into(), "Size".into(), ">".into(), "1MB".into()], "big.txt".into(), false )) ); assert_eq!(r("echo \">\" x").unwrap(), None, "a quoted > is a word"); assert!(r("ls >").is_err()); assert!(r("ls > a b").is_err()); } #[test] fn last_count_unique_and_the_file_commands_piped() { let lines = vec!["b".into(), "a".into(), "b".into(), "c".into()]; assert_eq!(parse("last 2").lines(lines.clone()).unwrap(), ["b", "c"]); assert_eq!(parse("tail -n 1").lines(lines.clone()).unwrap(), ["c"]); assert_eq!(parse("head -2").lines(lines.clone()).unwrap(), ["b", "a"]); assert_eq!(parse("unique").lines(lines.clone()).unwrap(), ["b", "a", "c"]); assert_eq!(parse("count").lines(lines.clone()).unwrap(), ["4"]); assert_eq!(parse("wc").lines(lines.clone()).unwrap(), ["4"]); assert_eq!(parse("grep B").lines(lines.clone()).unwrap(), ["b", "b"]); assert_eq!(parse("grep -v b").lines(lines).unwrap(), ["a", "c"]); let (columns, rows) = ls(); let (c, counted) = parse("count").table(columns, rows).unwrap(); assert_eq!( (c, counted), (vec![String::from("Count")], vec![vec![String::from("5")]]) ); } #[test] fn wrong_words_say_how() { let err = |l: &str| Filter::parse(&l.split_whitespace().collect::>()).unwrap_err(); assert!(err("where").starts_with("where and what")); assert!(err("where Size big 3").starts_with("where Column")); assert!(err("first many").contains("“many”")); assert!(err("sort Size sideways").starts_with("sort, a column")); } }