1use std::collections::HashMap;
28use std::ffi::OsStr;
29use std::path::{Path, PathBuf};
30use std::sync::{Arc, Mutex, OnceLock};
31
32const DEVELOPER_TOOLS_OVERRIDE_ENV: &str = "AFT_TEST_DEVELOPER_TOOLS";
35const LAUNCHER_DIRS_OVERRIDE_ENV: &str = "AFT_TEST_XCODE_LAUNCHER_DIRS";
38
39const XCSELECT_LIBRARY_MARKER: &[u8] = b"/usr/lib/libxcselect.dylib";
42
43#[derive(Clone, Debug, PartialEq, Eq)]
45pub enum GitAvailability {
46 Usable,
49 MissingDeveloperTools { launcher: PathBuf },
52}
53
54pub const MISSING_DEVELOPER_TOOLS_REASON: &str =
56 "git features are off: macOS developer tools are not installed, and running \
57 /usr/bin/git would open Apple's install dialog. Install them with \
58 `xcode-select --install`, or put another git (for example Homebrew's) on PATH, \
59 then restart AFT.";
60
61#[derive(Clone, Debug, PartialEq, Eq)]
62struct LauncherStamp {
63 len: u64,
64 modified: Option<std::time::SystemTime>,
65 #[cfg(unix)]
66 identity: (u64, u64, i64, i64, u32),
67}
68
69impl LauncherStamp {
70 fn from_metadata(metadata: &std::fs::Metadata) -> Self {
71 #[cfg(unix)]
72 use std::os::unix::fs::MetadataExt;
73 Self {
74 len: metadata.len(),
75 modified: metadata.modified().ok(),
76 #[cfg(unix)]
77 identity: (
78 metadata.dev(),
79 metadata.ino(),
80 metadata.ctime(),
81 metadata.ctime_nsec(),
82 metadata.mode(),
83 ),
84 }
85 }
86}
87
88type LauncherCache = Arc<Mutex<HashMap<PathBuf, (LauncherStamp, bool)>>>;
89
90#[derive(Clone, Debug)]
93pub struct Detector {
94 launcher_dirs: Vec<PathBuf>,
95 require_xcselect_marker: bool,
99 developer_tools_present: bool,
100 launcher_cache: LauncherCache,
101 #[cfg(any(test, feature = "test-support"))]
102 marker_reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
103}
104
105impl Detector {
106 pub fn new(launcher_dirs: Vec<PathBuf>, developer_tools_present: bool) -> Self {
109 Self {
110 launcher_dirs: canonical_dirs(launcher_dirs),
111 require_xcselect_marker: false,
112 developer_tools_present,
113 launcher_cache: Default::default(),
114 #[cfg(any(test, feature = "test-support"))]
115 marker_reads: Default::default(),
116 }
117 }
118
119 fn from_process() -> Self {
120 let override_dirs = std::env::var_os(LAUNCHER_DIRS_OVERRIDE_ENV)
121 .filter(|value| !value.is_empty())
122 .map(|value| std::env::split_paths(&value).collect::<Vec<_>>());
123 let override_tools = std::env::var(DEVELOPER_TOOLS_OVERRIDE_ENV)
124 .ok()
125 .and_then(|value| match value.as_str() {
126 "absent" => Some(false),
127 "present" => Some(true),
128 _ => None,
129 });
130
131 let (launcher_dirs, require_xcselect_marker) = match override_dirs {
132 Some(dirs) => (canonical_dirs(dirs), false),
133 None if cfg!(target_os = "macos") => (vec![PathBuf::from("/usr/bin")], true),
134 None => (Vec::new(), false),
135 };
136 let developer_tools_present = override_tools.unwrap_or_else(|| {
139 launcher_dirs.is_empty()
140 || macos_developer_tools_present(DeveloperDirProbe::system())
141 || xcode_select_reports_developer_dir()
142 });
143 Self {
144 launcher_dirs,
145 require_xcselect_marker,
146 developer_tools_present,
147 launcher_cache: Default::default(),
148 #[cfg(any(test, feature = "test-support"))]
149 marker_reads: Default::default(),
150 }
151 }
152
153 pub fn developer_tools_present(&self) -> bool {
154 self.developer_tools_present
155 }
156
157 pub fn is_unusable_launcher(&self, path: &Path) -> bool {
161 self.is_unusable_launcher_with_reader(path, |path| std::fs::read(path))
162 }
163
164 fn is_unusable_launcher_with_reader(
165 &self,
166 path: &Path,
167 read: impl FnOnce(&Path) -> std::io::Result<Vec<u8>>,
168 ) -> bool {
169 if self.developer_tools_present || self.launcher_dirs.is_empty() {
170 return false;
171 }
172 let canonical = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
173 let in_launcher_dir = canonical
174 .parent()
175 .is_some_and(|parent| self.launcher_dirs.iter().any(|dir| dir == parent));
176 if !in_launcher_dir {
177 return false;
178 }
179 if !self.require_xcselect_marker {
180 return true;
181 }
182 let Ok(metadata) = std::fs::metadata(&canonical) else {
183 return true;
184 };
185 let stamp = LauncherStamp::from_metadata(&metadata);
186 let mut cache = self
187 .launcher_cache
188 .lock()
189 .unwrap_or_else(|error| error.into_inner());
190 if let Some((cached_stamp, decision)) = cache.get(&canonical) {
191 if cached_stamp == &stamp {
192 return *decision;
193 }
194 }
195 #[cfg(any(test, feature = "test-support"))]
196 self.marker_reads
197 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
198 let bytes = match read(&canonical) {
199 Ok(bytes) => bytes,
200 Err(_) => return true,
203 };
204 let decision = contains_subslice(&bytes, XCSELECT_LIBRARY_MARKER);
205 cache.insert(canonical, (stamp, decision));
206 decision
207 }
208
209 pub fn git_availability(&self, path_var: &OsStr) -> GitAvailability {
211 if self.developer_tools_present || self.launcher_dirs.is_empty() {
212 return GitAvailability::Usable;
213 }
214 match first_on_path(path_var, "git") {
215 Some(git) if self.is_unusable_launcher(&git) => {
216 GitAvailability::MissingDeveloperTools { launcher: git }
217 }
218 _ => GitAvailability::Usable,
219 }
220 }
221}
222
223fn canonical_dirs(dirs: Vec<PathBuf>) -> Vec<PathBuf> {
224 dirs.into_iter()
225 .filter(|dir| !dir.as_os_str().is_empty())
226 .map(|dir| std::fs::canonicalize(&dir).unwrap_or(dir))
227 .collect()
228}
229
230fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool {
231 !needle.is_empty()
232 && haystack
233 .windows(needle.len())
234 .any(|window| window == needle)
235}
236
237fn first_on_path(path_var: &OsStr, binary: &str) -> Option<PathBuf> {
239 std::env::split_paths(path_var)
240 .filter(|dir| !dir.as_os_str().is_empty())
241 .find_map(|dir| crate::tool_path::probe_tool_in_dir(&dir, binary))
242}
243
244#[derive(Clone, Debug)]
246pub struct DeveloperDirProbe {
247 pub developer_dir_env: Option<PathBuf>,
248 pub selection_link: PathBuf,
249 pub defaults: Vec<PathBuf>,
250}
251
252impl DeveloperDirProbe {
253 fn system() -> Self {
254 Self {
255 developer_dir_env: crate::environment::non_empty_os_var("DEVELOPER_DIR")
256 .map(PathBuf::from),
257 selection_link: PathBuf::from("/var/db/xcode_select_link"),
258 defaults: vec![
259 PathBuf::from("/Applications/Xcode.app/Contents/Developer"),
260 PathBuf::from("/Library/Developer/CommandLineTools"),
261 ],
262 }
263 }
264}
265
266fn is_developer_dir(dir: &Path) -> bool {
269 dir.join("usr").join("bin").is_dir()
270}
271
272pub fn macos_developer_tools_present(probe: DeveloperDirProbe) -> bool {
274 if let Some(dir) = probe.developer_dir_env {
275 return is_developer_dir(&dir);
278 }
279 if let Ok(selected) = std::fs::canonicalize(&probe.selection_link) {
280 if is_developer_dir(&selected) {
281 return true;
282 }
283 }
284 probe.defaults.iter().any(|dir| is_developer_dir(dir))
285}
286
287fn xcode_select_reports_developer_dir() -> bool {
294 if !cfg!(target_os = "macos") {
295 return false;
296 }
297 std::process::Command::new("/usr/bin/xcode-select")
298 .arg("-p")
299 .stdin(std::process::Stdio::null())
300 .stderr(std::process::Stdio::null())
301 .output()
302 .is_ok_and(|output| {
303 output.status.success()
304 && is_developer_dir(Path::new(String::from_utf8_lossy(&output.stdout).trim()))
305 })
306}
307
308fn process_detector() -> &'static Detector {
309 static DETECTOR: OnceLock<Detector> = OnceLock::new();
310 DETECTOR.get_or_init(Detector::from_process)
311}
312
313pub fn git_availability() -> &'static GitAvailability {
315 static GIT: OnceLock<GitAvailability> = OnceLock::new();
316 GIT.get_or_init(|| {
317 let availability =
318 process_detector().git_availability(crate::effective_path::effective_path());
319 if let GitAvailability::MissingDeveloperTools { launcher } = &availability {
320 log::warn!(
321 "git disabled for this process: {} is Apple's developer-tools launcher and no \
322 developer tools are installed; running it would open the install dialog. \
323 Git-backed features use their non-git fallbacks.",
324 launcher.display()
325 );
326 }
327 availability
328 })
329}
330
331pub fn git_usable() -> bool {
335 #[cfg(any(test, feature = "test-support"))]
336 if let Some(usable) = TEST_GIT_USABLE.with(|value| value.get()) {
337 return usable;
338 }
339 matches!(git_availability(), GitAvailability::Usable)
340}
341
342#[cfg(any(test, feature = "test-support"))]
343thread_local! {
344 static TEST_GIT_USABLE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
345}
346
347#[cfg(any(test, feature = "test-support"))]
348pub fn with_git_usable_for_test<T>(usable: bool, run: impl FnOnce() -> T) -> T {
349 struct Reset(Option<bool>);
350 impl Drop for Reset {
351 fn drop(&mut self) {
352 TEST_GIT_USABLE.with(|value| value.set(self.0));
353 }
354 }
355 let _reset = Reset(TEST_GIT_USABLE.with(|value| value.replace(Some(usable))));
356 run()
357}
358
359pub fn git_status_json() -> serde_json::Value {
361 match git_availability() {
362 GitAvailability::Usable => serde_json::json!({ "available": true }),
363 GitAvailability::MissingDeveloperTools { launcher } => serde_json::json!({
364 "available": false,
365 "reason": "macos_developer_tools_missing",
366 "message": MISSING_DEVELOPER_TOOLS_REASON,
367 "launcher": launcher.display().to_string(),
368 }),
369 }
370}
371
372pub fn is_unusable_launcher(path: &Path) -> bool {
375 process_detector().is_unusable_launcher(path)
376}
377
378#[cfg(all(test, unix))]
379mod tests {
380 use super::*;
381
382 #[test]
383 fn launcher_read_error_is_retried_without_metadata_changes() {
384 let dir = tempfile::tempdir().unwrap();
385 let tool = dir.path().join("git");
386 std::fs::write(&tool, b"a real tool without the launcher marker").unwrap();
387 let mut detector = Detector::new(vec![dir.path().to_path_buf()], false);
388 detector.require_xcselect_marker = true;
389 let before = LauncherStamp::from_metadata(&std::fs::metadata(&tool).unwrap());
390
391 assert!(detector.is_unusable_launcher_with_reader(&tool, |_| {
392 Err(std::io::Error::from_raw_os_error(libc::EMFILE))
393 }));
394 assert_eq!(
395 before,
396 LauncherStamp::from_metadata(&std::fs::metadata(&tool).unwrap())
397 );
398 assert!(!detector.is_unusable_launcher(&tool));
399 assert_eq!(
400 detector
401 .marker_reads
402 .load(std::sync::atomic::Ordering::Relaxed),
403 2
404 );
405 assert!(!detector.is_unusable_launcher(&tool));
406 assert_eq!(
407 detector
408 .marker_reads
409 .load(std::sync::atomic::Ordering::Relaxed),
410 2
411 );
412 }
413
414 #[test]
415 fn launcher_marker_is_memoized_and_invalidated_by_file_replacement() {
416 let dir = tempfile::tempdir().unwrap();
417 let launcher = dir.path().join("git");
418 std::fs::write(&launcher, XCSELECT_LIBRARY_MARKER).unwrap();
419 let mut detector = Detector::new(vec![dir.path().to_path_buf()], false);
420 detector.require_xcselect_marker = true;
421 assert!(detector.is_unusable_launcher(&launcher));
422 assert!(detector.clone().is_unusable_launcher(&launcher));
423 assert_eq!(
424 detector
425 .marker_reads
426 .load(std::sync::atomic::Ordering::Relaxed),
427 1
428 );
429
430 let replacement = dir.path().join("replacement");
431 std::fs::write(&replacement, vec![b'x'; XCSELECT_LIBRARY_MARKER.len()]).unwrap();
432 let original_time = std::fs::metadata(&launcher).unwrap().modified().unwrap();
434 std::fs::File::options()
435 .write(true)
436 .open(&replacement)
437 .unwrap()
438 .set_modified(original_time)
439 .unwrap();
440 std::fs::remove_file(&launcher).unwrap();
441 std::fs::rename(&replacement, &launcher).unwrap();
442 assert!(!detector.is_unusable_launcher(&launcher));
443 assert!(!detector.is_unusable_launcher(&launcher));
444 assert_eq!(
445 detector
446 .marker_reads
447 .load(std::sync::atomic::Ordering::Relaxed),
448 2
449 );
450 }
451
452 fn executable(path: &Path, body: &str) {
453 crate::executable_cache::write_executable(path, body.as_bytes()).unwrap();
454 }
455
456 #[test]
457 fn launcher_git_without_developer_tools_is_refused() {
458 let temp = tempfile::tempdir().unwrap();
459 let launchers = temp.path().join("usr-bin");
460 std::fs::create_dir_all(&launchers).unwrap();
461 executable(&launchers.join("git"), "#!/bin/sh\nexit 1\n");
462
463 let detector = Detector::new(vec![launchers.clone()], false);
464 assert_eq!(
465 detector.git_availability(launchers.as_os_str()),
466 GitAvailability::MissingDeveloperTools {
467 launcher: launchers.join("git")
468 }
469 );
470 let with_tools = Detector::new(vec![launchers.clone()], true);
472 assert_eq!(
473 with_tools.git_availability(launchers.as_os_str()),
474 GitAvailability::Usable
475 );
476 }
477
478 #[test]
479 fn real_git_earlier_on_path_wins_over_the_launcher() {
480 let temp = tempfile::tempdir().unwrap();
481 let launchers = temp.path().join("usr-bin");
482 let homebrew = temp.path().join("homebrew-bin");
483 std::fs::create_dir_all(&launchers).unwrap();
484 std::fs::create_dir_all(&homebrew).unwrap();
485 executable(&launchers.join("git"), "#!/bin/sh\nexit 1\n");
486 executable(&homebrew.join("git"), "#!/bin/sh\nexit 0\n");
487
488 let detector = Detector::new(vec![launchers.clone()], false);
489 let path = std::env::join_paths([&homebrew, &launchers]).unwrap();
490 assert_eq!(detector.git_availability(&path), GitAvailability::Usable);
491 let reversed = std::env::join_paths([&launchers, &homebrew]).unwrap();
493 assert!(matches!(
494 detector.git_availability(&reversed),
495 GitAvailability::MissingDeveloperTools { .. }
496 ));
497 }
498
499 #[test]
500 fn marker_check_keeps_ordinary_binaries_in_the_launcher_dir() {
501 let temp = tempfile::tempdir().unwrap();
502 let dir = temp.path().join("usr-bin");
503 std::fs::create_dir_all(&dir).unwrap();
504 executable(&dir.join("ssh"), "plain program\n");
505 executable(&dir.join("clangd"), "...\0/usr/lib/libxcselect.dylib\0...");
506 let mut detector = Detector::new(vec![dir.clone()], false);
507 detector.require_xcselect_marker = true;
508 assert!(!detector.is_unusable_launcher(&dir.join("ssh")));
509 assert!(detector.is_unusable_launcher(&dir.join("clangd")));
510 }
511
512 #[test]
513 fn developer_dir_lookup_follows_the_launcher_order() {
514 let temp = tempfile::tempdir().unwrap();
515 let installed = temp.path().join("CommandLineTools");
516 std::fs::create_dir_all(installed.join("usr/bin")).unwrap();
517 let empty = temp.path().join("Leftover");
518 std::fs::create_dir_all(&empty).unwrap();
519 let missing_link = temp.path().join("no-link");
520
521 let probe = |env: Option<&Path>, link: &Path, defaults: Vec<PathBuf>| DeveloperDirProbe {
522 developer_dir_env: env.map(Path::to_path_buf),
523 selection_link: link.to_path_buf(),
524 defaults,
525 };
526 assert!(!macos_developer_tools_present(probe(
527 None,
528 &missing_link,
529 vec![empty.clone(), temp.path().join("Xcode.app")]
530 )));
531 assert!(macos_developer_tools_present(probe(
532 None,
533 &missing_link,
534 vec![installed.clone()]
535 )));
536 let link = temp.path().join("xcode_select_link");
537 std::os::unix::fs::symlink(&installed, &link).unwrap();
538 assert!(macos_developer_tools_present(probe(None, &link, vec![])));
539 assert!(!macos_developer_tools_present(probe(
541 Some(&empty),
542 &link,
543 vec![installed.clone()]
544 )));
545 assert!(macos_developer_tools_present(probe(
546 Some(&installed),
547 &missing_link,
548 vec![]
549 )));
550 }
551}