marathon-core 0.1.6

Marathon's rules: sessions, timers, triggers and time parsing
Documentation
//! How `marathon update` works out where Marathon came from, and whether a
//! newer release is out. The CLI does the actual updating; everything here
//! is plain logic so it tests anywhere.

use std::path::{Path, PathBuf};

/// The Homebrew name of the Marathon cask. Plain `marathon` is a game.
pub const BREW_CASK: &str = "abe238/tap/marathon";

/// Where the release page redirects to the newest tag.
pub const LATEST_URL: &str = "https://github.com/abe238/marathon/releases/latest";

/// How this copy of Marathon was installed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Install {
    /// The Homebrew cask (`brew install abe238/tap/marathon`).
    BrewCask,
    /// The old Homebrew formula, from before 0.1.5.
    BrewFormula,
    /// The curl one-liner or the DMG: an app bundle in this folder.
    App { folder: PathBuf },
    /// `npm install -g marathon-mac`.
    NpmGlobal,
    /// `npm install marathon-mac` inside a project.
    NpmLocal,
    /// `npx marathon-mac`, which runs from npm's cache.
    Npx,
    /// `pip install marathon-mac`, with this Python.
    Pip { python: String },
    /// `pipx install marathon-mac`.
    Pipx,
    /// `uv tool install marathon-mac`.
    UvTool,
    /// `uvx marathon-mac`, which runs from uv's cache.
    Uvx,
    /// The Python package, but we can't tell which tool put it there.
    Python,
    /// `cargo install marathon-cli`.
    Cargo,
    /// No idea.
    Unknown,
}

/// What the wrappers tell the binary about themselves, from the
/// `MARATHON_VIA` and `MARATHON_PYTHON` variables they set.
#[derive(Debug, Default, Clone)]
pub struct Hints {
    pub via: Option<String>,
    pub python: Option<String>,
    pub cargo_home: Option<PathBuf>,
    pub home: Option<PathBuf>,
}

/// Works out the install from the binary's real path (symlinks resolved)
/// and the wrappers' hints. `brew_has_cask` is asked only when the app
/// sits in `/Applications`, where both Homebrew and the DMG put it.
pub fn detect(exe: &Path, hints: &Hints, brew_has_cask: impl FnOnce() -> bool) -> Install {
    let path = exe.to_string_lossy();
    if hints.via.as_deref() == Some("npm") || path.contains("/node_modules/marathon-mac/") {
        return if path.contains("/_npx/") {
            Install::Npx
        } else if path.contains("/lib/node_modules/") {
            Install::NpmGlobal
        } else {
            Install::NpmLocal
        };
    }
    if hints.via.as_deref() == Some("pypi") || path.contains("/Caches/marathon-mac/") {
        return python_install(hints.python.as_deref());
    }
    if path.contains("/Cellar/") {
        return Install::BrewFormula;
    }
    if let Some(folder) = app_folder(exe) {
        if folder == Path::new("/Applications") && brew_has_cask() {
            return Install::BrewCask;
        }
        return Install::App { folder };
    }
    let cargo_bin = hints
        .cargo_home
        .clone()
        .or_else(|| hints.home.as_ref().map(|h| h.join(".cargo")))
        .map(|c| c.join("bin"));
    if cargo_bin.is_some_and(|bin| exe.parent() == Some(&bin)) {
        return Install::Cargo;
    }
    Install::Unknown
}

/// Which Python tool owns the package, from the interpreter that ran it.
fn python_install(python: Option<&str>) -> Install {
    let Some(py) = python else {
        return Install::Python;
    };
    if py.contains("/uv/tools/") {
        Install::UvTool
    } else if py.contains("/pipx/venvs/") {
        Install::Pipx
    } else if py.contains("/uv/") {
        // uvx runs from an environment in uv's cache.
        Install::Uvx
    } else {
        Install::Pip { python: py.into() }
    }
}

/// The folder holding `Marathon.app`, if `exe` is the command inside an
/// app bundle (`…/Marathon.app/Contents/Helpers/marathon`).
pub fn app_folder(exe: &Path) -> Option<PathBuf> {
    let app = exe.parent()?.parent()?.parent()?;
    let is_bundle = app.extension().is_some_and(|e| e == "app")
        && exe.parent()?.file_name()? == "Helpers"
        && exe.parent()?.parent()?.file_name()? == "Contents";
    is_bundle.then(|| app.parent().map(Path::to_path_buf))?
}

/// A version like `0.1.5` or `v0.1.5`, as numbers.
pub fn parse_version(s: &str) -> Option<Vec<u64>> {
    let s = s.trim().trim_start_matches('v');
    let nums: Option<Vec<u64>> = s.split('.').map(|p| p.parse().ok()).collect();
    nums.filter(|n| !n.is_empty())
}

