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 porcelain_records_in(root, &[])
242}
243
244fn porcelain_records_in(root: &Path, pathspecs: &[&str]) -> Result<Vec<(u8, u8, String)>> {
247 let mut command = Command::new("git");
248 if !pathspecs.is_empty() {
249 command.arg("--literal-pathspecs");
250 }
251 command.arg("-C").arg(root).args([
252 "status",
253 "--porcelain=v1",
254 "-z",
255 "--untracked-files=all",
256 "--no-renames",
257 "--ignored=no",
258 ]);
259 if !pathspecs.is_empty() {
260 command.arg("--").args(pathspecs);
261 }
262 let output = command.output().context("Failed to execute git status")?;
263
264 if !output.status.success() {
265 anyhow::bail!(
266 "git status failed: {}",
267 String::from_utf8_lossy(&output.stderr)
268 );
269 }
270
271 let mut records = Vec::new();
272 for record in output.stdout.split(|b| *b == 0) {
275 if record.len() < 4 {
276 continue;
277 }
278 let text = String::from_utf8_lossy(record);
279 let (status, path) = text.split_at(3);
280 let path = path.trim();
281 if path.is_empty() {
282 continue;
283 }
284 let mut bytes = status.bytes();
285 let x = bytes.next().unwrap_or(b' ');
286 let y = bytes.next().unwrap_or(b' ');
287 records.push((x, y, path.to_string()));
288 }
289 Ok(records)
290}
291
292pub fn changed_paths(root: impl AsRef<Path>) -> Result<HashSet<String>> {
298 Ok(porcelain_records(root.as_ref())?
299 .into_iter()
300 .map(|(_, _, p)| p)
301 .collect())
302}
303
304pub fn changed_paths_in(root: impl AsRef<Path>, pathspecs: &[&str]) -> Result<HashSet<String>> {
307 if pathspecs.is_empty() {
308 return Ok(HashSet::new());
309 }
310 Ok(porcelain_records_in(root.as_ref(), pathspecs)?
311 .into_iter()
312 .map(|(_, _, p)| p)
313 .collect())
314}
315
316pub fn head_commit_and_branch(root: impl AsRef<Path>) -> Result<(String, String)> {
319 let output = Command::new("git")
320 .arg("-C")
321 .arg(root.as_ref())
322 .args(["rev-parse", "HEAD", "--abbrev-ref", "HEAD"])
323 .output()
324 .context("Failed to execute git rev-parse")?;
325 if !output.status.success() {
326 anyhow::bail!(
327 "git rev-parse failed: {}",
328 String::from_utf8_lossy(&output.stderr)
329 );
330 }
331 let text = String::from_utf8(output.stdout).context("Invalid UTF-8 from git rev-parse")?;
332 let mut lines = text.lines().map(str::trim);
333 match (lines.next(), lines.next()) {
334 (Some(commit), Some(branch)) if !commit.is_empty() && !branch.is_empty() => {
335 Ok((commit.to_string(), branch.to_string()))
336 }
337 _ => anyhow::bail!("git rev-parse printed {:?}", text),
338 }
339}
340
341pub fn diff_names(root: impl AsRef<Path>, from: &str, to: &str) -> Result<Vec<String>> {
347 let output = Command::new("git")
348 .arg("-C")
349 .arg(root.as_ref())
350 .args(["diff", "--name-only", "-z", "--no-renames", from, to])
351 .output()
352 .context("Failed to execute git diff")?;
353 if !output.status.success() {
354 anyhow::bail!(
355 "git diff {}..{} failed: {}",
356 from,
357 to,
358 String::from_utf8_lossy(&output.stderr)
359 );
360 }
361 Ok(output
362 .stdout
363 .split(|b| *b == 0)
364 .filter(|p| !p.is_empty())
365 .map(|p| String::from_utf8_lossy(p).into_owned())
366 .collect())
367}
368
369pub fn get_worktree_changes<F>(root: impl AsRef<Path>, keep: F) -> Result<WorktreeChanges>
391where
392 F: Fn(&str) -> bool,
393{
394 let mut changes = WorktreeChanges::default();
395
396 for (x, y, path) in porcelain_records(root.as_ref())? {
397 if !keep(&path) {
398 continue;
399 }
400 if x == b'D' || y == b'D' {
403 changes.push_deleted(&path);
404 } else if x == b'?' || x == b'A' {
405 changes.push_added(&path);
406 } else {
407 changes.push_modified(&path);
408 }
409 }
410
411 Ok(changes)
412}
413
414pub fn is_ignored(root: impl AsRef<Path>, path: &str) -> Option<bool> {
419 let root = root.as_ref();
420 if !is_git_repo(root) || !is_git_available() {
421 return None;
422 }
423 let status = Command::new("git")
424 .arg("-C")
425 .arg(root)
426 .args(["check-ignore", "-q", "--", path])
427 .status()
428 .ok()?;
429 match status.code() {
430 Some(0) => Some(true),
431 Some(1) => Some(false),
432 _ => None,
433 }
434}
435
436pub fn get_git_state(root: impl AsRef<Path>) -> Result<GitState> {
441 let root = root.as_ref();
442
443 if !is_git_repo(root) {
444 anyhow::bail!("Not a git repository");
445 }
446
447 let branch = get_current_branch(root)?;
448 let commit = get_current_commit(root)?;
449 let dirty_paths = changed_paths(root)?;
450
451 Ok(GitState {
452 branch,
453 commit,
454 dirty: !dirty_paths.is_empty(),
455 dirty_paths,
456 })
457}
458
459pub fn get_git_state_optional(root: impl AsRef<Path>) -> Result<Option<GitState>> {
463 if !is_git_repo(&root) {
464 return Ok(None);
465 }
466
467 match get_git_state(root) {
468 Ok(state) => Ok(Some(state)),
469 Err(e) => {
470 log::warn!("Failed to get git state: {}", e);
471 Ok(None)
472 }
473 }
474}
475
476#[cfg(test)]
477mod tests {
478 use super::*;
479
480 #[test]
481 fn test_is_git_repo() {
482 assert!(is_git_repo("."));
484
485 assert!(!is_git_repo("/tmp"));
487 }
488
489 #[test]
490 fn test_get_current_branch() {
491 let branch = get_current_branch(".").unwrap();
493 assert!(!branch.is_empty());
494 log::info!("Current branch: {}", branch);
495 }
496
497 #[test]
498 fn test_get_current_commit() {
499 let commit = get_current_commit(".").unwrap();
501 assert_eq!(commit.len(), 40);
502 assert!(commit.chars().all(|c| c.is_ascii_hexdigit()));
503 log::info!("Current commit: {}", commit);
504 }
505
506 #[test]
507 fn test_has_uncommitted_changes() {
508 let has_changes = has_uncommitted_changes(".").unwrap();
510 log::info!("Has uncommitted changes: {}", has_changes);
511 }
512
513 #[test]
514 fn test_get_git_state() {
515 let state = get_git_state(".").unwrap();
516 assert!(!state.branch.is_empty());
517 assert_eq!(state.commit.len(), 40);
518 log::info!("Git state: {:?}", state);
519 }
520}