N-1: a POSIX shell's words after its line get a printing segment of their own; eval, cmd and PowerShell still join. N-2: the line flag is looked for among the shell's leading options, skipping -o and the like, and PowerShell stops at -File. N-3: the splitter marks unquoted < and > as tokens, so echo '>' | cat .env and cat '>' id_rsa are read. S-1: --regexp, --file, --expression and clusters holding e or f give the pattern. A guard test runs the re-check's ordinary commands.
503 lines
24 KiB
Rust
503 lines
24 KiB
Rust
//! 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, writes or removes them, or anything else.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Verb { Prints, Metadata, Writes, 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", "timeout", "nice", "ionice", "stdbuf", "xargs", "busybox", "if", "elif", "then", "else", "while", "until", "do", "!", "{",
|
|
];
|
|
/// Verbs that write or remove every path they name, and verbs that write only the last.
|
|
const WRITES_ALL: &[&str] = &["mv", "rm", "rmdir", "touch", "mkdir", "tee", "truncate", "shred", "set-content", "sc", "add-content", "ac", "out-file", "tee-object", "new-item", "remove-item", "rename-item", "move-item"];
|
|
const WRITES_LAST: &[&str] = &["cp", "ln", "install", "rsync", "scp", "copy-item"];
|
|
/// Shells that take a command line by a flag: see [`takes_a_line`].
|
|
const SHELLS: &[&str] = &["bash", "rbash", "sh", "zsh", "dash", "ksh", "rksh", "mksh", "oksh", "pdksh", "ash", "yash", "osh", "fish", "csh", "tcsh", "nu", "elvish", "xonsh", "pwsh", "powershell", "cmd"];
|
|
/// Verbs whose first word is a pattern, unless `-e` or `-f` gives it.
|
|
const PATTERN_FIRST: &[&str] = &["grep", "egrep", "fgrep", "rg", "awk", "sed"];
|
|
/// Short flags of grep and rg whose next word is their value, not the pattern, and the long
|
|
/// ones of both. rg's `-g` is left out: its value says which files are read.
|
|
const GREP_VALUE_FLAGS: &str = "ABCmdD";
|
|
const RG_VALUE_FLAGS: &str = "ABCmtTjMr";
|
|
const LONG_VALUE_FLAGS: &[&str] = &["--context", "--after-context", "--before-context", "--max-count", "--type", "--type-not", "--threads", "--replace"];
|
|
/// `--flag=value` forms whose value is a name the command leaves out or filters by: no file
|
|
/// it reads. The spaced form counts only for [`EXCLUDES_SPACED`], where the flag takes a value.
|
|
const EXCLUDES: &[&str] = &["--exclude", "--exclude-dir", "--ignore", "--grep"];
|
|
const EXCLUDES_SPACED: &[&str] = &["--exclude", "--exclude-dir"];
|
|
const TAKES_EXCLUDES_SPACED: &[&str] = &["grep", "egrep", "fgrep", "tar", "rsync"];
|
|
/// Flags before git's command that change nothing it reads. `-c` can run anything.
|
|
const GIT_QUIET_FLAGS: &[&str] = &["--no-pager", "-P", "--no-optional-locks"];
|
|
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
|
|
}
|
|
|
|
/// The home directory the hook runs under.
|
|
pub fn home_dir() -> Option<PathBuf> {
|
|
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)
|
|
}
|
|
|
|
/// `word` with a leading `~/`, `$HOME/` or `${HOME}/` expanded.
|
|
pub fn expand_home(word: &str, home: Option<&Path>) -> String {
|
|
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())
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct Splitter {
|
|
segments: Vec<Vec<Token>>,
|
|
words: Vec<Token>,
|
|
word: Option<String>,
|
|
heredoc: Option<String>,
|
|
/// The last thing read was an unquoted `<` or `>`.
|
|
after_redirect: bool,
|
|
}
|
|
|
|
/// A word, or an unquoted `<` or `>`: a quoted `'>'` is a word and never this.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
enum Token {
|
|
Word(String),
|
|
Redirect(char),
|
|
}
|
|
|
|
impl Splitter {
|
|
fn push(&mut self, c: char) {
|
|
self.word.get_or_insert_with(String::new).push(c);
|
|
self.after_redirect = false;
|
|
}
|
|
|
|
fn start_quote(&mut self) {
|
|
self.word.get_or_insert_with(String::new);
|
|
self.after_redirect = false;
|
|
}
|
|
|
|
fn redirect(&mut self, c: char) {
|
|
self.end_word();
|
|
self.words.push(Token::Redirect(c));
|
|
self.after_redirect = true;
|
|
}
|
|
|
|
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 == Token::Redirect('<')).count() == 2 {
|
|
self.heredoc = Some(word.trim_start_matches('-').to_string());
|
|
}
|
|
self.words.push(Token::Word(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, with an unquoted `<` and `>` as words of
|
|
/// their own. 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<Vec<String>> {
|
|
let text = |token: Token| match token {
|
|
Token::Word(word) => word,
|
|
Token::Redirect(c) => c.to_string(),
|
|
};
|
|
tokens(command, dialect).into_iter().map(|segment| segment.into_iter().map(text).collect()).collect()
|
|
}
|
|
|
|
fn tokens(command: &str, dialect: Dialect) -> Vec<Vec<Token>> {
|
|
let chars: Vec<char> = 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.start_quote();
|
|
}
|
|
(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. With none it is no heredoc: `$((1<<2))`.
|
|
if let Some(delimiter) = s.heredoc.take() {
|
|
let rest: String = chars[i..].iter().collect();
|
|
let body = rest.split_inclusive('\n').position(|line| line.trim() == delimiter);
|
|
let lines = rest.split_inclusive('\n').take(body.map_or(0, |at| at + 1));
|
|
i += lines.map(|line| line.chars().count()).sum::<usize>();
|
|
}
|
|
}
|
|
// `2>&1` and `>|` stay in their segment: this `&` starts no job, this `|` no pipe.
|
|
(None, '&' | '|') if s.word.is_none() && s.after_redirect && s.words.last() == Some(&Token::Redirect('>')) => {}
|
|
(None, ';' | '|' | '&' | '(' | ')' | '`') => s.end_segment(),
|
|
(None, '<' | '>') => s.redirect(c),
|
|
(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, `>` writes, 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<CommandPath> {
|
|
let mut found = Vec::new();
|
|
for words in tokens(command, dialect) {
|
|
let (mut args, mut inputs, mut outputs) = (Vec::new(), Vec::new(), Vec::new());
|
|
let mut rest = words.iter().peekable();
|
|
while let Some(token) = rest.next() {
|
|
let op = match token {
|
|
Token::Word(word) => {
|
|
args.push(word.as_str());
|
|
continue;
|
|
}
|
|
Token::Redirect(op) => *op,
|
|
};
|
|
let mut run = 1;
|
|
while rest.next_if_eq(&token).is_some() {
|
|
run += 1;
|
|
}
|
|
match (op, rest.next()) {
|
|
// `<>` opens its target both ways: it is read as well as written.
|
|
('<', Some(Token::Redirect('>'))) if run == 1 => {
|
|
let target = word_of(rest.next());
|
|
inputs.extend(target);
|
|
outputs.extend(target);
|
|
}
|
|
('<', Some(Token::Word(target))) if run == 1 => inputs.push(target.as_str()),
|
|
// `2>&1` names a file descriptor.
|
|
('>', Some(Token::Word(target))) if !target.chars().all(|c| c.is_ascii_digit()) => outputs.push(target.as_str()),
|
|
_ => {}
|
|
}
|
|
}
|
|
let (verb, named, written, inner) = named_words(&args);
|
|
found.extend(inner.iter().flat_map(|line| command_paths(line, dialect, cwd, home)));
|
|
let read = inputs.iter().map(|word| (*word, Verb::Prints, true));
|
|
let written = outputs.iter().chain(&written).map(|word| (*word, Verb::Writes, true));
|
|
for (word, verb, new) in read.chain(named.iter().map(|word| (*word, verb, false))).chain(written) {
|
|
found.extend(word_paths(word, new, cwd, home).into_iter().map(|path| CommandPath { path, verb }));
|
|
}
|
|
}
|
|
found
|
|
}
|
|
|
|
/// Whether `flag` of grep or rg takes the next word as its value. A short flag may close a
|
|
/// cluster: `-nA 2`.
|
|
fn takes_a_value(verb: &str, flag: &str) -> bool {
|
|
let short = match verb {
|
|
"grep" | "egrep" | "fgrep" => GREP_VALUE_FLAGS,
|
|
"rg" => RG_VALUE_FLAGS,
|
|
_ => return false,
|
|
};
|
|
LONG_VALUE_FLAGS.contains(&flag) || (flag.starts_with('-') && !flag.starts_with("--") && flag.ends_with(|c| short.contains(c)))
|
|
}
|
|
|
|
/// Whether `word` gives a pattern verb its pattern, so that its first other word is a file:
|
|
/// `-e`, `-f`, `--regexp`, `--file`, `--expression`, with or without `=`, or a short cluster
|
|
/// holding `e` or `f` (`-eAPI`, `-ie`, `-fp`). awk's `-e` is gawk's, and `e` in a cluster none.
|
|
fn gives_a_pattern(verb: &str, word: &str) -> bool {
|
|
let long = ["--regexp", "--file", "--expression", "--source"].iter().any(|flag| word == *flag || word.strip_prefix(flag).is_some_and(|rest| rest.starts_with('=')));
|
|
let letters: &[char] = if verb == "awk" { &['f'] } else { &['e', 'f'] };
|
|
let short = word.starts_with('-') && !word.starts_with("--") && word.len() > 1;
|
|
long || word == "-e" || (short && word[1..].contains(letters))
|
|
}
|
|
|
|
/// Whether the word after `flag` is a pattern: `-e API`, `-ie API`, `--regexp API`.
|
|
fn takes_a_pattern(flag: &str) -> bool {
|
|
matches!(flag, "--regexp" | "--expression" | "--source") || (flag.starts_with('-') && !flag.starts_with("--") && flag.ends_with('e'))
|
|
}
|
|
|
|
/// git's command, past its quiet flags and `-C <dir>`.
|
|
fn git_command<'a>(rest: &[&'a str]) -> Option<&'a str> {
|
|
let mut words = rest.iter().copied();
|
|
let mut word = words.next();
|
|
while let Some(flag) = word.filter(|w| *w == "-C" || GIT_QUIET_FLAGS.contains(w)) {
|
|
if flag == "-C" {
|
|
words.next();
|
|
}
|
|
word = words.next();
|
|
}
|
|
word
|
|
}
|
|
|
|
/// Whether `flag` of `shell` takes a command line: a short cluster holding `c` (`-c`, `-lc`,
|
|
/// `-ce`), `--command`, PowerShell's `-Command` by any abbreviation (its other flags hold a
|
|
/// `c` too), `cmd`'s `/c` and `/k`. A long flag such as `--norc` does not.
|
|
fn takes_a_line(shell: &str, flag: &str) -> bool {
|
|
let lower = flag.to_ascii_lowercase();
|
|
match shell {
|
|
"pwsh" | "powershell" => lower.len() > 1 && "-command".starts_with(&lower),
|
|
"cmd" => lower == "/c" || lower == "/k",
|
|
_ => matches!(flag, "--command" | "--commands") || (flag.starts_with('-') && !flag.starts_with("--") && flag.contains('c')),
|
|
}
|
|
}
|
|
|
|
/// Flags of a POSIX shell that take the next word: `-o pipefail`, `+O extglob`, `--rcfile x`.
|
|
fn shell_flag_takes_a_value(shell: &str, flag: &str) -> bool {
|
|
let short = !flag.starts_with("--") && flag.len() > 1 && flag.ends_with(['o', 'O']);
|
|
short || matches!(flag, "--rcfile" | "--init-file" | "--init-command") || (shell == "fish" && flag == "-C")
|
|
}
|
|
|
|
/// PowerShell's flags that take no value. Every other one does: `-ExecutionPolicy Bypass`.
|
|
const POWERSHELL_SWITCHES: &[&str] = &["-noprofile", "-nop", "-nologo", "-noninteractive", "-noni", "-noexit", "-login", "-l", "-interactive", "-mta", "-sta"];
|
|
|
|
/// The text of a word token.
|
|
fn word_of(token: Option<&Token>) -> Option<&str> {
|
|
match token {
|
|
Some(Token::Word(word)) => Some(word.as_str()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// A word quoted for a POSIX shell.
|
|
fn quoted(word: &str) -> String {
|
|
format!("'{}'", word.replace('\'', "'\\''"))
|
|
}
|
|
|
|
/// The command line a shell or `eval` is given, and how many of `rest` stand before it and
|
|
/// are the command's own. The line flag is looked for among the shell's leading options
|
|
/// only: after a script's name, or PowerShell's `-File`, a flag is the script's. `eval`,
|
|
/// `cmd` and PowerShell join the words after it. A POSIX shell takes one line, and the
|
|
/// words after it are its arguments, which the line may print: they get a segment of
|
|
/// their own that prints them, so `bash -c 'cat "$1"; echo done' _ .env` reads `.env`.
|
|
fn given_line(name: &str, rest: &[&str]) -> Option<(String, usize)> {
|
|
let joined = |words: &[&str]| Some(words.iter().copied().filter(|w| !w.starts_with('-')).collect::<Vec<_>>().join(" ")).filter(|line| !line.is_empty());
|
|
if name == "eval" {
|
|
return Some((joined(rest)?, 0));
|
|
}
|
|
if !SHELLS.contains(&name) {
|
|
return None;
|
|
}
|
|
let powershell = matches!(name, "pwsh" | "powershell");
|
|
let is_flag = |word: &str| word.starts_with(['-', '+']) || (name == "cmd" && word.starts_with('/'));
|
|
let takes_value = |word: &str| match powershell {
|
|
true => !POWERSHELL_SWITCHES.contains(&word.to_ascii_lowercase().as_str()),
|
|
false => shell_flag_takes_a_value(name, word),
|
|
};
|
|
let mut at = 0;
|
|
let (flag_at, given) = loop {
|
|
let word = *rest.get(at)?;
|
|
if let Some(line) = word.strip_prefix("--command=") {
|
|
break (at, Some(line));
|
|
}
|
|
if takes_a_line(name, word) {
|
|
break (at, None);
|
|
}
|
|
let file = powershell && word.len() > 1 && "-file".starts_with(&word.to_ascii_lowercase());
|
|
if !is_flag(word) || file {
|
|
return None;
|
|
}
|
|
at += 1 + usize::from(takes_value(word));
|
|
};
|
|
let mut after = flag_at + 1;
|
|
if powershell || name == "cmd" {
|
|
return Some((joined(&rest[after..])?, flag_at));
|
|
}
|
|
let line = match given {
|
|
Some(line) => line,
|
|
None => {
|
|
// `bash -c -o pipefail 'line'`: options may follow the flag.
|
|
after += usize::from(shell_flag_takes_a_value(name, rest[flag_at]));
|
|
while let Some(word) = rest.get(after).filter(|word| is_flag(word)) {
|
|
after += 1 + usize::from(shell_flag_takes_a_value(name, word));
|
|
}
|
|
let line = *rest.get(after)?;
|
|
after += 1;
|
|
line
|
|
}
|
|
};
|
|
let arguments: Vec<String> = rest.get(after..).unwrap_or_default().iter().map(|word| quoted(word)).collect();
|
|
match arguments.is_empty() {
|
|
true => Some((line.to_string(), flag_at)),
|
|
false => Some((format!("{line}\ncat {}", arguments.join(" ")), flag_at)),
|
|
}
|
|
}
|
|
|
|
/// The value `word` holds of an output `flag`: `-ofile`, `--output=file`.
|
|
fn attached_value<'a>(word: &'a str, flag: &str) -> Option<&'a str> {
|
|
if flag.len() == 2 {
|
|
return word.strip_prefix(flag).filter(|value| !value.is_empty());
|
|
}
|
|
word.strip_prefix(flag)?.strip_prefix('=')
|
|
}
|
|
|
|
/// The segment's verb class, 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 `=`), the words it
|
|
/// writes to and the command line it hands to a shell. A verb goes by its file name. A wrapper goes by its
|
|
/// file name only as a bare word or an absolute path: `./do` is a project's script, and
|
|
/// `/home/me/env` may be one, so the word after an absolute path still counts as a path.
|
|
/// A metadata verb has to be a bare word: `./test .env` may do anything with the file.
|
|
fn named_words<'a>(args: &[&'a str]) -> (Verb, Vec<&'a str>, Vec<&'a str>, Option<String>) {
|
|
let base = |word: &str| Path::new(word).file_name().and_then(|n| n.to_str()).unwrap_or(word).to_ascii_lowercase().trim_end_matches(".exe").to_string();
|
|
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, mut by_path) = (0, false, 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(&base(word).as_str()) && (word.starts_with('/') || !word.contains('/')) => {
|
|
prefixed = true;
|
|
by_path |= word.starts_with('/');
|
|
}
|
|
// A prefix's flag or number: `nice -n 10 cat`, `timeout 5s cat`.
|
|
None if prefixed && word.starts_with(|c: char| c == '-' || c.is_ascii_digit()) => {}
|
|
None => break,
|
|
}
|
|
at += 1;
|
|
}
|
|
let Some(verb_word) = args.get(at) else {
|
|
return (Verb::Other, named, Vec::new(), None);
|
|
};
|
|
if by_path {
|
|
named.push(verb_word);
|
|
}
|
|
let rest = &args[at + 1..];
|
|
let name = base(verb_word);
|
|
// A shell's `-c` argument and `eval`'s are command lines of their own.
|
|
let (inner, rest) = given_line(&name, rest).map_or((None, rest), |(line, own)| (Some(line), &rest[..own]));
|
|
// `git commit -F` puts the file into a message.
|
|
let git_reads = rest.iter().any(|w| w.starts_with("-F") || w.starts_with("--file"));
|
|
let is_metadata = !verb_word.contains('/') && (METADATA.contains(&name.as_str()) || (name == "git" && !git_reads && git_command(rest).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 };
|
|
|
|
// The flags naming what this verb writes. On a printing or metadata verb `-o` is mostly
|
|
// no such flag (`strings -o`, `od -o`, `ls -o`), and what it names would miss the gate.
|
|
let output_flags: &[&str] = match name.as_str() {
|
|
"wget" => &["-O", "--output-document"],
|
|
"cp" | "mv" | "ln" | "install" => &["-t", "--target-directory"],
|
|
"copy-item" | "move-item" => &["-destination"],
|
|
verb if verb == "sort" || !(PRINTS.contains(&verb) || METADATA.contains(&verb)) => &["-o", "--output"],
|
|
_ => &[],
|
|
};
|
|
let pattern_first = PATTERN_FIRST.contains(&name.as_str());
|
|
let mut pattern_due = pattern_first && !rest.iter().any(|w| gives_a_pattern(&name, w));
|
|
let mut previous = "";
|
|
let mut written = Vec::new();
|
|
let from = named.len();
|
|
for word in rest.iter().copied() {
|
|
let is_pattern = (pattern_first && takes_a_pattern(previous)) || (name == "find" && FIND_PATTERNS.contains(&previous)) || (TAKES_EXCLUDES_SPACED.contains(&name.as_str()) && EXCLUDES_SPACED.contains(&previous)) || takes_a_value(&name, previous);
|
|
let is_output_flag = |flag: &&str| if flag.len() == 2 { *flag == previous } else { flag.eq_ignore_ascii_case(previous) };
|
|
let output = if output_flags.iter().any(|flag| is_output_flag(&flag)) { Some(word) } else { output_flags.iter().find_map(|flag| attached_value(word, flag)) };
|
|
previous = word;
|
|
if let Some(value) = output {
|
|
written.push(value);
|
|
// What prints stays printing, so a flag that writes takes nothing past the gate.
|
|
if verb == Verb::Prints {
|
|
named.push(value);
|
|
}
|
|
continue;
|
|
}
|
|
if is_pattern {
|
|
continue;
|
|
}
|
|
if !word.starts_with('-') {
|
|
if pattern_due {
|
|
pattern_due = false;
|
|
continue;
|
|
}
|
|
named.push(word);
|
|
}
|
|
match word.split_once('=') {
|
|
Some(("of", value)) if name == "dd" => written.push(value),
|
|
Some((flag, _)) if EXCLUDES.contains(&flag) => {}
|
|
Some((_, value)) => named.push(value),
|
|
None => {}
|
|
}
|
|
}
|
|
// `sed -Ei`, `sed --in-place`: it still prints (`w /dev/stdout`), so its words stay named.
|
|
let in_place = name == "sed" && rest.iter().any(|w| w.starts_with("--i") || (w.starts_with('-') && !w.starts_with("--") && w.contains('i')));
|
|
if in_place {
|
|
written.extend(named[from..].iter().copied());
|
|
} else if WRITES_ALL.contains(&name.as_str()) {
|
|
written.extend(named.drain(from..));
|
|
} else if WRITES_LAST.contains(&name.as_str()) && named.len() > from {
|
|
// `host:/path` is no file here.
|
|
let remote = |word: &&str| matches!(name.as_str(), "scp" | "rsync") && word.split('/').next().is_some_and(|host| host.contains(':'));
|
|
written.extend(named.pop().filter(|word| !remote(word)));
|
|
}
|
|
(verb, named, written, inner)
|
|
}
|
|
|
|
/// The paths one word names. A word counts when it is a file or `new`, a file the command
|
|
/// makes, or when it holds a separator and is there or may be once the shell expands it: a
|
|
/// package, a branch and a host's path hold one too. Other text with spaces and an address
|
|
/// 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, new: bool, cwd: &Path, home: Option<&Path>) -> Vec<PathBuf> {
|
|
let expanded = expand_home(word, home);
|
|
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<PathBuf> = 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();
|
|
// A glob that matches nothing yet may be the name of the file a command makes.
|
|
if !files.is_empty() || !new {
|
|
return files;
|
|
}
|
|
}
|
|
let path = absolute(Path::new(&expanded), cwd);
|
|
let prose = word.contains(char::is_whitespace) || word.contains("://");
|
|
let reached = path.exists() || word.contains(['$', '*', '?']);
|
|
if path.is_file() || new || (!prose && word.contains('/') && reached) { vec![path] } else { Vec::new() }
|
|
}
|