artifactize-core 0.27.1

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
use std::{fs, io, path::Path};

/// The directories path_helper adds to new macOS login terminals, in its file order.
#[cfg(any(target_os = "macos", test))]
pub(super) fn terminal_paths(system: &Path) -> io::Result<Vec<std::path::PathBuf>> {
    fn read(path: &Path) -> io::Result<Vec<std::path::PathBuf>> {
        match fs::read_to_string(path) {
            Ok(text) => Ok(text
                .lines()
                .map(std::path::PathBuf::from)
                .filter(|path| path.is_absolute())
                .collect()),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
            Err(error) => Err(error),
        }
    }
    let mut directories = read(&system.join("paths"))?;
    let mut files = match fs::read_dir(system.join("paths.d")) {
        Ok(entries) => entries
            .map(|entry| entry.map(|entry| entry.path()))
            .collect::<io::Result<Vec<_>>>()?,
        Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),
        Err(error) => return Err(error),
    };
    files.sort();
    for file in files.into_iter().filter(|path| path.is_file()) {
        directories.extend(read(&file)?);
    }
    Ok(directories)
}

pub(super) enum Consent {
    Installed,
    Declined,
}

pub(super) fn register(
    bin: &Path,
    paths_file: &Path,
    state: &Path,
    reachable: bool,
    write: impl FnOnce(&Path, &str) -> io::Result<Consent>,
) -> io::Result<()> {
    if reachable {
        return Ok(());
    }
    bin.to_str()
        .filter(|text| !text.contains(['\n', '\r']))
        .ok_or_else(|| io::Error::other("bundle path cannot be represented in paths.d"))?;
    if !bin.join("artifactize").is_file() || !bin.join("artifactize-tools").is_file() {
        return Err(io::Error::other("bundle is missing its commands"));
    }
    let content = format!("{}\n", crate::platform::path_text(bin));
    match fs::read_to_string(paths_file) {
        Ok(existing) if existing == content => return Ok(()),
        // A moved/deleted bundle's old entry can be repaired. Another working bundle is
        // not ours to replace, even if this shell does not use path_helper.
        Ok(existing)
            if Path::new(existing.trim_end_matches(['\r', '\n']))
                .join("artifactize")
                .is_file() =>
        {
            return Ok(());
        }
        Ok(_) => {}
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(error),
    }
    let declined_file = state.join("desktop-cli-declined.json");
    let mut declined: Vec<std::path::PathBuf> = match fs::read(&declined_file) {
        Ok(bytes) => serde_json::from_slice(&bytes).map_err(io::Error::other)?,
        Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),
        Err(error) => return Err(error),
    };
    if declined.iter().any(|path| path == bin) {
        return Ok(());
    }
    match write(paths_file, &content)? {
        Consent::Installed => Ok(()),
        Consent::Declined => {
            declined.push(bin.to_owned());
            fs::create_dir_all(state)?;
            #[derive(serde::Serialize)]
            struct Declined<'a>(
                #[serde(serialize_with = "crate::platform::serialize_paths")]
                &'a [std::path::PathBuf],
            );
            fs::write(
                declined_file,
                serde_json::to_vec(&Declined(&declined)).map_err(io::Error::other)?,
            )
        }
    }
}

#[cfg(target_os = "macos")]
pub(super) fn write_privileged(destination: &Path, content: &str) -> io::Result<Consent> {
    use std::{
        io::Write,
        process::{Command, Stdio},
        time::Duration,
    };
    // AppleScript reports this error marker when the user cancels the authorization prompt.
    const USER_CANCELLED: &str = "(-128)";
    // A noninteractive sudo probe should finish immediately; bound a stalled plugin.
    const SUDO_TIMEOUT: Duration = Duration::from_secs(5);
    // Give the person time to read the system prompt and authenticate, without leaving
    // an unresponsive authorization service running indefinitely.
    const AUTHORIZATION_TIMEOUT: Duration = Duration::from_secs(120);
    let mut source = tempfile::NamedTempFile::new()?;
    source.write_all(content.as_bytes())?;
    source.flush()?;
    let mut sudo = Command::new("/usr/bin/sudo");
    sudo.args(["-n", "/usr/bin/install", "-m", "644"])
        .arg(source.path())
        .arg(destination)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    if super::bounded_status(&mut sudo, SUDO_TIMEOUT)?.success() {
        return Ok(Consent::Installed);
    }
    // AppleScript's elevation API accepts only a shell command. The script is constant,
    // and AppleScript quotes both paths, which arrive as arguments.
    const SCRIPT: &str = "on run argv\n do shell script \"/usr/bin/install -m 644 \" & quoted form of item 1 of argv & \" \" & quoted form of item 2 of argv with prompt \"Artifactize wants to make the artifactize command available in Terminal.\" with administrator privileges\nend run";
    let errors = tempfile::NamedTempFile::new()?;
    let mut prompt = Command::new("/usr/bin/osascript");
    prompt
        .args(["-e", SCRIPT])
        .arg(source.path())
        .arg(destination)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(errors.reopen()?);
    // The person needs time to read the system prompt and authenticate. This runs off
    // the UI thread and is still bounded if the authorization service stops answering.
    let status = super::bounded_status(&mut prompt, AUTHORIZATION_TIMEOUT)?;
    if status.success() {
        Ok(Consent::Installed)
    } else {
        let message = fs::read_to_string(errors.path())?;
        if message.contains(USER_CANCELLED) {
            Ok(Consent::Declined)
        } else {
            Err(io::Error::other(format!(
                "command registration authorization failed: {message}"
            )))
        }
    }
}

#[cfg(test)]
mod tests;