Skip to main content

omni_dev/
git.rs

1//! Git operations and repository management.
2
3use std::path::{Path, PathBuf};
4
5pub mod amendment;
6pub mod commit;
7pub mod diff_split;
8pub mod main_branches;
9pub mod remote;
10pub mod repository;
11pub mod worktree_rebase;
12
13pub use amendment::AmendmentHandler;
14pub use commit::{
15    refine_message_scope, resolve_scope, CommitAnalysis, CommitAnalysisForAI, CommitInfo,
16    CommitInfoForAI, FileDiffRef,
17};
18pub use diff_split::{split_by_file, split_file_by_hunk, FileDiff, HunkDiff};
19pub use main_branches::{branches_containing, detect_main_branch_tips, MainBranchTip};
20pub use remote::RemoteInfo;
21pub use repository::GitRepository;
22
23/// Number of hex characters to show in abbreviated commit hashes.
24pub const SHORT_HASH_LEN: usize = 8;
25
26/// Length of a full SHA-1 commit hash in hex characters.
27pub const FULL_HASH_LEN: usize = 40;
28
29/// Environment override for the `git` binary, for when a process runs under
30/// launchd/systemd with a minimal `PATH`. The exact analogue of
31/// `OMNI_DEV_GH_BIN` (`crate::pr_status`) and `OMNI_DEV_VSCODE_BIN` (the tray's
32/// `code` launcher).
33const GIT_BIN_ENV: &str = "OMNI_DEV_GIT_BIN";
34
35/// Absolute paths probed for `git` when [`GIT_BIN_ENV`] is unset, in order.
36///
37/// The daemon cannot rely on `PATH`: launchd hands it
38/// `/usr/bin:/bin:/usr/sbin:/sbin`. On macOS that *does* contain `/usr/bin/git`
39/// (the Xcode command-line-tools shim), so the fallback would work โ€” but it
40/// would silently pick a different `git` than the user's shell does, which for
41/// a history-rewriting operation is exactly the kind of divergence worth ruling
42/// out. Homebrew first, therefore, matching [`GH_BINARY_CANDIDATES`] order.
43///
44/// [`GH_BINARY_CANDIDATES`]: crate::pr_status
45const GIT_BINARY_CANDIDATES: &[&str] = &[
46    "/opt/homebrew/bin/git",
47    "/usr/local/bin/git",
48    "/home/linuxbrew/.linuxbrew/bin/git",
49    "/usr/bin/git",
50];
51
52/// Resolves `git`, preferring [`GIT_BIN_ENV`], then the first existing
53/// well-known absolute path, then bare `git` on `PATH`.
54///
55/// This is the fix for the *real* obstacle to running git from the daemon
56/// (ADR-0059). The obstacle was never credentials โ€” launchd exports
57/// `SSH_AUTH_SOCK` into the per-user session, so a LaunchAgent inherits the
58/// user's `ssh-agent` โ€” it was the minimal `PATH`, the same problem
59/// [ADR-0049](../docs/adrs/adr-0049.md) ยง3 solves for the `code` launcher and
60/// [`resolve_gh_binary`](crate::pr_status::resolve_gh_binary) solves for `gh`.
61///
62/// Callers should do this **once** and pass the result down, rather than
63/// re-reading the environment per subprocess.
64#[must_use]
65pub fn resolve_git_binary() -> PathBuf {
66    resolve_git_binary_from(std::env::var_os(GIT_BIN_ENV), GIT_BINARY_CANDIDATES)
67}
68
69/// The testable core of [`resolve_git_binary`]. Split so the probe order can be
70/// unit-tested without mutating the process environment (#1030).
71fn resolve_git_binary_from(
72    env_override: Option<std::ffi::OsString>,
73    candidates: &[&str],
74) -> PathBuf {
75    if let Some(path) = env_override.filter(|p| !p.is_empty()) {
76        return PathBuf::from(path);
77    }
78    for candidate in candidates {
79        let path = Path::new(candidate);
80        if path.exists() {
81            return path.to_path_buf();
82        }
83    }
84    PathBuf::from("git")
85}
86
87#[cfg(test)]
88#[allow(clippy::unwrap_used)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn resolve_git_binary_from_prefers_env_then_candidate_then_fallback() {
94        assert_eq!(
95            resolve_git_binary_from(Some("/custom/git".into()), &["/usr/bin/git"]),
96            PathBuf::from("/custom/git"),
97            "an explicit override wins over every candidate"
98        );
99        // A path guaranteed to exist on every platform the suite runs on.
100        let existing = std::env::current_exe().unwrap();
101        let existing = existing.to_str().unwrap();
102        assert_eq!(
103            resolve_git_binary_from(None, &["/no/such/git/xyzzy", existing]),
104            PathBuf::from(existing),
105            "the first *existing* candidate wins, not merely the first"
106        );
107        assert_eq!(
108            resolve_git_binary_from(None, &["/no/such/git/xyzzy"]),
109            PathBuf::from("git"),
110            "with nothing found, fall back to a bare PATH lookup"
111        );
112        assert_eq!(
113            resolve_git_binary_from(Some(String::new().into()), &["/no/such/git/xyzzy"]),
114            PathBuf::from("git"),
115            "an empty override is ignored rather than spawning \"\""
116        );
117    }
118
119    #[test]
120    fn resolve_git_binary_reads_the_real_environment() {
121        // Smoke: the public wrapper must not panic on whatever this machine has.
122        let _ = resolve_git_binary();
123    }
124}