1use std::fs;
11use std::io::{self, Write};
12use std::path::{Path, PathBuf};
13
14pub const PATH_LINE: &str = "export PATH=\"$HOME/.local/bin:$PATH\"";
16const MARKER: &str = "# Added by Marathon so the `marathon` command works";
17
18const PROFILES: &[&str] = &[
20 ".zshenv",
21 ".zprofile",
22 ".zshrc",
23 ".profile",
24 ".bash_profile",
25 ".bashrc",
26];
27
28#[derive(Debug, Default, PartialEq, Eq)]
30pub struct Report {
31 pub linked: bool,
33 pub profile: Option<PathBuf>,
35 pub skipped: Option<&'static str>,
37}
38
39pub fn set_up(home: &Path, helper: &Path, shell: &str) -> io::Result<Report> {
44 let mut report = Report::default();
45 if managed_by_homebrew(helper) {
46 report.skipped = Some("Homebrew already links the command");
47 return Ok(report);
48 }
49 if runs_from_temporary_place(helper) {
50 report.skipped = Some("the app isn't in its final place yet");
51 return Ok(report);
52 }
53 if !helper.is_file() {
54 report.skipped = Some("the app has no command inside it");
55 return Ok(report);
56 }
57 let bin = home.join(".local/bin");
58 let link = bin.join("marathon");
59 match fs::symlink_metadata(&link) {
60 Ok(meta) if !meta.file_type().is_symlink() => {
62 report.skipped = Some("another marathon command is already there");
63 return Ok(report);
64 }
65 Ok(_) => {
66 let target = fs::read_link(&link)?;
67 if target != helper {
68 if target.exists() && !is_app_helper(&target) {
71 report.skipped = Some("another marathon command is already there");
72 return Ok(report);
73 }
74 fs::remove_file(&link)?;
75 symlink(helper, &link)?;
76 }
77 }
78 Err(e) if e.kind() == io::ErrorKind::NotFound => {
79 fs::create_dir_all(&bin)?;
80 symlink(helper, &link)?;
81 }
82 Err(e) => return Err(e),
83 }
84 report.linked = true;
85
86 if !PROFILES.iter().any(|p| mentions_local_bin(&home.join(p))) {
87 let profile = home.join(login_profile(shell));
88 let mut file = fs::OpenOptions::new()
89 .create(true)
90 .append(true)
91 .open(&profile)?;
92 let lead = match fs::read(&profile) {
93 Ok(bytes) if !bytes.is_empty() && !bytes.ends_with(b"\n") => "\n",
94 _ => "",
95 };
96 write!(file, "{lead}\n{MARKER}\n{PATH_LINE}\n")?;
97 report.profile = Some(profile);
98 }
99 Ok(report)
100}
101
102fn login_profile(shell: &str) -> &'static str {
104 if shell.ends_with("/bash") {
105 ".bash_profile"
106 } else {
107 ".zprofile"
108 }
109}
110
111fn managed_by_homebrew(helper: &Path) -> bool {
112 let s = helper.to_string_lossy();
113 s.contains("/Cellar/") || s.contains("/Caskroom/") || s.starts_with("/opt/homebrew/")
114}
115
116fn runs_from_temporary_place(helper: &Path) -> bool {
119 let s = helper.to_string_lossy();
120 s.starts_with("/Volumes/") || s.contains("/AppTranslocation/")
121}
122
123fn is_app_helper(path: &Path) -> bool {
124 path.ends_with("Contents/Helpers/marathon")
125}
126
127fn mentions_local_bin(profile: &Path) -> bool {
128 fs::read_to_string(profile).is_ok_and(|s| s.contains(".local/bin"))
129}
130
131#[cfg(unix)]
132fn symlink(target: &Path, link: &Path) -> io::Result<()> {
133 std::os::unix::fs::symlink(target, link)
134}
135
136#[cfg(not(unix))]
137fn symlink(_: &Path, _: &Path) -> io::Result<()> {
138 Err(io::Error::new(
139 io::ErrorKind::Unsupported,
140 "needs a Unix system",
141 ))
142}
143
144#[cfg(all(test, unix))]
145mod tests {
146 use super::*;
147
148 fn scratch(name: &str) -> PathBuf {
149 let dir = std::env::temp_dir().join(format!("marathon-cmd-{name}-{}", std::process::id()));
150 let _ = fs::remove_dir_all(&dir);
151 fs::create_dir_all(&dir).unwrap();
152 dir
153 }
154
155 fn app(root: &Path, at: &str) -> PathBuf {
156 let helper = root.join(at).join("Marathon.app/Contents/Helpers/marathon");
157 fs::create_dir_all(helper.parent().unwrap()).unwrap();
158 fs::write(&helper, "").unwrap();
159 helper
160 }
161
162 #[test]
163 fn links_and_adds_path_once() {
164 let home = scratch("fresh");
165 let helper = app(&home, "Applications");
166 let r = set_up(&home, &helper, "/bin/zsh").unwrap();
167 assert!(r.linked);
168 assert_eq!(r.profile, Some(home.join(".zprofile")));
169 assert_eq!(
170 fs::read_link(home.join(".local/bin/marathon")).unwrap(),
171 helper
172 );
173 let again = set_up(&home, &helper, "/bin/zsh").unwrap();
174 assert!(again.linked && again.profile.is_none());
175 let text = fs::read_to_string(home.join(".zprofile")).unwrap();
176 assert_eq!(text.matches(PATH_LINE).count(), 1);
177 fs::remove_dir_all(home).unwrap();
178 }
179
180 #[test]
181 fn keeps_existing_path_setup_and_bash() {
182 let home = scratch("bash");
183 let helper = app(&home, "Applications");
184 let r = set_up(&home, &helper, "/bin/bash").unwrap();
185 assert_eq!(r.profile, Some(home.join(".bash_profile")));
186
187 let home2 = scratch("haspath");
188 let helper2 = app(&home2, "Applications");
189 fs::write(home2.join(".zshrc"), "export PATH=~/.local/bin:$PATH").unwrap();
190 assert!(
191 set_up(&home2, &helper2, "/bin/zsh")
192 .unwrap()
193 .profile
194 .is_none()
195 );
196 assert!(!home2.join(".zprofile").exists());
197 fs::remove_dir_all(home).unwrap();
198 fs::remove_dir_all(home2).unwrap();
199 }
200
201 #[test]
202 fn moves_link_to_new_app_but_respects_others() {
203 let home = scratch("move");
204 let old = app(&home, "old");
205 let new = app(&home, "Applications");
206 set_up(&home, &old, "").unwrap();
207 set_up(&home, &new, "").unwrap();
208 let link = home.join(".local/bin/marathon");
209 assert_eq!(fs::read_link(&link).unwrap(), new);
210
211 let other = home.join("npm/marathon");
213 fs::create_dir_all(other.parent().unwrap()).unwrap();
214 fs::write(&other, "").unwrap();
215 fs::remove_file(&link).unwrap();
216 std::os::unix::fs::symlink(&other, &link).unwrap();
217 let r = set_up(&home, &new, "").unwrap();
218 assert!(!r.linked && r.skipped.is_some());
219 assert_eq!(fs::read_link(&link).unwrap(), other);
220 fs::remove_dir_all(home).unwrap();
221 }
222
223 #[test]
224 fn leaves_homebrew_alone() {
225 let home = scratch("brew");
226 let helper =
227 Path::new("/opt/homebrew/Cellar/marathon/0.1.4/Marathon.app/Contents/Helpers/marathon");
228 let r = set_up(&home, helper, "").unwrap();
229 assert!(!r.linked && r.skipped.is_some());
230 assert!(!home.join(".local").exists());
231 let dmg = Path::new("/Volumes/Marathon/Marathon.app/Contents/Helpers/marathon");
232 assert!(set_up(&home, dmg, "").unwrap().skipped.is_some());
233 fs::remove_dir_all(home).unwrap();
234 }
235}