artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Program lookup metadata policies shared by scoped execution and preflight.

use std::{
    ffi::OsStr,
    io,
    path::{Component, Path, PathBuf},
};

pub(crate) fn reject_link_ancestors(path: &Path) -> io::Result<()> {
    // Drive prefixes and filesystem roots are anchors, not entries to inspect.
    for ancestor in path
        .ancestors()
        .filter(|ancestor| ancestor.file_name().is_some())
    {
        match super::path_kind(ancestor) {
            Ok(super::FileKind::Symlink) => {
                return Err(io::Error::other("Artifact symlinks are not supported."));
            }
            Ok(_) => (),
            // An extensionless candidate or an output to be restored may not exist yet.
            Err(error) if error.kind() == io::ErrorKind::NotFound => (),
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

/// The folder-relative path a declared command names, with native separators converted
/// for scope validation. A bare PATH name or an absolute command stays literal (`None`).
pub(crate) fn folder_relative(path: &Path) -> Result<Option<String>, String> {
    if path.is_absolute() {
        return Ok(None);
    }
    if path.has_root() || matches!(path.components().next(), Some(Component::Prefix(_))) {
        return Err("A program path must be absolute or relative to its Artifact.".into());
    }
    let command = super::path_text(path);
    if !command.contains('/') {
        return Ok(None);
    }
    let relative = command.strip_prefix("./").unwrap_or(&command);
    artifactize_tools::scope::logical_path(relative).map_err(|error| error.to_string())?;
    Ok(Some(relative.to_owned()))
}

/// Select a scoped executable in host lookup order, with all path admissions supplied by
/// the caller. Distinguish generated suffixes from parent components authored by the caller.
pub(crate) fn resolve_scoped(
    relative: &Path,
    admit: impl Fn(&Path) -> Result<PathBuf, String>,
) -> Result<PathBuf, String> {
    let mut failure = None;
    for candidate in artifactize_tools::program::candidates(relative, super::environment::var) {
        let candidate = if candidate != relative {
            let parent = candidate.parent().unwrap_or(Path::new(""));
            let directory = admit(parent)?;
            let Some(spelling) = suffix_spelling(&directory, &candidate) else {
                continue;
            };
            spelling
        } else {
            candidate
        };
        match admit(&candidate) {
            Ok(path) if resolve(&path, Path::new("")).is_ok() => return Ok(path),
            Ok(_) => (),
            Err(error) => {
                failure.get_or_insert(error);
            }
        }
    }
    Err(failure.unwrap_or_else(|| "Executable path is unavailable or outside scope.".into()))
}

/// Lookup-added suffixes use actual entry spelling; caller-authored parents remain exact.
fn suffix_spelling(directory: &Path, candidate: &Path) -> Option<PathBuf> {
    let requested = candidate.file_name()?.to_str()?;
    std::fs::read_dir(directory)
        .ok()?
        .filter_map(Result::ok)
        .find_map(|entry| {
            let name = entry.file_name();
            name.to_str()?
                .eq_ignore_ascii_case(requested)
                .then(|| candidate.with_file_name(name))
        })
}

/// Find `program` as a child whose environment `variable` reads would: by `PATH` (and on
/// Windows `PATHEXT`) for a bare name, below `cwd` for a path.
pub(crate) fn resolve_with(
    program: &Path,
    cwd: &Path,
    variable: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> std::io::Result<PathBuf> {
    artifactize_tools::program::resolve_with(program, cwd, variable)
}

/// Find `program` as a child with the person's environment ([`super::environment::snapshot`])
/// would.
pub(crate) fn resolve(program: &Path, cwd: &Path) -> std::io::Result<PathBuf> {
    artifactize_tools::program::resolve(program, cwd)
}

/// Find `program` beside this executable or one directory up (Cargo test binaries are
/// under `deps`), then on PATH. All candidates use the ordinary executable lookup rules.
pub(crate) fn resolve_near_current(program: &OsStr) -> io::Result<PathBuf> {
    let current = std::env::current_exe()?;
    if let Some(path) = resolve_sibling(program, &current) {
        return Ok(path);
    }
    resolve(Path::new(program), &std::env::current_dir()?)
}

fn resolve_sibling(program: &OsStr, current: &Path) -> Option<PathBuf> {
    // Probe the executable's directory and the parent of Cargo's `deps` directory.
    const SIBLING_DIRECTORIES: usize = 2;
    current
        .ancestors()
        .skip(1)
        .take(SIBLING_DIRECTORIES)
        .find_map(|directory| resolve(&directory.join(program), directory).ok())
}

/// Hand `target`, a file or URL, to the desktop's opener.
pub(crate) async fn open_desktop(target: &std::ffi::OsStr) -> std::io::Result<()> {
    artifactize_tools::opener::open(target).await
}

/// A short, synchronous host-tool probe; no shell is added and no console window opens.
pub(crate) fn tool_output<'a>(
    program: &str,
    args: impl IntoIterator<Item = &'a std::ffi::OsStr>,
) -> Option<Vec<u8>> {
    let cwd = std::env::current_dir().ok()?;
    let program = resolve(Path::new(program), &cwd).ok()?;
    let mut command = std::process::Command::new(program);
    command
        .args(args)
        .env_clear()
        .envs(super::environment::snapshot())
        .stdin(std::process::Stdio::null());
    super::hide_console_window(&mut command);
    let output = command.output().ok()?;
    output.status.success().then_some(output.stdout)
}

#[cfg(test)]
mod tests;