litnik 0.2.1

An embedded Lit and FileCheck runner for compiler test suites.
Documentation
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::shell::ast::Arg;

/// The byte-oriented result of an embedded shell command.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ShellCommandOutput {
    /// Bytes written to standard output.
    pub stdout: Vec<u8>,
    /// Bytes written to standard error.
    pub stderr: Vec<u8>,
    /// Process-style exit status. Zero denotes success.
    pub exit_code: i32,
}

/// Executes a command supplied by the embedding application.
///
/// Handlers receive the complete argument vector, including the command name
/// at index zero, buffered standard input, the command working directory, and
/// the effective environment. They may be used as any pipeline stage; input is
/// buffered before the handler is called.
pub trait ShellCommandHandler: Send + Sync {
    /// Runs one invocation of the embedded command.
    ///
    /// # Errors
    ///
    /// Returns an error when the handler cannot complete the invocation. A
    /// completed command failure belongs in [`ShellCommandOutput::exit_code`]
    /// instead.
    fn execute(
        &self,
        args: &[String],
        stdin: &[u8],
        cwd: &Path,
        environment: &HashMap<String, String>,
    ) -> Result<ShellCommandOutput, String>;
}

impl<F> ShellCommandHandler for F
where
    F: Fn(&[String], &[u8], &Path, &HashMap<String, String>) -> Result<ShellCommandOutput, String>
        + Send
        + Sync,
{
    fn execute(
        &self,
        args: &[String],
        stdin: &[u8],
        cwd: &Path,
        environment: &HashMap<String, String>,
    ) -> Result<ShellCommandOutput, String> {
        self(args, stdin, cwd, environment)
    }
}

/// Mutable state shared by commands in one Lit shell script.
///
/// The state contains the effective environment supplied by the runner.
/// Directory and exported-variable changes made by standalone builtins persist
/// for later commands.
#[derive(Clone)]
pub struct ShellEnv {
    /// Working directory used to resolve commands, globs, and relative paths.
    pub cwd: PathBuf,
    /// Environment passed to external and embedded commands.
    pub env: HashMap<String, String>,
    /// Directories saved by `pushd` and restored by `popd`.
    pub dir_stack: Vec<PathBuf>,
    /// File creation mask inherited by subsequently spawned Unix processes.
    pub umask: Option<u32>,
    /// Whether late path substitutions use forward slashes.
    pub normalize_slashes: bool,
    pub(crate) tools: HashMap<String, PathBuf>,
    pub(crate) commands: HashMap<String, Arc<dyn ShellCommandHandler>>,
}

