//! Where `git` is on this Mac — by stat-ing, and by invoking nothing. //! //! ## Why a ladder and not `which` //! //! Measured on macOS 27: `/usr/bin/git` is a 200 KB hardlinked stub (link //! count 78 — the same inode serves `/usr/bin/clang` and `/usr/bin/make`) //! whose one import is `_xcselect_invoke_xcrun`, signed //! `com.apple.dt.xcode_select.tool-shim-public`. It exists on every Mac //! whether git is installed or not, so `which -a git` answers it on a machine //! with no git at all. With no Command Line Tools it exits 1 AND posts //! *"The 'git' command requires the command line developer tools"* into the //! caller's Aqua session — from a LaunchAgent, which is what this app's helper //! is. Homebrew guards the same call for the same reason //! (`Library/Homebrew/brew.sh`: *"Don't check xcrun if Xcode and the CLT //! aren't installed, as that opens a popup window"*). There is no suppression //! environment variable. //! //! `xcrun --find git` is worse — it shells out to `xcodebuild` and HANGS for //! ever when `xcode-select -p` is `/`. `xcode-select -p` itself is safe but is //! not a validity check: with `DEVELOPER_DIR=/nonexistent` it prints //! `/nonexistent/Developer` and exits 0. //! //! **Stat-ing absolute paths is the only thing that cannot prompt**, so that is //! the whole of what this file does. //! //! ## The order, and why it is this order //! //! **THE LADDER IS `cotton_core::git::CANDIDATES` AND THIS CRATE ONLY READS //! IT.** It used to be declared here as well — the third of three Rust copies, //! and the only unguarded one — which is what made the drift possible. //! `/usr/bin/git` is not on the list and must never be added: //! [`the_shim_is_never_a_candidate`] is the guard on this side, and //! `cotton-core`'s own suite is the guard on the declaration. //! //! ## Absent is a STATE //! //! `None` is a real answer, not a failure: it is the Mac that has neither the //! Command Line Tools nor Homebrew git, and the honest thing is a sentence on //! the Serving page ([`GIT_MISSING`]) and nothing cloned. The same shape as //! the Mac's ingest sources answering `no_permission` — a state, never an //! error, and never a retry loop against the shim. use std::path::{Path, PathBuf}; /// Every path this Mac may find `git` at, in the order it is looked for — /// `cotton_core::git::CANDIDATES`, RE-EXPORTED AND NOT DECLARED. /// /// There is ONE Rust declaration of this ladder and it is the core's. The Mac /// app still holds a Swift literal twin (`CottonHost`'s `HelperPaths`), because /// it exports `COTTON_GIT` BEFORE `cotton_open` and has no core to ask yet; /// `scripts/__tests__/swift-mac.test.ts` holds that twin equal to the core's /// file. Nothing in Rust can drift any more, because nothing in Rust repeats /// the list. pub use cotton_core::git::CANDIDATES as GIT_CANDIDATES; /// The path that is NEVER a candidate, named so the guard can say why. pub use cotton_core::git::SHIM as XCODE_SELECT_SHIM; /// What the Serving page says when the ladder finds nothing. /// /// A sentence a person can act on, and the two ways to act on it, because /// "git is not installed" on a Mac that has `/usr/bin/git` reads as a lie /// otherwise. pub const GIT_MISSING: &str = "git is not installed on this Mac. Install the Xcode Command Line Tools \ (xcode-select --install) or Homebrew git, then restart CottonDB."; /// The environment variable the answer travels in — /// `cotton_core::git::PROGRAM_ENV`. /// /// A variable and not a field on the config struct, for /// `HelperPaths::litestream`'s reason: every call site of that struct is a /// literal, and where a person's git happens to live is not something the FFI /// ABI should grow a field for. Read once, when the core is built. pub use cotton_core::git::PROGRAM_ENV as GIT_VARIABLE; /// Does this path name a file that exists? /// /// Injected so every case below runs without a real `/opt/homebrew`. The real /// one is [`file_exists`]. pub type Exists<'a> = &'a dyn Fn(&Path) -> bool; /// `std::fs::metadata` — a stat, and nothing executed. /// /// A DIRECTORY named `git` is not a program, which is why this asks whether /// the path is a file rather than whether it exists. It does not ask whether /// the bit is executable: a `git` on one of these four paths that is not /// executable is a broken install, and the refusal a person can read comes /// from running it, not from a permission bit this process might not be able /// to see. pub fn file_exists(path: &Path) -> bool { std::fs::metadata(path) .map(|meta| meta.is_file()) .unwrap_or(false) } /// The first `git` on the ladder, or `None`. /// /// Pure over `exists`, so the order and the absence are both held by a test /// rather than by whatever happens to be installed on the machine running it. pub fn discover_git_with(exists: Exists<'_>) -> Option { GIT_CANDIDATES .iter() .map(PathBuf::from) .find(|path| exists(path)) } /// What an explicit [`GIT_VARIABLE`] names, if it names a git at all. /// /// **THE SHIM IS REFUSED BY NAME HERE TOO.** The ladder cannot hold /// `/usr/bin/git` — a test says so — but the variable is a path an operator /// types by hand (the procedure “Hold a repository's bytes in Cotton, and move its origin off the git host”), so it is the one way the /// shim could still be reached, and from a GUI app running it posts Apple's /// install-the-tools dialog into an Aqua session nobody is sitting at. A /// RELATIVE path is refused for the same by-name reason: it resolves against a /// working directory nobody chose. `cotton-server`'s twin /// (`repos::git::git_at`) refuses both, and this is the half the Mac's own /// export goes through. /// /// Pure over `exists`, so both refusals are held by a test rather than by what /// happens to be on the machine running it. pub fn git_from_variable(named: &std::ffi::OsStr, exists: Exists<'_>) -> Option { let path = PathBuf::from(named); if path.as_os_str().is_empty() || !path.is_absolute() || (cfg!(target_os = "macos") && path == Path::new(XCODE_SELECT_SHIM)) { return None; } exists(&path).then_some(path) } /// The first `git` on this Mac's ladder, or `None`. /// /// An explicit `COTTON_GIT` wins — that is what the Swift side exports, and /// what a rehearsal pointed at a fake git sets. It is stat-ed like every other /// candidate, and refused by name like the shim: see [`git_from_variable`]. A /// variable naming a path that is not there is a misconfiguration to fall /// through, not a program to try to run. pub fn discover_git() -> Option { if let Some(named) = std::env::var_os(GIT_VARIABLE) { if let Some(path) = git_from_variable(&named, &file_exists) { return Some(path); } } if cfg!(target_os = "linux") { return cotton_core::git::git_on_path(std::env::var_os("PATH").as_deref()); } discover_git_with(&file_exists) } #[cfg(test)] mod tests { use super::*; use std::collections::BTreeSet; /// A machine on which exactly these paths hold a file. fn machine<'a>(present: &'a [&'a str]) -> impl Fn(&Path) -> bool + 'a { let set: BTreeSet<&str> = present.iter().copied().collect(); move |path: &Path| set.contains(&path.to_string_lossy().as_ref()) } #[test] fn the_shim_is_never_a_candidate() { assert!( !GIT_CANDIDATES.contains(&XCODE_SELECT_SHIM), "{XCODE_SELECT_SHIM} is the xcode-select shim: from a GUI app it posts Apple's \ install-the-tools dialog into the caller's Aqua session, on a Mac nobody is sitting \ at. It must never be on this ladder." ); // And nothing on the ladder is under `/usr/bin` at all, so a fifth // entry cannot sneak the shim's directory back in. for candidate in GIT_CANDIDATES { assert!( !candidate.starts_with("/usr/bin/"), "{candidate} is under /usr/bin, which is where the shims live" ); assert!( candidate.starts_with('/'), "{candidate} is not absolute — a relative candidate is resolved against a \ working directory nobody chose" ); } } #[test] fn an_explicit_variable_is_refused_by_name_exactly_as_the_ladder_is() { // THE VARIABLE IS THE ONE WAY BACK TO THE SHIM. The ladder cannot hold // `/usr/bin/git` (the case above), but `COTTON_GIT` is a path an // operator types by hand — and the ladder's own refusal is worth // nothing if the override waves the same path through. A relative path // goes with it: it resolves against a working directory nobody chose. let everything = |_: &Path| true; for refused in [ #[cfg(target_os = "macos")] XCODE_SELECT_SHIM, "", "git", "./git", "../usr/bin/git", "bin/git", ] { assert_eq!( git_from_variable(std::ffi::OsStr::new(refused), &everything), None, "`{refused}` was accepted as this Mac's git" ); } // And what it is FOR still works: an absolute path to a real file, // which is what the Mac exports and what a rehearsal points at a fake. assert_eq!( git_from_variable(std::ffi::OsStr::new("/opt/homebrew/bin/git"), &everything), Some(PathBuf::from("/opt/homebrew/bin/git")) ); // A variable naming something that is not there falls through to the // ladder rather than being run. assert_eq!( git_from_variable( std::ffi::OsStr::new("/tmp/no-git-here"), &machine(&["/opt/homebrew/bin/git"]) ), None ); } #[test] fn homebrew_wins_over_the_command_line_tools_because_a_person_chose_it() { let exists = machine(&[ "/opt/homebrew/bin/git", "/Library/Developer/CommandLineTools/usr/bin/git", "/Applications/Xcode.app/Contents/Developer/usr/bin/git", ]); assert_eq!( discover_git_with(&exists), Some(PathBuf::from("/opt/homebrew/bin/git")) ); } #[test] fn every_rung_of_the_ladder_is_reached_in_its_declared_order() { // One machine per rung, each holding only that rung and the ones below // it — so a reordering of the constant is a red run here. for (index, candidate) in GIT_CANDIDATES.iter().enumerate() { let present: Vec<&str> = GIT_CANDIDATES[index..].to_vec(); let exists = machine(&present); assert_eq!( discover_git_with(&exists).as_deref(), Some(Path::new(candidate)), "with {present:?} installed the ladder did not pick {candidate}" ); } } #[test] fn a_mac_with_no_git_answers_none_and_the_sentence_says_what_to_do() { // The shim is there — it is on every Mac — and it changes nothing. let exists = machine(&[XCODE_SELECT_SHIM]); assert_eq!( discover_git_with(&exists), None, "the shim was read as an installed git" ); assert!(GIT_MISSING.contains("xcode-select --install")); assert!(GIT_MISSING.contains("Homebrew")); } #[test] fn a_directory_named_git_is_not_a_program() { let root = tempfile::tempdir().expect("a temp dir"); let directory = root.path().join("git"); std::fs::create_dir(&directory).expect("a directory"); assert!(!file_exists(&directory)); let file = root.path().join("real-git"); std::fs::write(&file, b"#!/bin/sh\n").expect("a file"); assert!(file_exists(&file)); assert!(!file_exists(&root.path().join("nothing-here"))); } } #[cfg(all(test, target_os = "linux"))] mod linux_tests { /// RULE: Linux accepts its system git because it is not an Xcode shim. #[test] fn linux_accepts_system_git() { assert_eq!(super::git_from_variable(std::ffi::OsStr::new("/usr/bin/git"), &|_| true), Some(std::path::PathBuf::from("/usr/bin/git"))); } }