1use anyhow::{Context, Result};
8use std::collections::HashSet;
9use std::path::Path;
10use std::process::Command;
11use std::sync::OnceLock;
12
13#[derive(Debug, Clone)]
15pub struct GitState {
16 pub branch: String,
18 pub commit: String,
20 pub dirty: bool,
22 pub dirty_paths: HashSet<String>,
25}
26
27pub fn is_git_repo(root: impl AsRef<Path>) -> bool {
29 root.as_ref().join(".git").exists()
30}
31
32pub fn is_git_available() -> bool {
39 static AVAILABLE: OnceLock<bool> = OnceLock::new();
40 *AVAILABLE.get_or_init(|| match Command::new("git").arg("--version").output() {
41 Ok(_) => true,
42 Err(e) => e.kind() != std::io::ErrorKind::NotFound,
43 })
44}
45
46pub fn get_current_branch(root: impl AsRef<Path>) -> Result<String> {
50 let output = Command::new("git")
51 .arg("-C")
52 .arg(root.as_ref())
53 .args(["rev-parse", "--abbrev-ref", "HEAD"])
54 .output()
55 .context("Failed to execute git rev-parse")?;
56
57 if !output.status.success() {
58 anyhow::bail!(
59 "git rev-parse failed: {}",
60 String::from_utf8_lossy(&output.stderr)
61 );
62 }
63
64 let branch = String::from_utf8(output.stdout)
65 .context("Invalid UTF-8 in branch name")?
66 .trim()
67 .to_string();
68
69 Ok(branch)
70}
71
72pub fn read_head_branch(root: impl AsRef<Path>) -> Option<String> {
81 let mut git_dir = root.as_ref().join(".git");
82 if git_dir.is_file() {
83 let text = std::fs::read_to_string(&git_dir).ok()?;
84 let target = text.strip_prefix("gitdir:")?.trim();
85 let target = Path::new(target);
86 git_dir = if target.is_absolute() {
87 target.to_path_buf()
88 } else {
89 root.as_ref().join(target)
90 };
91 }
92 let head = std::fs::read_to_string(git_dir.join("HEAD")).ok()?;
93 let head = head.trim();
94 if let Some(reference) = head.strip_prefix("ref:") {
95 let reference = reference.trim();
96 let name = reference.strip_prefix("refs/heads/").unwrap_or(reference);
97 return Some(name.to_string());
98 }
99 if !head.is_empty() && head.bytes().all(|b| b.is_ascii_hexdigit()) {
100 return Some("HEAD".to_string());
101 }
102 None
103}
104
105pub fn get_current_commit(root: impl AsRef<Path>) -> Result<String> {
109 let output = Command::new("git")
110 .arg("-C")
111 .arg(root.as_ref())
112 .args(["rev-parse", "HEAD"])
113 .output()
114 .context("Failed to execute git rev-parse HEAD")?;
115
116 if !output.status.success() {
117 anyhow::bail!(
118 "git rev-parse HEAD failed: {}",
119 String::from_utf8_lossy(&output.stderr)
120 );
121 }
122
123 let commit = String::from_utf8(output.stdout)
124 .context("Invalid UTF-8 in commit SHA")?
125 .trim()
126 .to_string();
127
128 Ok(commit)
129}
130
131pub fn has_uncommitted_changes(root: impl AsRef<Path>) -> Result<bool> {
136 let output = Command::new("git")
137 .arg("-C")
138 .arg(root.as_ref())
139 .args(["status", "--porcelain"])
140 .output()
141 .context("Failed to execute git status")?;
142
143 if !output.status.success() {
144 anyhow::bail!(
145 "git status failed: {}",
146 String::from_utf8_lossy(&output.stderr)
147 );
148 }
149
150 let has_changes = !output.stdout.is_empty();
153
154 Ok(has_changes)
155}
156
157#[derive(Debug, Clone, Default, PartialEq, Eq)]
163pub struct WorktreeChanges {
164 pub modified: Vec<String>,
166 pub added: Vec<String>,
168 pub deleted: Vec<String>,
170 pub modified_count: usize,
171 pub added_count: usize,
172 pub deleted_count: usize,
173 pub truncated: bool,
175}
176
177impl WorktreeChanges {
178 pub fn is_empty(&self) -> bool {
180 self.modified_count == 0 && self.added_count == 0 && self.deleted_count == 0
181 }
182
183 pub fn total(&self) -> usize {
185 self.modified_count + self.added_count + self.deleted_count
186 }
187
188 pub fn any<F: Fn(&str) -> bool>(&self, pred: F) -> bool {
190 self.modified
191 .iter()
192 .chain(&self.added)
193 .chain(&self.deleted)
194 .any(|p| pred(p))
195 }
196}
197
198pub const MAX_REPORTED_PATHS: usize = 100;
200
201impl WorktreeChanges {
202 pub fn push_modified(&mut self, path: &str) {
204 self.modified_count += 1;
205 if self.modified.len() < MAX_REPORTED_PATHS {
206 self.modified.push(path.to_string());
207 } else {
208 self.truncated = true;
209 }
210 }
211
212 pub fn push_added(&mut self, path: &str) {
213 self.added_count += 1;
214 if self.added.len() < MAX_REPORTED_PATHS {
215 self.added.push(path.to_string());
216 } else {
217 self.truncated = true;
218 }
219 }
220
221 pub fn push_deleted(&mut self, path: &str) {
222 self.deleted_count += 1;
223 if self.deleted.len() < MAX_REPORTED_PATHS {
224 self.deleted.push(path.to_string());
225 } else {
226 self.truncated = true;
227 }
228 }
229
230 pub fn sort(&mut self) {
233 self.modified.sort();
234 self.added.sort();
235 self.deleted.sort();
236 }
237}
238
239fn porcelain_records(root: &Path) -> Result<Vec<(u8, u8, String)>> {
241 let output = Command::new("git")
242 .arg("-C")
243 .arg(root)
244 .args([
245 "status",
246 "--porcelain=v1",
247 "-z",
248 "--untracked-files=all",
249 "--no-renames",
250 "--ignored=no",
251 ])
252 .output()
253 .context("Failed to execute git status")?;
254
255 if !output.status.success() {
256 anyhow::bail!(
257 "git status failed: {}",
258 String::from_utf8_lossy(&output.stderr)
259 );
260 }
261
262 let mut records = Vec::new();
263 for record in output.stdout.split(|b| *b == 0) {
266 if record.len() < 4 {
267 continue;
268 }
269 let text = String::from_utf8_lossy(record);
270 let (status, path) = text.split_at(3);
271 let path = path.trim();
272 if path.is_empty() {
273 continue;
274 }
275 let mut bytes = status.bytes();
276 let x = bytes.next().unwrap_or(b' ');
277 let y = bytes.next().unwrap_or(b' ');
278 records.push((x, y, path.to_string()));
279 }
280 Ok(records)
281}
282
283pub fn changed_paths(root: impl AsRef<Path>) -> Result<HashSet<String>> {
289 Ok(porcelain_records(root.as_ref())?
290 .into_iter()
291 .map(|(_, _, p)| p)
292 .collect())
293}
294
295pub fn diff_names(root: impl AsRef<Path>, from: &str, to: &str) -> Result<Vec<String>> {
301 let output = Command::new("git")
302 .arg("-C")
303 .arg(root.as_ref())
304 .args(["diff", "--name-only", "-z", "--no-renames", from, to])
305 .output()
306 .context("Failed to execute git diff")?;
307 if !output.status.success() {
308 anyhow::bail!(
309 "git diff {}..{} failed: {}",
310 from,
311 to,
312 String::from_utf8_lossy(&output.stderr)
313 );
314 }
315 Ok(output
316 .stdout
317 .split(|b| *b == 0)
318 .filter(|p| !p.is_empty())
319 .map(|p| String::from_utf8_lossy(p).into_owned())
320 .collect())
321}
322
323pub fn get_worktree_changes<F>(root: impl AsRef<Path>, keep: F) -> Result<WorktreeChanges>
345where
346 F: Fn(&str) -> bool,
347{
348 let mut changes = WorktreeChanges::default();
349
350 for (x, y, path) in porcelain_records(root.as_ref())? {
351 if !keep(&path) {
352 continue;
353 }
354 if x == b'D' || y == b'D' {
357 changes.push_deleted(&path);
358 } else if x == b'?' || x == b'A' {
359 changes.push_added(&path);
360 } else {
361 changes.push_modified(&path);
362 }
363 }
364
365 Ok(changes)
366}
367
368pub fn is_ignored(root: impl AsRef<Path>, path: &str) -> Option<bool> {
373 let root = root.as_ref();
374 if !is_git_repo(root) || !is_git_available() {
375 return None;
376 }
377 let status = Command::new("git")
378 .arg("-C")
379 .arg(root)
380 .args(["check-ignore", "-q", "--", path])
381 .status()
382 .ok()?;
383 match status.code() {
384 Some(0) => Some(true),
385 Some(1) => Some(false),
386 _ => None,
387 }
388}
389
390pub fn get_git_state(root: impl AsRef<Path>) -> Result<GitState> {
395 let root = root.as_ref();
396
397 if !is_git_repo(root) {
398 anyhow::bail!("Not a git repository");
399 }
400
401 let branch = get_current_branch(root)?;
402 let commit = get_current_commit(root)?;
403 let dirty_paths = changed_paths(root)?;
404
405 Ok(GitState {
406 branch,
407 commit,
408 dirty: !dirty_paths.is_empty(),
409 dirty_paths,
410 })
411}
412
413pub fn get_git_state_optional(root: impl AsRef<Path>) -> Result<Option<GitState>> {
417 if !is_git_repo(&root) {
418 return Ok(None);
419 }
420
421 match get_git_state(root) {
422 Ok(state) => Ok(Some(state)),
423 Err(e) => {
424 log::warn!("Failed to get git state: {}", e);
425 Ok(None)
426 }
427 }
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433
434 #[test]
435 fn test_is_git_repo() {
436 assert!(is_git_repo("."));
438
439 assert!(!is_git_repo("/tmp"));
441 }
442
443 #[test]
444 fn test_get_current_branch() {
445 let branch = get_current_branch(".").unwrap();
447 assert!(!branch.is_empty());
448 log::info!("Current branch: {}", branch);
449 }
450
451 #[test]
452 fn test_get_current_commit() {
453 let commit = get_current_commit(".").unwrap();
455 assert_eq!(commit.len(), 40);
456 assert!(commit.chars().all(|c| c.is_ascii_hexdigit()));
457 log::info!("Current commit: {}", commit);
458 }
459
460 #[test]
461 fn test_has_uncommitted_changes() {
462 let has_changes = has_uncommitted_changes(".").unwrap();
464 log::info!("Has uncommitted changes: {}", has_changes);
465 }
466
467 #[test]
468 fn test_get_git_state() {
469 let state = get_git_state(".").unwrap();
470 assert!(!state.branch.is_empty());
471 assert_eq!(state.commit.len(), 40);
472 log::info!("Git state: {:?}", state);
473 }
474}