//! 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, Writes}; /// 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", Writes)]), ]); } #[test] fn a_word_after_an_output_redirect_is_written() { check(Posix, &[ ("echo .env >> .gitignore", &[(".env", Metadata), (".gitignore", Writes)]), ("cat a.txt > .env", &[("a.txt", Prints), (".env", Writes)]), (">a.txt cat .env", &[(".env", Prints), ("a.txt", Writes)]), ("npm test > .env", &[(".env", Writes)]), ("cat .env 2>/dev/null", &[(".env", Prints), ("/dev/null", Writes)]), // Not there yet, and no separator. ("tool > new", &[("new", Writes)]), // A file descriptor is no file. ("tool 2>&1", NOTHING), ]); } #[test] fn a_writing_verb_writes_its_target() { check(Posix, &[ ("cp .env a-copy", &[(".env", Other), ("a-copy", Writes)]), ("cp -r .env build/new", &[(".env", Other), ("build/new", Writes)]), ("ln -s a.txt new", &[("a.txt", Other), ("new", Writes)]), ("mv .env a-copy", &[(".env", Writes), ("a-copy", Writes)]), ("rm .env", &[(".env", Writes)]), ("touch new", &[("new", Writes)]), ("mkdir -p build/x/y", &[("build/x/y", Writes)]), ("tee -a new", &[("new", Writes)]), ("dd if=.env of=new", &[(".env", Other), ("new", Writes)]), ("sed -i s/a/b/ .env", &[(".env", Prints), (".env", Writes)]), ("sed -i.bak s/a/b/ .env", &[(".env", Prints), (".env", Writes)]), ("curl -o new https://example.invalid/x", &[("new", Writes)]), ("curl --output=new https://example.invalid/x", &[("new", Writes)]), ("wget -O new https://example.invalid/x", &[("new", Writes)]), ("sort -o new a.txt", &[("a.txt", Prints), ("new", Writes)]), // These print: `-o` is a flag of its own, and the first word stays the pattern. ("grep -o build/new a.txt", &[("a.txt", Prints)]), ("curl -O example.invalid/build/new", NOTHING), ]); check(PowerShell, &[ ("Remove-Item .\\.env", &[(".env", Writes)]), ("Set-Content new x", &[("new", Writes), ("x", Writes)]), ("Copy-Item a.txt new", &[("a.txt", Other), ("new", Writes)]), ]); } // --------------------------------------------------------------------------- // Paths and globs // --------------------------------------------------------------------------- #[test] fn a_word_is_a_path_when_it_is_a_file_or_holds_a_separator_and_is_there() { check(Posix, &[ ("npm run build", NOTHING), ("cat build", NOTHING), ("cat a-word", NOTHING), // What is not there is a package, a branch or a host's path, unless a redirect // writes it or the shell may expand it. ("cat build/new", NOTHING), ("tool > build/new", &[("build/new", Writes)]), ("tool < build/new", &[("build/new", Prints)]), ("tool $X/new", &[("$X/new", Other)]), ("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), ("python .env", ENV_OTHER), ("docker cp .env c:/x", ENV_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 a_wrapper_is_no_verb_and_its_flag_or_number_neither() { check(Posix, &[ ("timeout 5 cat .env", ENV_PRINTS), ("timeout 5s cat .env", ENV_PRINTS), ("nice -n 10 cat .env", ENV_PRINTS), ("ionice -c 2 cat .env", ENV_PRINTS), ("stdbuf -o0 cat .env", ENV_PRINTS), ("xargs -n 1 cat .env", ENV_PRINTS), ("busybox cat .env", ENV_PRINTS), ("timeout 5 ls .env", ENV_METADATA), // The named limit: a flag's value that is a word becomes the verb. ("sudo -u root cat .env", ENV_OTHER), ]); } #[test] fn an_early_redirect_stays_in_its_segment() { check(Posix, &[ ("cat 2>&1 .env", ENV_PRINTS), ("cat 1>&2 .env", ENV_PRINTS), ("cat >&2 .env", ENV_PRINTS), ("cat .env 2>&1 | ls", ENV_PRINTS), ("a & cat .env", ENV_PRINTS), ]); } #[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", Writes)]), ("cat > a.txt << \"EOF\"\nsee cat .env\nEOF\ncat .env", &[("a.txt", Writes), (".env", Prints)]), ("cat > a.txt <<-EOF\n\tsee cat .env\n\tEOF\ncat .env", &[("a.txt", Writes), (".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:?}"); } }