use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
pub const PATH_LINE: &str = "export PATH=\"$HOME/.local/bin:$PATH\"";
const MARKER: &str = "# Added by Marathon so the `marathon` command works";
const PROFILES: &[&str] = &[
".zshenv",
".zprofile",
".zshrc",
".profile",
".bash_profile",
".bashrc",
];
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Report {
pub linked: bool,
pub profile: Option<PathBuf>,
pub skipped: Option<&'static str>,
}
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) {
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 {
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)
}
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/")
}
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);
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();
}
}