impl fmt::Debug for ShellEnv {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ShellEnv")
            .field("cwd", &self.cwd)
            .field("env", &self.env)
            .field("dir_stack", &self.dir_stack)
            .field("umask", &self.umask)
            .field("normalize_slashes", &self.normalize_slashes)
            .field("tools", &self.tools)
            .field("commands", &self.commands.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl ShellEnv {
    /// Creates shell state rooted at `cwd`.
    ///
    /// Values in `env` override inherited Unicode process variables.
    #[cfg(test)]
    pub fn new(cwd: PathBuf, env: HashMap<String, String>, normalize_slashes: bool) -> Self {
        let mut inherited = std::env::vars_os()
            .filter_map(|(key, value)| Some((key.into_string().ok()?, value.into_string().ok()?)))
            .collect::<HashMap<_, _>>();
        inherited.extend(env);
        Self::from_environment(cwd, inherited, normalize_slashes)
    }

    pub(crate) fn from_environment(
        cwd: PathBuf,
        env: HashMap<String, String>,
        normalize_slashes: bool,
    ) -> Self {
        Self {
            cwd,
            env,
            dir_stack: Vec::new(),
            umask: None,
            normalize_slashes,
            tools: HashMap::new(),
            commands: HashMap::new(),
        }
    }

    /// Registers an external executable for an exact command name.
    ///
    /// Registered paths take precedence over `PATH` lookup. A relative path is
    /// anchored to the current shell directory when it is registered.
    pub fn register_tool(&mut self, name: impl Into<String>, path: impl Into<PathBuf>) {
        let path = path.into();
        let path = if path.is_absolute() {
            path
        } else {
            self.cwd.join(path)
        };
        self.tools.insert(name.into(), path);
    }

    /// Registers a synchronous embedded implementation for an exact command name.
    ///
    /// Embedded commands take precedence over registered tools and `PATH`. The
    /// executor cannot preempt a handler while it is running.
    pub fn register_command(
        &mut self,
        name: impl Into<String>,
        command: Arc<dyn ShellCommandHandler>,
    ) {
        self.commands.insert(name.into(), command);
    }

    /// Saves the current directory and changes to `path`.
    ///
    /// # Errors
    ///
    /// Returns an error without changing state when `path` is not a directory.
    pub fn pushd(&mut self, path: &str) -> Result<(), String> {
        let next = self.resolve_path(path);
        if !next.is_dir() {
            return Err(format!("cd: {}: No such file or directory", path));
        }
        self.dir_stack.push(self.cwd.clone());
        self.cwd = next;
        Ok(())
    }

    /// Restores the most recently saved directory.
    ///
    /// Returns `None` without changing the current directory when the stack is
    /// empty.
    pub fn popd(&mut self) -> Option<PathBuf> {
        let next = self.dir_stack.pop()?;
        self.cwd = next.clone();
        Some(next)
    }

    /// Changes to `path` without modifying the directory stack.
    ///
    /// # Errors
    ///
    /// Returns an error without changing state when `path` is not a directory.
    pub fn change_dir(&mut self, path: &str) -> Result<(), String> {
        let next = self.resolve_path(path);
        if !next.is_dir() {
            return Err(format!("cd: {path}: No such file or directory"));
        }
        self.cwd = next;
        Ok(())
    }

    /// Resolves `value` against the current directory without accessing it.
    pub fn resolve_path(&self, value: &str) -> PathBuf {
        let p = PathBuf::from(value);
        if p.is_absolute() {
            p
        } else {
            self.cwd.join(p)
        }
    }
}

pub(crate) fn expand_arg_glob(arg: &Arg, cwd: &Path) -> Vec<String> {
    let active_metacharacters = arg.active_metacharacters();
    if active_metacharacters.is_empty() {
        vec![arg.as_owned_text()]
    } else {
        expand_glob_pattern(arg.as_str(), &active_metacharacters, cwd)
    }
}

fn expand_glob_pattern(pattern: &str, active_metacharacters: &[usize], cwd: &Path) -> Vec<String> {
    if active_metacharacters.is_empty() {
        return vec![pattern.to_string()];
    }

    let path = if Path::new(pattern).is_absolute() {
        PathBuf::from(pattern)
    } else {
        cwd.join(pattern)
    };

    let Some(parent) = path.parent() else {
        return vec![pattern.to_string()];
    };
    let Some(file_pat) = path.file_name().and_then(|name| name.to_str()) else {
        return vec![pattern.to_string()];
    };
    let file_start = pattern.chars().count() - file_pat.chars().count();
    let file_metacharacters = active_metacharacters
        .iter()
        .filter_map(|index| index.checked_sub(file_start))
        .collect::<Vec<_>>();
    let needs_full_glob = active_metacharacters
        .iter()
        .any(|index| *index < file_start)
        || file_metacharacters.iter().any(|index| {
            file_pat
                .chars()
                .nth(*index)
                .is_some_and(|ch| matches!(ch, '[' | ']'))
        });
    if needs_full_glob {
        return expand_with_glob_crate(pattern, active_metacharacters, cwd);
    }
    if file_metacharacters.is_empty() {
        return vec![pattern.to_string()];
    }
    let all_wildcards_active = file_pat
        .chars()
        .filter(|ch| matches!(ch, '*' | '?'))
        .count()
        == file_metacharacters.len();

    let mut expanded = Vec::new();
    let read = match std::fs::read_dir(parent) {
        Ok(entries) => entries,
        Err(_) => return vec![pattern.to_string()],
    };
    for entry in read.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        if name.starts_with('.') && !file_pat.starts_with('.') {
            continue;
        }
        let matches = if all_wildcards_active {
            glob_match_like(file_pat, name)
        } else {
            glob_match_wildcards(file_pat, &file_metacharacters, name)
        };
        if matches {
            expanded.push(entry.path().to_string_lossy().to_string());
        }
    }

    expanded.sort_unstable();

    if expanded.is_empty() {
        vec![pattern.to_string()]
    } else {
        expanded
    }
}

fn expand_with_glob_crate(
    pattern: &str,
    active_metacharacters: &[usize],
    cwd: &Path,
) -> Vec<String> {
    let mut encoded = String::new();
    for (index, ch) in pattern.chars().enumerate() {
        if active_metacharacters.binary_search(&index).is_ok() {
            encoded.push(ch);
        } else {
            encoded.push_str(&glob::Pattern::escape(&ch.to_string()));
        }
    }
    let absolute = if Path::new(&encoded).is_absolute() {
        PathBuf::from(encoded)
    } else {
        cwd.join(encoded)
    };
    let options = glob::MatchOptions {
        case_sensitive: true,
        require_literal_separator: true,
        require_literal_leading_dot: true,
    };
    let Ok(paths) = glob::glob_with(&absolute.to_string_lossy(), options) else {
        return vec![pattern.to_string()];
    };
    let mut expanded = paths
        .filter_map(Result::ok)
        .map(|path| path.to_string_lossy().into_owned())
        .collect::<Vec<_>>();
    expanded.sort_unstable();
    if expanded.is_empty() {
        vec![pattern.to_string()]
    } else {
        expanded
    }
}

fn glob_match_like(pattern: &str, value: &str) -> bool {
    let active_wildcards = pattern
        .chars()
        .enumerate()
        .filter_map(|(index, ch)| matches!(ch, '*' | '?').then_some(index))
        .collect::<Vec<_>>();
    glob_match_wildcards(pattern, &active_wildcards, value)
}

fn glob_match_wildcards(pattern: &str, active_wildcards: &[usize], value: &str) -> bool {
    let pat: Vec<char> = pattern.chars().collect();
    let txt: Vec<char> = value.chars().collect();

    let mut pi = 0usize;
    let mut vi = 0usize;
    let mut star_idx: Option<(usize, usize)> = None;

    while vi < txt.len() {
        if pi < pat.len()
            && ((pat[pi] == '?' && active_wildcards.binary_search(&pi).is_ok())
                || pat[pi] == txt[vi])
        {
            vi += 1;
            pi += 1;
            continue;
        }

        if pi < pat.len() && pat[pi] == '*' && active_wildcards.binary_search(&pi).is_ok() {
            star_idx = Some((pi, vi));
            pi += 1;
            continue;
        }

        if let Some((si, sv)) = star_idx {
            pi = si + 1;
            vi = sv + 1;
            continue;
        }

        return false;
    }

    while pi < pat.len() && pat[pi] == '*' && active_wildcards.binary_search(&pi).is_ok() {
        pi += 1;
    }

    pi == pat.len()
}

#[cfg(test)]
mod tests {
    use super::glob_match_like;

    #[test]
    fn glob_match_smoke() {
        assert!(glob_match_like("*.txt", "a.txt"));
        assert!(glob_match_like("a?c", "abc"));
        assert!(!glob_match_like("a?c", "ac"));
    }
}