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