marathon-core 0.1.4

Marathon's rules: sessions, timers, triggers and time parsing
Documentation
//! Puts the `marathon` command on the user's PATH when the app was
//! installed by dragging it out of the DMG, the one install that can't
//! run a script. The app calls [`set_up`] once per location it runs from.
//!
//! It links `~/.local/bin/marathon` to the helper inside the app, and if
//! no shell profile mentions `~/.local/bin`, adds one marked line to the
//! login profile of the user's shell. Homebrew installs are left alone:
//! Homebrew links the command itself.

use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};

/// The line added to a shell profile, after a comment that says who added it.
pub const PATH_LINE: &str = "export PATH=\"$HOME/.local/bin:$PATH\"";
const MARKER: &str = "# Added by Marathon so the `marathon` command works";

/// Profiles that might already put `~/.local/bin` on the PATH.
const PROFILES: &[&str] = &[
    ".zshenv",
    ".zprofile",
    ".zshrc",
    ".profile",
    ".bash_profile",
    ".bashrc",
];

/// What [`set_up`] did.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Report {
    /// `~/.local/bin/marathon` now points at the app's helper.
    pub linked: bool,
    /// The profile that got the PATH line, if one did.
    pub profile: Option<PathBuf>,
    /// Why nothing was done, if nothing was.
    pub skipped: Option<&'static str>,
}

/// Links the command and makes sure the shell can find it.
///
/// `helper` is the CLI inside the app bundle, `shell` the user's login
/// shell (`$SHELL`; empty if unknown, which counts as zsh, the macOS default).
pub fn set_up(home: &Path, helper: &Path, shell: &str) -> io::Result<Report> {
    let mut report = Report::default();
    if managed_by_homebrew(helper) {
        report.skipped = Some("Homebrew already links the command");
        return Ok(report);
    }
    if runs_from_temporary_place(helper) {
        report.skipped = Some("the app isn't in its final place yet");
        return Ok(report);
    }
    if !helper.is_file() {
        report.skipped = Some("the app has no command inside it");
        return Ok(report);
    }
    let bin = home.join(".local/bin");
    let link = bin.join("marathon");
    match fs::symlink_metadata(&link) {
        // A real file is someone else's install (say, a copy): leave it.
        Ok(meta) if !meta.file_type().is_symlink() => {
            report.skipped = Some("another marathon command is already there");
            return Ok(report);
        }
        Ok(_) => {
            let target = fs::read_link(&link)?;
            if target != helper {
                // Replace links to an older Marathon.app or to nothing;
                // keep a link to anything else (npm, uv, cargo...).
                if target.exists() && !is_app_helper(&target) {
                    report.skipped = Some("another marathon command is already there");
                    return Ok(report);
                }
                fs::remove_file(&link)?;
                symlink(helper, &link)?;
            }
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            fs::create_dir_all(&bin)?;
            symlink(helper, &link)?;
        }
        Err(e) => return Err(e),
    }
    report.linked = true;

    if !PROFILES.iter().any(|p| mentions_local_bin(&home.join(p))) {
        let profile = home.join(login_profile(shell));
        let mut file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&profile)?;
        let lead = match fs::read(&profile) {
            Ok(bytes) if !bytes.is_empty() && !bytes.ends_with(b"\n") => "\n",
            _ => "",
        };
        write!(file, "{lead}\n{MARKER}\n{PATH_LINE}\n")?;
        report.profile = Some(profile);
    }
    Ok(report)
}

/// The profile a new Terminal window reads for this shell.
fn login_profile(shell: &str) -> &'static str {
    if shell.ends_with("/bash") {
        ".bash_profile"
    } else {
        ".zprofile"
    }
}

fn managed_by_homebrew(helper: &Path) -> bool {
    let s = helper.to_string_lossy();
    s.contains("/Cellar/") || s.contains("/Caskroom/") || s.starts_with("/opt/homebrew/")
}

/// Straight off the DMG, or from the read-only copy macOS makes of an app
/// it hasn't let out of quarantine: a link there would soon point nowhere.
fn runs_from_temporary_place(helper: &Path) -> bool {
    let s = helper.to_string_lossy();
    s.starts_with("/Volumes/") || s.contains("/AppTranslocation/")
}