/// Whether `latest` is newer than `current`.
pub fn is_newer(latest: &str, current: &str) -> bool {
    match (parse_version(latest), parse_version(current)) {
        (Some(l), Some(c)) => l > c,
        _ => false,
    }
}

/// The version from the page `releases/latest` redirects to, such as
/// `https://github.com/abe238/marathon/releases/tag/v0.1.6`.
pub fn version_from_url(url: &str) -> Option<String> {
    let tag = url.trim().rsplit_once("/releases/tag/")?.1;
    let v = tag.trim_end_matches('/').trim_start_matches('v');
    parse_version(v).map(|_| v.to_string())
}

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

    fn d(exe: &str, hints: &Hints, brew: bool) -> Install {
        detect(Path::new(exe), hints, || brew)
    }

    #[test]
    fn versions() {
        assert!(is_newer("0.1.6", "0.1.5"));
        assert!(is_newer("v0.2.0", "0.1.10"));
        assert!(is_newer("0.1.10", "0.1.9"));
        assert!(!is_newer("0.1.5", "0.1.5"));
        assert!(!is_newer("0.1.4", "0.1.5"));
        assert!(!is_newer("garbage", "0.1.5"));
        assert_eq!(
            version_from_url("https://github.com/abe238/marathon/releases/tag/v0.1.6\n"),
            Some("0.1.6".into())
        );
        assert_eq!(
            version_from_url("https://github.com/abe238/marathon/releases"),
            None
        );
    }

    #[test]
    fn apps() {
        let h = Hints::default();
        let exe = "/Applications/Marathon.app/Contents/Helpers/marathon";
        assert_eq!(d(exe, &h, true), Install::BrewCask);
        assert_eq!(
            d(exe, &h, false),
            Install::App {
                folder: "/Applications".into()
            }
        );
        let mine = "/Users/a/Applications/Marathon.app/Contents/Helpers/marathon";
        assert_eq!(
            d(mine, &h, true),
            Install::App {
                folder: "/Users/a/Applications".into()
            }
        );
        assert_eq!(
            d("/opt/homebrew/Cellar/marathon/0.1.4/bin/marathon", &h, true),
            Install::BrewFormula
        );
    }

    #[test]
    fn npm() {
        let h = Hints {
            via: Some("npm".into()),
            ..Hints::default()
        };
        let tail = "node_modules/marathon-mac/vendor/Marathon.app/Contents/Helpers/marathon";
        assert_eq!(
            d(&format!("/Users/a/.npm/_npx/abc/{tail}"), &h, false),
            Install::Npx
        );
        assert_eq!(
            d(&format!("/opt/homebrew/lib/{tail}"), &h, true),
            Install::NpmGlobal
        );
        assert_eq!(
            d(&format!("/Users/a/proj/{tail}"), &Hints::default(), false),
            Install::NpmLocal
        );
    }

    #[test]
    fn python() {
        let exe =
            "/Users/a/Library/Caches/marathon-mac/0.1.5/Marathon.app/Contents/Helpers/marathon";
        let with = |py: &str| Hints {
            via: Some("pypi".into()),
            python: Some(py.into()),
            ..Hints::default()
        };
        assert_eq!(
            d(
                exe,
                &with("/Users/a/.local/share/uv/tools/marathon-mac/bin/python"),
                false
            ),
            Install::UvTool
        );
        assert_eq!(
            d(
                exe,
                &with("/Users/a/.local/pipx/venvs/marathon-mac/bin/python"),
                false
            ),
            Install::Pipx
        );
        assert_eq!(
            d(
                exe,
                &with("/Users/a/.cache/uv/archive-v0/xyz/bin/python"),
                false
            ),
            Install::Uvx
        );
        assert_eq!(
            d(exe, &with("/usr/bin/python3"), false),
            Install::Pip {
                python: "/usr/bin/python3".into()
            }
        );
        assert_eq!(d(exe, &Hints::default(), false), Install::Python);
    }

    #[test]
    fn cargo_and_unknown() {
        let h = Hints {
            home: Some("/Users/a".into()),
            ..Hints::default()
        };
        assert_eq!(d("/Users/a/.cargo/bin/marathon", &h, false), Install::Cargo);
        let custom = Hints {
            cargo_home: Some("/opt/cargo".into()),
            ..h.clone()
        };
        assert_eq!(d("/opt/cargo/bin/marathon", &custom, false), Install::Cargo);
        assert_eq!(d("/usr/local/bin/marathon", &h, false), Install::Unknown);
    }
}