Skip to main content

git_nav/
git.rs

1//! Repo metadata gathered by shelling out to `git`. Every repo's info is
2//! collected on its own rayon thread — this is where the "slow first start"
3//! win comes from: N sequential `git status` calls become max(N, #cores).
4
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use rayon::prelude::*;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct RepoInfo {
13    pub name: String,
14    pub path: String,
15    pub branch: String,
16    pub sha: String,
17    pub ahead: u32,
18    pub behind: u32,
19    pub dirty: u32,
20    pub org: String,
21    pub author: String,
22}
23
24impl RepoInfo {
25    fn placeholder(path: &Path) -> Self {
26        RepoInfo {
27            name: path
28                .file_name()
29                .and_then(|n| n.to_str())
30                .unwrap_or("")
31                .to_string(),
32            path: path.to_string_lossy().to_string(),
33            branch: "-".into(),
34            sha: "-".into(),
35            ahead: 0,
36            behind: 0,
37            dirty: 0,
38            org: "-".into(),
39            author: "-".into(),
40        }
41    }
42}
43
44pub fn gather_infos(paths: &[PathBuf]) -> Vec<RepoInfo> {
45    paths.par_iter().map(|p| get_repo_info(p)).collect()
46}
47
48pub fn get_repo_info(path: &Path) -> RepoInfo {
49    let mut info = RepoInfo::placeholder(path);
50
51    if let Ok(output) = Command::new("git")
52        .arg("-C")
53        .arg(path)
54        .args(["status", "--porcelain=v2", "--branch"])
55        .output()
56    {
57        if let Ok(stdout) = String::from_utf8(output.stdout) {
58            parse_status(&stdout, &mut info);
59        }
60    }
61
62    if let Ok(output) = Command::new("git")
63        .arg("-C")
64        .arg(path)
65        .args(["remote", "get-url", "origin"])
66        .output()
67    {
68        if let Ok(stdout) = String::from_utf8(output.stdout) {
69            info.org = parse_org(stdout.trim());
70        }
71    }
72
73    if let Ok(output) = Command::new("git")
74        .arg("-C")
75        .arg(path)
76        .args(["log", "-1", "--format=%an"])
77        .output()
78    {
79        if let Ok(stdout) = String::from_utf8(output.stdout) {
80            let author = stdout.trim();
81            if !author.is_empty() {
82                info.author = author.to_string();
83            }
84        }
85    }
86
87    info
88}
89
90pub(crate) fn parse_status(stdout: &str, info: &mut RepoInfo) {
91    for line in stdout.lines() {
92        if let Some(rest) = line.strip_prefix("# branch.oid ") {
93            if rest != "(initial)" {
94                info.sha = rest.chars().take(7).collect();
95            }
96        } else if let Some(rest) = line.strip_prefix("# branch.head ") {
97            info.branch = rest.to_string();
98        } else if let Some(rest) = line.strip_prefix("# branch.ab ") {
99            for p in rest.split_whitespace() {
100                if let Some(n) = p.strip_prefix('+') {
101                    info.ahead = n.parse().unwrap_or(0);
102                } else if let Some(n) = p.strip_prefix('-') {
103                    info.behind = n.parse().unwrap_or(0);
104                }
105            }
106        } else if line.starts_with(['1', '2', 'u', '?']) {
107            info.dirty += 1;
108        }
109    }
110}
111
112/// Extract the org/owner segment from a git remote URL. Handles ssh
113/// (`git@host:org/repo.git`) and URL (`https://host/org/repo.git`) forms.
114pub fn parse_org(url: &str) -> String {
115    if url.is_empty() {
116        return "-".into();
117    }
118    let mut u = url.trim_end_matches('/').to_string();
119    if let Some(stripped) = u.strip_suffix(".git") {
120        u = stripped.to_string();
121    }
122
123    let path_part: String = if let Some(scheme_idx) = u.find("://") {
124        let after = &u[scheme_idx + 3..];
125        match after.find('/') {
126            Some(i) => after[i + 1..].to_string(),
127            None => after.to_string(),
128        }
129    } else if let Some(colon_idx) = u.find(':') {
130        u[colon_idx + 1..].to_string()
131    } else {
132        u.clone()
133    };
134
135    let parts: Vec<&str> = path_part.split('/').filter(|s| !s.is_empty()).collect();
136    if parts.len() >= 2 {
137        parts[parts.len() - 2].to_string()
138    } else {
139        "-".into()
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn parse_org_ssh_form() {
149        assert_eq!(parse_org("git@github.com:acme/foo.git"), "acme");
150    }
151
152    #[test]
153    fn parse_org_https_form() {
154        assert_eq!(parse_org("https://github.com/acme/foo.git"), "acme");
155    }
156
157    #[test]
158    fn parse_org_ssh_url_form() {
159        assert_eq!(parse_org("ssh://git@github.com/acme/foo"), "acme");
160    }
161
162    #[test]
163    fn parse_org_trailing_slash() {
164        assert_eq!(parse_org("https://gitlab.com/acme/foo/"), "acme");
165    }
166
167    #[test]
168    fn parse_org_missing_returns_dash() {
169        assert_eq!(parse_org(""), "-");
170        assert_eq!(parse_org("nonsense"), "-");
171    }
172
173    #[test]
174    fn parse_status_full_output() {
175        let s = "# branch.oid 1234567890abcdef\n\
176                 # branch.head main\n\
177                 # branch.ab +2 -1\n\
178                 1 .M N... 100644 100644 100644 abc def foo\n\
179                 ? untracked\n";
180        let mut info = RepoInfo::placeholder(std::path::Path::new("/tmp/x"));
181        parse_status(s, &mut info);
182        assert_eq!(info.branch, "main");
183        assert_eq!(info.sha, "1234567");
184        assert_eq!(info.ahead, 2);
185        assert_eq!(info.behind, 1);
186        assert_eq!(info.dirty, 2);
187    }
188
189    #[test]
190    fn parse_status_initial_commit() {
191        let s = "# branch.oid (initial)\n# branch.head main\n";
192        let mut info = RepoInfo::placeholder(std::path::Path::new("/tmp/x"));
193        parse_status(s, &mut info);
194        assert_eq!(info.sha, "-");
195        assert_eq!(info.branch, "main");
196    }
197
198    fn run_git(path: &std::path::Path, args: &[&str]) {
199        let ok = std::process::Command::new("git")
200            .arg("-C")
201            .arg(path)
202            .args(args)
203            .status()
204            .expect("git invoke")
205            .success();
206        assert!(ok, "git {args:?} failed in {path:?}");
207    }
208
209    #[test]
210    fn get_repo_info_populates_author() {
211        let tmp = tempfile::tempdir().unwrap();
212        let path = tmp.path();
213        run_git(path, &["init", "-q"]);
214        run_git(path, &["config", "user.email", "test@example.com"]);
215        run_git(path, &["config", "user.name", "Test Author"]);
216        std::fs::write(path.join("f"), "hi").unwrap();
217        run_git(path, &["add", "."]);
218        run_git(path, &["commit", "-q", "-m", "init"]);
219
220        let info = get_repo_info(path);
221        assert_eq!(info.author, "Test Author");
222    }
223}