1use 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}
22
23impl RepoInfo {
24 fn placeholder(path: &Path) -> Self {
25 RepoInfo {
26 name: path
27 .file_name()
28 .and_then(|n| n.to_str())
29 .unwrap_or("")
30 .to_string(),
31 path: path.to_string_lossy().to_string(),
32 branch: "-".into(),
33 sha: "-".into(),
34 ahead: 0,
35 behind: 0,
36 dirty: 0,
37 org: "-".into(),
38 }
39 }
40}
41
42pub fn gather_infos(paths: &[PathBuf]) -> Vec<RepoInfo> {
43 paths.par_iter().map(|p| get_repo_info(p)).collect()
44}
45
46pub fn get_repo_info(path: &Path) -> RepoInfo {
47 let mut info = RepoInfo::placeholder(path);
48
49 if let Ok(output) = Command::new("git")
50 .arg("-C")
51 .arg(path)
52 .args(["status", "--porcelain=v2", "--branch"])
53 .output()
54 {
55 if let Ok(stdout) = String::from_utf8(output.stdout) {
56 parse_status(&stdout, &mut info);
57 }
58 }
59
60 if let Ok(output) = Command::new("git")
61 .arg("-C")
62 .arg(path)
63 .args(["remote", "get-url", "origin"])
64 .output()
65 {
66 if let Ok(stdout) = String::from_utf8(output.stdout) {
67 info.org = parse_org(stdout.trim());
68 }
69 }
70 info
71}
72
73pub(crate) fn parse_status(stdout: &str, info: &mut RepoInfo) {
74 for line in stdout.lines() {
75 if let Some(rest) = line.strip_prefix("# branch.oid ") {
76 if rest != "(initial)" {
77 info.sha = rest.chars().take(7).collect();
78 }
79 } else if let Some(rest) = line.strip_prefix("# branch.head ") {
80 info.branch = rest.to_string();
81 } else if let Some(rest) = line.strip_prefix("# branch.ab ") {
82 for p in rest.split_whitespace() {
83 if let Some(n) = p.strip_prefix('+') {
84 info.ahead = n.parse().unwrap_or(0);
85 } else if let Some(n) = p.strip_prefix('-') {
86 info.behind = n.parse().unwrap_or(0);
87 }
88 }
89 } else if line.starts_with(['1', '2', 'u', '?']) {
90 info.dirty += 1;
91 }
92 }
93}
94
95pub fn parse_org(url: &str) -> String {
98 if url.is_empty() {
99 return "-".into();
100 }
101 let mut u = url.trim_end_matches('/').to_string();
102 if let Some(stripped) = u.strip_suffix(".git") {
103 u = stripped.to_string();
104 }
105
106 let path_part: String = if let Some(scheme_idx) = u.find("://") {
107 let after = &u[scheme_idx + 3..];
108 match after.find('/') {
109 Some(i) => after[i + 1..].to_string(),
110 None => after.to_string(),
111 }
112 } else if let Some(colon_idx) = u.find(':') {
113 u[colon_idx + 1..].to_string()
114 } else {
115 u.clone()
116 };
117
118 let parts: Vec<&str> = path_part.split('/').filter(|s| !s.is_empty()).collect();
119 if parts.len() >= 2 {
120 parts[parts.len() - 2].to_string()
121 } else {
122 "-".into()
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn parse_org_ssh_form() {
132 assert_eq!(parse_org("git@github.com:acme/foo.git"), "acme");
133 }
134
135 #[test]
136 fn parse_org_https_form() {
137 assert_eq!(parse_org("https://github.com/acme/foo.git"), "acme");
138 }
139
140 #[test]
141 fn parse_org_ssh_url_form() {
142 assert_eq!(parse_org("ssh://git@github.com/acme/foo"), "acme");
143 }
144
145 #[test]
146 fn parse_org_trailing_slash() {
147 assert_eq!(parse_org("https://gitlab.com/acme/foo/"), "acme");
148 }
149
150 #[test]
151 fn parse_org_missing_returns_dash() {
152 assert_eq!(parse_org(""), "-");
153 assert_eq!(parse_org("nonsense"), "-");
154 }
155
156 #[test]
157 fn parse_status_full_output() {
158 let s = "# branch.oid 1234567890abcdef\n\
159 # branch.head main\n\
160 # branch.ab +2 -1\n\
161 1 .M N... 100644 100644 100644 abc def foo\n\
162 ? untracked\n";
163 let mut info = RepoInfo::placeholder(std::path::Path::new("/tmp/x"));
164 parse_status(s, &mut info);
165 assert_eq!(info.branch, "main");
166 assert_eq!(info.sha, "1234567");
167 assert_eq!(info.ahead, 2);
168 assert_eq!(info.behind, 1);
169 assert_eq!(info.dirty, 2);
170 }
171
172 #[test]
173 fn parse_status_initial_commit() {
174 let s = "# branch.oid (initial)\n# branch.head main\n";
175 let mut info = RepoInfo::placeholder(std::path::Path::new("/tmp/x"));
176 parse_status(s, &mut info);
177 assert_eq!(info.sha, "-");
178 assert_eq!(info.branch, "main");
179 }
180}