diff --git a/src/core/extract.rs b/src/core/extract.rs deleted file mode 100644 index 6535513..0000000 --- a/src/core/extract.rs +++ /dev/null @@ -1,50 +0,0 @@ -use regex::Regex; -use std::sync::OnceLock; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Confidence { - /// Absolute path or path with explicit separator. - High, - /// Bare filename with extension; could be a word. - Low, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PathCandidate { - pub text: String, - pub confidence: Confidence, -} - -/// Heuristically extract path-like substrings from arbitrary text. -/// Confident matches (absolute paths, paths containing separators) → `High`. -/// Bare filenames with an extension → `Low` (advisory only). -pub fn extract_path_candidates(text: &str) -> Vec { - static UNIX_ABS: OnceLock = OnceLock::new(); - static WIN_ABS: OnceLock = OnceLock::new(); - static REL_WITH_SEP: OnceLock = OnceLock::new(); - static BARE_NAME: OnceLock = OnceLock::new(); - - let unix_abs = UNIX_ABS.get_or_init(|| Regex::new(r"(?m)(?:^|\s)(/[\w./~\-_]+)").unwrap()); - let win_abs = WIN_ABS.get_or_init(|| Regex::new(r#"(?m)(?:^|\s)([A-Za-z]:\\[\w.\\\-_]+)"#).unwrap()); - let rel = REL_WITH_SEP.get_or_init(|| Regex::new(r"(?m)(?:^|\s)((?:\./|\.\./|[\w\-_]+/)[\w./\-_]+)").unwrap()); - let bare = BARE_NAME.get_or_init(|| Regex::new(r"(?m)(?:^|\s)([\w\-_]+\.[A-Za-z]{1,8})(?:\s|[.,;:!?]|$)").unwrap()); - - let mut out = Vec::new(); - let mut seen = std::collections::HashSet::new(); - - for re in [unix_abs, win_abs, rel] { - for cap in re.captures_iter(text) { - let m = cap.get(1).unwrap().as_str().trim_end_matches(['.', ',', ';', ':', '!', '?']); - if seen.insert(m.to_string()) { - out.push(PathCandidate { text: m.to_string(), confidence: Confidence::High }); - } - } - } - for cap in bare.captures_iter(text) { - let m = cap.get(1).unwrap().as_str(); - if seen.insert(m.to_string()) { - out.push(PathCandidate { text: m.to_string(), confidence: Confidence::Low }); - } - } - out -} diff --git a/src/core/mod.rs b/src/core/mod.rs index 93522af..dda910b 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -2,13 +2,12 @@ pub mod botignore; pub mod decision; -pub mod extract; pub mod op; +pub mod paths; pub mod policy; pub mod project; pub mod secrets; pub use decision::{Decision, Reason, Rule}; -pub use extract::{extract_path_candidates, Confidence, PathCandidate}; pub use op::Op; pub use policy::Policy; diff --git a/src/core/paths.rs b/src/core/paths.rs new file mode 100644 index 0000000..fca630a --- /dev/null +++ b/src/core/paths.rs @@ -0,0 +1,240 @@ +//! Absolute paths, and the paths a command line names. +//! +//! A text check, no shell: it never expands `$VAR` or tracks `cd`, and it cannot see +//! inside `"$(...)"` or a script. It runs on every command call, so it leans towards +//! naming nothing: a word counts only where it can be a path the command reaches. + +use globset::Glob; +use std::path::{Component, Path, PathBuf}; + +/// Which shell's quoting a command is written in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dialect { Posix, PowerShell } + +/// What a command does with the paths it names: shows their text, shows at most a name +/// or a size, or anything else. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verb { Prints, Metadata, Other } + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CommandPath { + pub path: PathBuf, + pub verb: Verb, +} + +const PRINTS: &[&str] = &[ + "cat", "head", "tail", "less", "more", "bat", "nl", "tac", "cut", "sort", "uniq", "grep", "egrep", "fgrep", "rg", + "awk", "sed", "strings", "xxd", "od", "hexdump", "base64", "gc", "type", "get-content", "select-string", +]; +const METADATA: &[&str] = &["ls", "stat", "file", "test", "[", "[[", "du", "which", "echo", "printf"]; +const GIT_METADATA: &[&str] = &["status", "check-ignore", "ls-files", "commit"]; +/// Words that run what follows them. The shell's keywords are here because in +/// `if [ -f .env ]; then` the verb is `[`. +const PREFIXES: &[&str] = + &["sudo", "env", "time", "nohup", "command", "exec", "if", "elif", "then", "else", "while", "until", "do", "!", "{"]; +/// Verbs whose first word is a pattern, unless `-e` or `-f` gives it. +const PATTERN_FIRST: &[&str] = &["grep", "egrep", "fgrep", "rg", "awk", "sed"]; +const FIND_PATTERNS: &[&str] = &["-name", "-iname", "-path", "-ipath", "-wholename", "-regex"]; +const GLOB_CHARS: [char; 3] = ['*', '?', '[']; + +/// `path` against `base`, with `.` and `..` resolved by their text alone: the path may +/// not exist. `std::path::absolute` is newer than this crate's `rust-version`. +pub fn absolute(path: &Path, base: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for part in base.join(path).components() { + match part { + Component::CurDir => {} + Component::ParentDir => drop(out.pop()), + other => out.push(other.as_os_str()), + } + } + out +} + +#[derive(Default)] +struct Splitter { + segments: Vec>, + words: Vec, + word: Option, + heredoc: Option, +} + +impl Splitter { + fn push(&mut self, c: char) { + self.word.get_or_insert_with(String::new).push(c); + } + + fn end_word(&mut self) { + if let Some(word) = self.word.take() { + // `<<` opens a heredoc, `<<<` a one-word string. + if self.words.iter().rev().take_while(|w| *w == "<").count() == 2 { + self.heredoc = Some(word.trim_start_matches('-').to_string()); + } + self.words.push(word); + } + } + + fn end_segment(&mut self) { + self.end_word(); + if !self.words.is_empty() { + self.segments.push(std::mem::take(&mut self.words)); + } + } +} + +/// A command's words, one list per simple command. `<` and `>` are words of their own, +/// also when quoted, which a check this short can afford. A comment and a heredoc's +/// body are left out: they are text no command reads as a path. +pub fn segments(command: &str, dialect: Dialect) -> Vec> { + let chars: Vec = command.chars().collect(); + let escape = if dialect == Dialect::Posix { '\\' } else { '`' }; + let (mut s, mut quote, mut i) = (Splitter::default(), None, 0); + while i < chars.len() { + let c = chars[i]; + i += 1; + match (quote, c) { + (_, '\\') if dialect == Dialect::PowerShell => s.push('/'), + (Some('\''), '\'') | (Some('"'), '"') => quote = None, + (Some('\''), _) => s.push(c), + (_, _) if c == escape => { + // A line end after the escape joins the lines. + if let Some(next) = chars.get(i).filter(|next| **next != '\n') { + s.push(*next); + } + i += 1; + } + (Some(_), _) => s.push(c), + (None, '\'' | '"') => { + quote = Some(c); + s.word.get_or_insert_with(String::new); + } + (None, '#') if s.word.is_none() => i += chars[i..].iter().take_while(|next| **next != '\n').count(), + (None, '\n') => { + s.end_segment(); + // The body runs to its closing line, or to the end if it has none. + if let Some(delimiter) = s.heredoc.take() { + while i < chars.len() { + let line: String = chars[i..].iter().take_while(|next| **next != '\n').collect(); + i += line.chars().count() + 1; + if line.trim() == delimiter { + break; + } + } + } + } + (None, ';' | '|' | '&' | '(' | ')' | '`') => s.end_segment(), + (None, '<' | '>') => { + s.end_word(); + s.words.push(c.to_string()); + } + (None, _) if c.is_whitespace() => s.end_word(), + (None, _) => s.push(c), + } + } + s.end_segment(); + s.segments +} + +/// The paths `command` names, each with the verb that reaches it. `cwd` resolves them; +/// `home` expands a leading `~/`, `$HOME/`, `${HOME}/`. A redirect target is never the +/// verb or a pattern: `<` prints whatever the verb is, `>` takes the segment's verb, +/// and a heredoc's delimiter or a here-string names nothing. +pub fn command_paths(command: &str, dialect: Dialect, cwd: &Path, home: Option<&Path>) -> Vec { + let mut found = Vec::new(); + for words in segments(command, dialect) { + let (mut args, mut inputs, mut outputs) = (Vec::new(), Vec::new(), Vec::new()); + let mut rest = words.iter().map(String::as_str).peekable(); + while let Some(word) = rest.next() { + if word != "<" && word != ">" { + args.push(word); + continue; + } + let mut run = 1; + while rest.next_if_eq(&word).is_some() { + run += 1; + } + match (word, rest.next()) { + ("<", Some(target)) if run == 1 => inputs.push(target), + (">", Some(target)) => outputs.push(target), + _ => {} + } + } + let (verb, named) = named_words(&args); + let classed = inputs.iter().map(|word| (*word, Verb::Prints)); + for (word, verb) in classed.chain(named.iter().chain(&outputs).map(|word| (*word, verb))) { + found.extend(word_paths(word, cwd, home).into_iter().map(|path| CommandPath { path, verb })); + } + } + found +} + +/// The segment's verb class and the words that may name a path: not the verb word, a +/// flag or a pattern position. `--file=.env` and `X=.env` name what follows the `=`. +fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>) { + let is_name = |name: &str| !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_'); + let mut named = Vec::new(); + let (mut at, mut prefixed) = (0, false); + while let Some(word) = args.get(at) { + match word.split_once('=').filter(|(name, _)| is_name(name)) { + Some((_, value)) => named.push(value), + None if PREFIXES.contains(word) => prefixed = true, + None if prefixed && word.starts_with('-') => {} + None => break, + } + at += 1; + } + let Some(verb_word) = args.get(at) else { + return (Verb::Other, named); + }; + let rest = &args[at + 1..]; + let name = Path::new(verb_word).file_name().and_then(|n| n.to_str()).unwrap_or(verb_word).to_ascii_lowercase(); + let is_metadata = METADATA.contains(&name.as_str()) || (name == "git" && rest.first().is_some_and(|w| GIT_METADATA.contains(w))); + let verb = if PRINTS.contains(&name.as_str()) { Verb::Prints } else if is_metadata { Verb::Metadata } else { Verb::Other }; + + let pattern_first = PATTERN_FIRST.contains(&name.as_str()); + let mut pattern_due = pattern_first && !rest.iter().any(|w| matches!(*w, "-e" | "-f")); + let mut previous = ""; + for word in rest.iter().copied() { + let is_pattern = (pattern_first && previous == "-e") || (name == "find" && FIND_PATTERNS.contains(&previous)); + previous = word; + if is_pattern { + continue; + } + if !word.starts_with('-') { + if pattern_due { + pattern_due = false; + continue; + } + named.push(word); + } + named.extend(word.split_once('=').map(|(_, value)| value)); + } + (verb, named) +} + +/// The paths one word names. A word counts when it is a file or holds a separator; text +/// with spaces and an address hold one too, so they count only as a real file. A glob +/// reaches the files of its one directory and, as in a shell, a dotfile only when it +/// starts with `.`. +fn word_paths(word: &str, cwd: &Path, home: Option<&Path>) -> Vec { + let expanded = home + .and_then(|home| Some(home.join(["~/", "$HOME/", "${HOME}/"].iter().find_map(|p| word.strip_prefix(p))?))) + .map_or_else(|| word.to_string(), |path| path.to_string_lossy().into_owned()); + let (dir, name) = expanded.rsplit_once('/').unwrap_or(("", &expanded)); + if let Some(glob) = Glob::new(name).ok().filter(|_| name.contains(GLOB_CHARS) && !dir.contains(GLOB_CHARS)) { + let matcher = glob.compile_matcher(); + let dir = absolute(Path::new(if dir.is_empty() && expanded.starts_with('/') { "/" } else { dir }), cwd); + let entries = std::fs::read_dir(dir).into_iter().flatten().filter_map(|entry| Some(entry.ok()?.path())); + let mut files: Vec = entries + .filter(|path| { + let entry = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + matcher.is_match(entry) && (!entry.starts_with('.') || name.starts_with('.')) && path.is_file() + }) + .collect(); + files.sort(); + return files; + } + let path = absolute(Path::new(&expanded), cwd); + let prose = word.contains(char::is_whitespace) || word.contains("://"); + if path.is_file() || (word.contains('/') && !prose) { vec![path] } else { Vec::new() } +} diff --git a/tests/core_extract.rs b/tests/core_extract.rs deleted file mode 100644 index 72a07d9..0000000 --- a/tests/core_extract.rs +++ /dev/null @@ -1,39 +0,0 @@ -use dirigent_fermata::core::extract::{extract_path_candidates, Confidence}; - -#[test] -fn extracts_absolute_unix_path() { - let s = "the file is at /home/user/.env and was modified"; - let cs = extract_path_candidates(s); - assert!(cs.iter().any(|c| c.text == "/home/user/.env" && c.confidence == Confidence::High)); -} - -#[test] -fn extracts_absolute_windows_path() { - let s = r"see C:\Users\me\secret.toml for details"; - let cs = extract_path_candidates(s); - assert!(cs.iter().any(|c| c.text == r"C:\Users\me\secret.toml" && c.confidence == Confidence::High)); -} - -#[test] -fn extracts_relative_with_separator() { - let s = "modified src/lib.rs and tests/foo.rs"; - let cs = extract_path_candidates(s); - let texts: Vec<_> = cs.iter().map(|c| c.text.as_str()).collect(); - assert!(texts.contains(&"src/lib.rs")); - assert!(texts.contains(&"tests/foo.rs")); -} - -#[test] -fn bare_filename_with_extension_is_low_confidence() { - let s = "open README.md please"; - let cs = extract_path_candidates(s); - let r = cs.iter().find(|c| c.text == "README.md").unwrap(); - assert_eq!(r.confidence, Confidence::Low); -} - -#[test] -fn ignores_pure_words() { - let s = "the quick brown fox"; - let cs = extract_path_candidates(s); - assert!(cs.is_empty()); -} diff --git a/tests/core_paths.rs b/tests/core_paths.rs new file mode 100644 index 0000000..2e8c66e --- /dev/null +++ b/tests/core_paths.rs @@ -0,0 +1,455 @@ +//! What a command line names: `core::paths`. The rules run on every Bash call, so each +//! table holds what must be seen and what must be left alone. All files here are fake. + +use dirigent_fermata::core::paths::{absolute, command_paths, segments, Dialect, Verb}; +use std::fs; +use std::path::{Path, PathBuf}; +use tempfile::TempDir; +use Dialect::{Posix, PowerShell}; +use Verb::{Metadata, Other, Prints}; + +/// A project and a home of their own. +struct Fixture { + cwd: TempDir, + home: TempDir, +} + +fn fixture() -> Fixture { + let cwd = tempfile::tempdir().unwrap(); + for file in [".env", ".env.local", ".gitignore", "a.txt", "id_rsa", "vendor/bin/x", "my dir/.env", "sub/b.key"] { + let path = cwd.path().join(file); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, "").unwrap(); + } + fs::create_dir(cwd.path().join("build")).unwrap(); + let home = tempfile::tempdir().unwrap(); + fs::write(home.path().join("x"), "").unwrap(); + Fixture { cwd, home } +} + +impl Fixture { + /// Each path named, relative to the working directory or `~/` where it lies under one. + fn named(&self, command: &str, dialect: Dialect) -> Vec<(String, Verb)> { + command_paths(command, dialect, self.cwd.path(), Some(self.home.path())) + .into_iter() + .map(|named| (self.shown(&named.path), named.verb)) + .collect() + } + + fn shown(&self, path: &Path) -> String { + if let Ok(rel) = path.strip_prefix(self.cwd.path()) { + return rel.display().to_string(); + } + match path.strip_prefix(self.home.path()) { + Ok(rel) => format!("~/{}", rel.display()), + Err(_) => path.display().to_string(), + } + } +} + +fn check(dialect: Dialect, rows: &[(&str, &[(&str, Verb)])]) { + let f = fixture(); + for (command, expected) in rows { + let expected: Vec<(String, Verb)> = expected.iter().map(|(path, verb)| (path.to_string(), *verb)).collect(); + assert_eq!(f.named(command, dialect), expected, "{command:?}"); + } +} + +const ENV_PRINTS: &[(&str, Verb)] = &[(".env", Prints)]; +const ENV_METADATA: &[(&str, Verb)] = &[(".env", Metadata)]; +const ENV_OTHER: &[(&str, Verb)] = &[(".env", Other)]; +const NOTHING: &[(&str, Verb)] = &[]; + +// --------------------------------------------------------------------------- +// The spellings of one path +// --------------------------------------------------------------------------- + +#[test] +fn every_spelling_of_a_path_is_seen() { + check(Posix, &[ + ("cat .env", ENV_PRINTS), + ("cat ./.env", ENV_PRINTS), + ("cat ./sub/../.env", ENV_PRINTS), + ("cat \".env\"", ENV_PRINTS), + ("cat '.env'", ENV_PRINTS), + ("cat \\.env", ENV_PRINTS), + ("cat .e\"n\"v", ENV_PRINTS), + ("cat .env;false", ENV_PRINTS), + ("cat ./.env; false", ENV_PRINTS), + ("a&&cat .env", ENV_PRINTS), + ("a||cat .env", ENV_PRINTS), + ("a|cat .env", ENV_PRINTS), + ("a&cat .env", ENV_PRINTS), + ("(cat .env)", ENV_PRINTS), + ("$(cat .env)", ENV_PRINTS), + ("echo $(cat .env)", ENV_PRINTS), + ("echo `cat .env`", ENV_PRINTS), + ("ls\ncat .env", ENV_PRINTS), + ("ls\r\ncat .env\r\n", ENV_PRINTS), + ("cat \\\n .env", ENV_PRINTS), + ("cat \".env", ENV_PRINTS), + ("cat '.env", ENV_PRINTS), + ("cat .env 2>&1", ENV_PRINTS), + ("tool --file=.env", ENV_OTHER), + ("tool -f=./.env", ENV_OTHER), + ("tool file=.env", ENV_OTHER), + ]); +} + +#[test] +fn an_open_quote_runs_to_the_end_and_a_quote_keeps_its_separators() { + check(Posix, &[ + ("cat \".env; ls", NOTHING), + ("cat 'a; b' .env", ENV_PRINTS), + ("cat \"my dir/.env\"", &[("my dir/.env", Prints)]), + ("cat my\\ dir/.env", &[("my dir/.env", Prints)]), + ]); +} + +#[test] +fn a_word_after_an_input_redirect_is_a_printing_path_and_never_the_verb() { + check(Posix, &[ + ("<.env", ENV_PRINTS), + ("< .env", ENV_PRINTS), + ("<.env cat", ENV_PRINTS), + ("cat <.env", ENV_PRINTS), + ("wc -l < .env", ENV_PRINTS), + ("ls < .env", ENV_PRINTS), + ("<.env cat a.txt", &[(".env", Prints), ("a.txt", Prints)]), + // The verb is still the one after the redirect. + ("<.env rm a.txt", &[(".env", Prints), ("a.txt", Other)]), + ]); +} + +#[test] +fn a_word_after_an_output_redirect_takes_the_verb_of_its_segment() { + check(Posix, &[ + ("echo .env >> .gitignore", &[(".env", Metadata), (".gitignore", Metadata)]), + ("cat a.txt > .env", &[("a.txt", Prints), (".env", Prints)]), + (">a.txt cat .env", &[(".env", Prints), ("a.txt", Prints)]), + ("npm test > .env", ENV_OTHER), + ("cat .env 2>/dev/null", &[(".env", Prints), ("/dev/null", Prints)]), + ]); +} + +// --------------------------------------------------------------------------- +// Paths and globs +// --------------------------------------------------------------------------- + +#[test] +fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator() { + check(Posix, &[ + ("npm run build", NOTHING), + ("cat build", NOTHING), + ("cat a-word", NOTHING), + ("cat build/new", &[("build/new", Prints)]), + ("cat vendor/", &[("vendor", Prints)]), + ("cat ~/x", &[("~/x", Prints)]), + ("cat $HOME/x", &[("~/x", Prints)]), + ("cat ${HOME}/x", &[("~/x", Prints)]), + ]); + // No home known: the text stays as written, under the working directory. + let f = fixture(); + let named = command_paths("cat ~/x", Posix, f.cwd.path(), None); + assert_eq!(named[0].path, f.cwd.path().join("~/x")); +} + +/// A glob in an absolute path or under home reads that directory, not the working one. +#[test] +fn a_glob_reads_the_directory_it_names() { + let f = fixture(); + assert_eq!(f.named("cat ~/x*", Posix), vec![("~/x".to_string(), Prints)]); + let absolute_glob = format!("cat {}/.env*", f.cwd.path().display()); + assert_eq!(f.named(&absolute_glob, Posix), vec![(".env".to_string(), Prints), (".env.local".to_string(), Prints)]); + let at_root = f.named("cat /*", Posix); + assert!(at_root.iter().all(|(path, _)| path.starts_with('/')), "{at_root:?}"); +} + +#[test] +fn prose_and_addresses_name_no_path_unless_such_a_file_exists() { + check(Posix, &[ + ("git commit -m \"fix .env loading\"", NOTHING), + ("tool \"see vendor/a for it\"", NOTHING), + ("curl https://example.invalid/.env", NOTHING), + ("curl https://example.invalid/x.key?a=b", NOTHING), + ("tool \"my dir/.env\"", &[("my dir/.env", Other)]), + ]); +} + +#[test] +fn a_glob_matches_the_entries_of_its_one_directory() { + check(Posix, &[ + ("cat .env*", &[(".env", Prints), (".env.local", Prints)]), + ("cat .e?v", ENV_PRINTS), + ("cat [.]env", NOTHING), + // A shell does not expand `*` to a dotfile. + ("cat *", &[("a.txt", Prints), ("id_rsa", Prints)]), + ("cat ?env", NOTHING), + ("cat sub/*.key", &[("sub/b.key", Prints)]), + ("cat missing/*.key", NOTHING), + ("ls *.key", NOTHING), + ("ls id_*", &[("id_rsa", Metadata)]), + // A directory among the entries is no file, as `cat build` names none. + ("cat b*", NOTHING), + // A glob over directories is left as written, and the rules read it as a path. + ("cat */.env", &[("*/.env", Prints)]), + ("cat */*.key", &[("*/*.key", Prints)]), + // Not a glob a matcher can read. + ("cat .env[", NOTHING), + ]); +} + +// --------------------------------------------------------------------------- +// Verb classes +// --------------------------------------------------------------------------- + +#[test] +fn every_printing_verb_prints() { + let f = fixture(); + for verb in ["cat", "head", "tail", "less", "more", "bat", "nl", "tac", "cut", "sort", "uniq", "strings", "xxd", "od", "hexdump", "base64", "gc", "type", "get-content", "select-string"] { + assert_eq!(f.named(&format!("{verb} .env"), Posix), vec![(".env".to_string(), Prints)], "{verb}"); + } + for verb in ["grep", "egrep", "fgrep", "rg", "awk", "sed"] { + assert_eq!(f.named(&format!("{verb} x .env"), Posix), vec![(".env".to_string(), Prints)], "{verb}"); + } +} + +#[test] +fn every_metadata_verb_is_metadata() { + check(Posix, &[ + ("ls -la .env", ENV_METADATA), + ("stat .env", ENV_METADATA), + ("file .env", ENV_METADATA), + ("test -f .env", ENV_METADATA), + ("[ -f .env ]", ENV_METADATA), + ("[[ -f .env ]]", ENV_METADATA), + ("du .env", ENV_METADATA), + ("which .env", ENV_METADATA), + ("echo .env", ENV_METADATA), + ("printf %s .env", ENV_METADATA), + ("git status .env", ENV_METADATA), + ("git check-ignore .env", ENV_METADATA), + ("git ls-files .env", ENV_METADATA), + ("git commit -m .env", ENV_METADATA), + ]); +} + +#[test] +fn everything_else_is_other() { + check(Posix, &[ + ("source .env", ENV_OTHER), + (". .env", ENV_OTHER), + ("source .env && npm test", ENV_OTHER), + ("cp .env a-copy", ENV_OTHER), + ("mv .env a-copy", ENV_OTHER), + ("rm .env", ENV_OTHER), + ("python .env", ENV_OTHER), + ("docker cp .env c:/x", &[(".env", Other), ("c:/x", Other)]), + ("git add .env", ENV_OTHER), + ("git diff .env", ENV_OTHER), + ("git", NOTHING), + ("ssh -i id_rsa host", &[("id_rsa", Other)]), + ("chmod 600 id_rsa", &[("id_rsa", Other)]), + ("openssl rsa -in sub/b.key", &[("sub/b.key", Other)]), + ]); +} + +#[test] +fn the_verb_comes_after_assignments_and_prefixes() { + check(Posix, &[ + ("sudo cat .env", ENV_PRINTS), + ("sudo -n cat .env", ENV_PRINTS), + ("X=1 cat .env", ENV_PRINTS), + ("X=1 Y=2 cat .env", ENV_PRINTS), + ("env X=1 cat .env", ENV_PRINTS), + ("env -i cat .env", ENV_PRINTS), + ("time cat .env", ENV_PRINTS), + ("nohup cat .env", ENV_PRINTS), + ("command cat .env", ENV_PRINTS), + ("exec cat .env", ENV_PRINTS), + ("/usr/bin/cat .env", ENV_PRINTS), + ("CAT .env", ENV_PRINTS), + ("X=.env cat a.txt", &[(".env", Prints), ("a.txt", Prints)]), + ("X=.env; cat $X", ENV_OTHER), + ("sudo ls .env", ENV_METADATA), + // Nothing left to run. + ("env", NOTHING), + ("env; false", NOTHING), + ("X=1", NOTHING), + ]); +} + +#[test] +fn the_verb_word_is_never_a_path() { + check(Posix, &[ + ("vendor/bin/x", NOTHING), + ("./.env", NOTHING), + (".env", NOTHING), + ("vendor/bin/x .env", ENV_OTHER), + ("sudo vendor/bin/x", NOTHING), + ]); +} + +#[test] +fn a_shell_keyword_is_no_verb() { + check(Posix, &[ + ("if [ -f .env ]; then echo yes; fi", ENV_METADATA), + ("if test -f .env; then echo yes; fi", ENV_METADATA), + ("if true; then cat id_rsa; fi", &[("id_rsa", Prints)]), + ("while true; do cat .env; done", ENV_PRINTS), + ("if false; then ls; else cat .env; fi", ENV_PRINTS), + ("! test -f .env", ENV_METADATA), + ("{ cat .env; }", ENV_PRINTS), + ]); +} + +// --------------------------------------------------------------------------- +// Pattern positions +// --------------------------------------------------------------------------- + +#[test] +fn the_first_word_of_a_pattern_verb_is_its_pattern() { + check(Posix, &[ + ("grep .env .gitignore", &[(".gitignore", Prints)]), + ("grep -n .env .gitignore", &[(".gitignore", Prints)]), + ("grep --color=auto .env .gitignore", &[(".gitignore", Prints)]), + ("rg .env", NOTHING), + ("sed s/.env/x/ a.txt", &[("a.txt", Prints)]), + ("awk '/.env/' a.txt", &[("a.txt", Prints)]), + ("grep -e x .env", ENV_PRINTS), + ("sed -e s/a/b/ .env", ENV_PRINTS), + ("sed -e s/.env/x/ a.txt", &[("a.txt", Prints)]), + ("sed -E s/.env/x/ a.txt", &[("a.txt", Prints)]), + ("grep -f .env a.txt", &[(".env", Prints), ("a.txt", Prints)]), + ("awk -f .env a.txt", &[(".env", Prints), ("a.txt", Prints)]), + ("grep x .env a.txt", &[(".env", Prints), ("a.txt", Prints)]), + ]); +} + +#[test] +fn a_finds_pattern_names_no_path() { + check(Posix, &[ + ("find . -name .env", NOTHING), + ("find . -iname .env", NOTHING), + ("find . -path ./.env", NOTHING), + ("find . -ipath ./.env", NOTHING), + ("find . -wholename ./.env", NOTHING), + ("find . -regex ./.env", NOTHING), + ("find . -name '*.key'", NOTHING), + ("find sub", NOTHING), + ("find sub/ -name x", &[("sub", Other)]), + ]); +} + +// --------------------------------------------------------------------------- +// What is not a command +// --------------------------------------------------------------------------- + +#[test] +fn a_comment_names_nothing() { + check(Posix, &[ + ("# read .env first\nls", NOTHING), + ("npm test # see .env", NOTHING), + ("ls # cat .env\ncat a.txt", &[("a.txt", Prints)]), + // Not at the start of a word, or quoted: no comment. + ("cat a#b .env", ENV_PRINTS), + ("tool \"#\" .env", ENV_OTHER), + ]); +} + +#[test] +fn a_heredoc_body_is_text() { + check(Posix, &[ + ("cat > a.txt < a.txt <<'EOF'\nsee cat .env\nEOF", &[("a.txt", Prints)]), + ("cat > a.txt << \"EOF\"\nsee cat .env\nEOF\ncat .env", &[("a.txt", Prints), (".env", Prints)]), + ("cat > a.txt <<-EOF\n\tsee cat .env\n\tEOF\ncat .env", &[("a.txt", Prints), (".env", Prints)]), + ("git commit -F - <c", Posix), [vec!["a", "<", "b", ">", "c"]]); + assert_eq!(split("a\\b", PowerShell), [vec!["a/b"]]); + assert_eq!(split("a`;b", PowerShell), [vec!["a;b"]]); + assert!(split("", Posix).is_empty()); + assert!(split(" # only a comment", Posix).is_empty()); +} + +#[test] +fn absolute_resolves_lexically() { + let base = Path::new("/p/q"); + for (path, expected) in [ + (".env", "/p/q/.env"), + ("./.env", "/p/q/.env"), + ("../b/x", "/p/b/x"), + ("../../../x", "/x"), + ("a/./b/../c", "/p/q/a/c"), + ("/abs/./y/../z", "/abs/z"), + ("", "/p/q"), + ] { + assert_eq!(absolute(Path::new(path), base), PathBuf::from(expected), "{path:?}"); + } +}