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, os::unix::fs::symlink, path::Path};

const COMMANDS: [&str; 2] = ["artifactize", "artifactize-tools"];

pub(super) fn register(
    bundled: &Path,
    stable: &Path,
    local_bin: &Path,
    version: &str,
    reachable: bool,
) -> io::Result<()> {
    let owns_cli = fs::read_link(local_bin.join("artifactize"))
        .is_ok_and(|target| target == stable.join("artifactize"));
    // Our stable copies must follow AppImage updates even when our own link is already
    // reachable. An unrelated existing installation always wins.
    if reachable && !owns_cli {
        return Ok(());
    }
    for name in COMMANDS {
        let link = local_bin.join(name);
        match fs::symlink_metadata(&link) {
            Ok(_) if fs::read_link(&link).is_ok_and(|target| target == stable.join(name)) => {}
            Ok(_) => {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!(
                        "will not replace {}: not installed by the app",
                        crate::platform::path_text(&link)
                    ),
                ));
            }
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
    }
    fs::create_dir_all(stable)?;
    fs::create_dir_all(local_bin)?;
    let installed_version = stable.join("version");
    if fs::read_to_string(&installed_version).ok().as_deref() != Some(version)
        || COMMANDS.iter().any(|name| !stable.join(name).is_file())
    {
        for name in COMMANDS {
            // Replace by rename: a running CLI retains its old executable, and a failed
            // copy cannot truncate a working one. No symlink points into the FUSE mount.
            let temporary = tempfile::NamedTempFile::new_in(stable)?;
            fs::copy(bundled.join(name), temporary.path())?;
            temporary
                .persist(stable.join(name))
                .map_err(|error| error.error)?;
        }
        fs::write(installed_version, version)?;
    }
    for name in COMMANDS {
        let link = local_bin.join(name);
        match symlink(stable.join(name), &link) {
            Ok(()) => {}
            Err(error)
                if error.kind() == io::ErrorKind::AlreadyExists
                    && fs::read_link(&link).is_ok_and(|target| target == stable.join(name)) => {}
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests;