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
//! Find or launch the installed desktop app, without a shell.
//! Every install channel leaves `artifactize-desktop` beside the commands it bundles (the
//! deb, the Windows zip and MSIX, the Mac app the cask links), on `PATH` (install.sh's
//! launcher), or at one of this system's app locations.

use std::{
    ffi::OsString,
    path::{Path, PathBuf},
    process::Stdio,
};

/// The desktop app's program name, without this system's executable suffix.
const PROGRAM: &str = "artifactize-desktop";

/// The file, below the data home's `artifactize` folder, that names the AppImage last started.
#[cfg(target_os = "linux")]
const APPIMAGE_RECORD: &str = "appimage-path";

/// The Microsoft Store package's family name; its execution-alias folder exists while it is
/// installed.
#[cfg(windows)]
const STORE_PACKAGE_FAMILY: &str = "lhj6102.Artifactize_ayfzfzbsv48sg";

/// Start the installed Desktop app and let it outlive the CLI. `doctor` uses the same
/// discovery without starting a process.
pub fn launch(args: &[OsString]) -> Result<(), String> {
    let app = installed()
        .filter(|path| path.is_file())
        .ok_or("Artifactize Desktop is not available. Install it from https://artifactize.dev/.")?;
    let mut command = artifactize_foundation::platform::process::resolved_command(&app, args)
        .map_err(|error| format!("Cannot launch {}: {error}", super::path_text(&app)))?;
    command
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    super::spawn_detached(command)
        .map(|child| child.reap())
        .map_err(|error| format!("Cannot launch {}: {error}", super::path_text(&app)))
}

/// The installed desktop app this command finds, if any.
pub(crate) fn installed() -> Option<PathBuf> {
    // A Homebrew or AppImage link names the bundle only once resolved.
    let executable = std::env::current_exe()
        .ok()
        .map(|executable| std::fs::canonicalize(&executable).unwrap_or(executable));
    let cwd = std::env::current_dir().ok();
    let home = super::home_directory();
    find(
        executable.as_deref(),
        cwd.as_deref(),
        super::environment::var,
        locations(super::environment::var, home.as_deref()),
    )
}

fn find(
    executable: Option<&Path>,
    cwd: Option<&Path>,
    variable: impl Fn(&str) -> Option<OsString>,
    locations: Vec<PathBuf>,
) -> Option<PathBuf> {
    executable
        .and_then(Path::parent)
        .map(|bin| bin.join(format!("{PROGRAM}{}", std::env::consts::EXE_SUFFIX)))
        .filter(|beside| beside.is_file())
        .or_else(|| {
            cwd.and_then(|cwd| super::program::resolve_with(Path::new(PROGRAM), cwd, variable).ok())
        })
        .or_else(|| locations.into_iter().find(|location| location.exists()))
}

/// Where this system's installers put the app when it is not beside the command or on `PATH`.
#[cfg(target_os = "macos")]
fn locations(_variable: impl Fn(&str) -> Option<OsString>, home: Option<&Path>) -> Vec<PathBuf> {
    // The disk image and the cask install into /Applications, install.sh into ~/Applications.
    let bundle = Path::new("Artifactize.app/Contents/MacOS").join(PROGRAM);
    std::iter::once(PathBuf::from("/Applications"))
        .chain(home.map(|home| home.join("Applications")))
        .map(|applications| applications.join(&bundle))
        .collect()
}

#[cfg(target_os = "linux")]
fn locations(variable: impl Fn(&str) -> Option<OsString>, home: Option<&Path>) -> Vec<PathBuf> {
    let Some(artifactize) = home.map(|home| data_home(variable, home).join("artifactize")) else {
        return Vec::new();
    };
    // install.sh unpacks the AppImage here; an AppImage started directly records its path.
    let mut locations = vec![artifactize.join("desktop/AppRun")];
    locations.extend(
        std::fs::read(artifactize.join(APPIMAGE_RECORD))
            .ok()
            .filter(|path| !path.is_empty())
            .map(|path| super::path_from_bytes(&path)),
    );
    locations
}

#[cfg(windows)]
fn locations(variable: impl Fn(&str) -> Option<OsString>, _home: Option<&Path>) -> Vec<PathBuf> {
    let Some(local) = variable("LOCALAPPDATA")
        .filter(|path| !path.is_empty())
        .map(PathBuf::from)
    else {
        return Vec::new();
    };
    // install.ps1's default folder, and the alias folder the Store package owns.
    vec![
        local
            .join("Programs/artifactize")
            .join(format!("{PROGRAM}.exe")),
        local
            .join("Microsoft/WindowsApps")
            .join(STORE_PACKAGE_FAMILY),
    ]
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
fn locations(_variable: impl Fn(&str) -> Option<OsString>, _home: Option<&Path>) -> Vec<PathBuf> {
    Vec::new()
}

/// `$XDG_DATA_HOME` when it is an absolute path, else `~/.local/share`.
#[cfg(target_os = "linux")]
pub(super) fn data_home(variable: impl Fn(&str) -> Option<OsString>, home: &Path) -> PathBuf {
    variable("XDG_DATA_HOME")
        .filter(|path| !path.is_empty())
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .unwrap_or_else(|| home.join(".local/share"))
}

/// Name `appimage` as the installed app below `artifactize`, the data home's folder. The
/// record is replaced by rename and only when it changes.
#[cfg(target_os = "linux")]
pub(super) fn record_appimage(artifactize: &Path, appimage: &Path) -> std::io::Result<()> {
    use std::{io::Write, os::unix::ffi::OsStrExt};
    let record = artifactize.join(APPIMAGE_RECORD);
    let bytes = appimage.as_os_str().as_bytes();
    if std::fs::read(&record).is_ok_and(|recorded| recorded == bytes) {
        return Ok(());
    }
    std::fs::create_dir_all(artifactize)?;
    let mut temporary = tempfile::NamedTempFile::new_in(artifactize)?;
    temporary.write_all(bytes)?;
    temporary.persist(record).map_err(|error| error.error)?;
    Ok(())
}

#[cfg(test)]
mod tests;