Files
fermata/src/core/paths.rs
T
g4borg 8dd5a81bc8 fix(fermata): a script named like a wrapper or a metadata verb hides nothing; every shell's command line is read
./do .env, scripts/time .env and ./test .env pass no more: a wrapper counts by its file
name only as a bare word or an absolute path, and the word after an absolute path still
counts as a path, so /home/me/scripts/env .env is stopped too. A metadata verb has to be
a bare word. dash, ksh, mksh, ash, yash, fish, csh, tcsh, pwsh, powershell and cmd have
their command line read, and bash --norc -c no longer hides it.
2026-11-07 08:58:35 +01:00

272 lines
13 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, 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", "timeout", "nice", "ionice", "stdbuf", "xargs", "busybox", "if", "elif", "then", "else", "while", "until", "do", "!", "{",
];
/// Shells that take a command line by a flag: see [`takes_a_line`].
const SHELLS: &[&str] = &["bash", "sh", "zsh", "dash", "ksh", "mksh", "ash", "yash", "fish", "csh", "tcsh", "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"];
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<Vec<String>>,
words: Vec<String>,
word: Option<String>,
heredoc: Option<String>,
}
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<Vec<String>> {
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.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. 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` stays in its segment: the `&` after `>` starts no job.
(None, '&') if s.word.is_none() && s.words.last().is_some_and(|w| w == ">") => {}
(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<CommandPath> {
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, inner) = named_words(&args);
found.extend(inner.iter().flat_map(|inner| command_paths(inner, dialect, cwd, home)));
let read = inputs.iter().map(|word| (*word, Verb::Prints, true));
let written = outputs.iter().map(|word| (*word, verb, true));
for (word, verb, redirect) in read.chain(named.iter().map(|word| (*word, verb, false))).chain(written) {
found.extend(word_paths(word, redirect, cwd, home).into_iter().map(|path| CommandPath { path, verb }));
}
}
found
}
/// Whether a shell's flag takes a command line: `-c`, `-lc`, PowerShell's `-Command`, `cmd`'s
/// `/c`. A long flag such as `--norc` does not.
fn takes_a_line(flag: &str) -> bool {
let lower = flag.to_ascii_lowercase();
lower == "-command" || lower == "/c" || (flag.starts_with('-') && !flag.starts_with("--") && flag.ends_with('c'))
}
/// 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 `=`) 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>, Option<&'a str>) {
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, 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 = match name.as_str() {
"eval" => rest.first().copied(),
shell if SHELLS.contains(&shell) => rest.iter().position(|w| takes_a_line(w)).and_then(|at| rest.get(at + 1).copied()),
_ => None,
};
let is_metadata = !verb_word.contains('/') && (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, inner)
}
/// The paths one word names. A word counts when it is a file or a `redirect`'s target,
/// 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. 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, redirect: bool, cwd: &Path, home: Option<&Path>) -> Vec<PathBuf> {
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<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();
return files;
}
let path = absolute(Path::new(&expanded), cwd);
let prose = word.contains(char::is_whitespace) || word.contains("://");
let reached = redirect || path.exists() || word.contains(['$', '*', '?']);
if path.is_file() || (word.contains('/') && !prose && reached) { vec![path] } else { Vec::new() }
}