fn is_app_helper(path: &Path) -> bool {
    path.ends_with("Contents/Helpers/marathon")
}

fn mentions_local_bin(profile: &Path) -> bool {
    fs::read_to_string(profile).is_ok_and(|s| s.contains(".local/bin"))
}

#[cfg(unix)]
fn symlink(target: &Path, link: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(target, link)
}

#[cfg(not(unix))]
fn symlink(_: &Path, _: &Path) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "needs a Unix system",
    ))
}

#[cfg(all(test, unix))]
mod tests {
    use super::*;

    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("marathon-cmd-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn app(root: &Path, at: &str) -> PathBuf {
        let helper = root.join(at).join("Marathon.app/Contents/Helpers/marathon");
        fs::create_dir_all(helper.parent().unwrap()).unwrap();
        fs::write(&helper, "").unwrap();
        helper
    }

    #[test]
    fn links_and_adds_path_once() {
        let home = scratch("fresh");
        let helper = app(&home, "Applications");
        let r = set_up(&home, &helper, "/bin/zsh").unwrap();
        assert!(r.linked);
        assert_eq!(r.profile, Some(home.join(".zprofile")));
        assert_eq!(
            fs::read_link(home.join(".local/bin/marathon")).unwrap(),
            helper
        );
        let again = set_up(&home, &helper, "/bin/zsh").unwrap();
        assert!(again.linked && again.profile.is_none());
        let text = fs::read_to_string(home.join(".zprofile")).unwrap();
        assert_eq!(text.matches(PATH_LINE).count(), 1);
        fs::remove_dir_all(home).unwrap();
    }

    #[test]
    fn keeps_existing_path_setup_and_bash() {
        let home = scratch("bash");
        let helper = app(&home, "Applications");
        let r = set_up(&home, &helper, "/bin/bash").unwrap();
        assert_eq!(r.profile, Some(home.join(".bash_profile")));

        let home2 = scratch("haspath");
        let helper2 = app(&home2, "Applications");
        fs::write(home2.join(".zshrc"), "export PATH=~/.local/bin:$PATH").unwrap();
        assert!(
            set_up(&home2, &helper2, "/bin/zsh")
                .unwrap()
                .profile
                .is_none()
        );
        assert!(!home2.join(".zprofile").exists());
        fs::remove_dir_all(home).unwrap();
        fs::remove_dir_all(home2).unwrap();
    }

    #[test]
    fn moves_link_to_new_app_but_respects_others() {
        let home = scratch("move");
        let old = app(&home, "old");
        let new = app(&home, "Applications");
        set_up(&home, &old, "").unwrap();
        set_up(&home, &new, "").unwrap();
        let link = home.join(".local/bin/marathon");
        assert_eq!(fs::read_link(&link).unwrap(), new);

        // A link to some other install of the command stays.
        let other = home.join("npm/marathon");
        fs::create_dir_all(other.parent().unwrap()).unwrap();
        fs::write(&other, "").unwrap();
        fs::remove_file(&link).unwrap();
        std::os::unix::fs::symlink(&other, &link).unwrap();
        let r = set_up(&home, &new, "").unwrap();
        assert!(!r.linked && r.skipped.is_some());
        assert_eq!(fs::read_link(&link).unwrap(), other);
        fs::remove_dir_all(home).unwrap();
    }

    #[test]
    fn leaves_homebrew_alone() {
        let home = scratch("brew");
        let helper =
            Path::new("/opt/homebrew/Cellar/marathon/0.1.4/Marathon.app/Contents/Helpers/marathon");
        let r = set_up(&home, helper, "").unwrap();
        assert!(!r.linked && r.skipped.is_some());
        assert!(!home.join(".local").exists());
        let dmg = Path::new("/Volumes/Marathon/Marathon.app/Contents/Helpers/marathon");
        assert!(set_up(&home, dmg, "").unwrap().skipped.is_some());
        fs::remove_dir_all(home).unwrap();
    }
}