Skip to main content

orch/engine/git/
diff.rs

1use crate::sys::cmd::CommandErrorContext;
2use std::collections::BTreeMap;
3use std::path::Path;
4use tokio::process::Command;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct DiffHunk {
8    pub old_start: u32,
9    pub old_count: u32,
10    pub new_start: u32,
11    pub new_count: u32,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct FileDiffSummary {
16    pub path: String,
17    pub hunks: Vec<DiffHunk>,
18}
19
20pub fn parse_unified_diff_hunks(diff: &str) -> Vec<FileDiffSummary> {
21    let mut by_file: BTreeMap<String, Vec<DiffHunk>> = BTreeMap::new();
22    let mut current_file: Option<String> = None;
23
24    for line in diff.lines() {
25        if let Some(path) = line.strip_prefix("+++ b/") {
26            current_file = Some(path.to_string());
27            by_file.entry(path.to_string()).or_default();
28            continue;
29        }
30
31        if let Some(rest) = line.strip_prefix("@@ -") {
32            let Some(file) = current_file.as_ref() else {
33                continue;
34            };
35            if let Some(hunk) = parse_hunk_header(rest) {
36                by_file.entry(file.clone()).or_default().push(hunk);
37            }
38        }
39    }
40
41    by_file
42        .into_iter()
43        .map(|(path, hunks)| FileDiffSummary { path, hunks })
44        .collect()
45}
46
47fn parse_hunk_header(rest: &str) -> Option<DiffHunk> {
48    let (old_part, remainder) = rest.split_once(" +")?;
49    let (new_part, _) = remainder.split_once(" @@")?;
50
51    let (old_start, old_count) = parse_range(old_part)?;
52    let (new_start, new_count) = parse_range(new_part)?;
53
54    Some(DiffHunk {
55        old_start,
56        old_count,
57        new_start,
58        new_count,
59    })
60}
61
62fn parse_range(part: &str) -> Option<(u32, u32)> {
63    if let Some((start, count)) = part.split_once(',') {
64        Some((start.parse().ok()?, count.parse().ok()?))
65    } else {
66        Some((part.parse().ok()?, 1))
67    }
68}
69
70/// Check if the current branch has any commits ahead of the default branch.
71pub async fn has_commits_ahead(dir: &Path, default_branch: &str) -> bool {
72    let output = Command::new("git")
73        .args([
74            "rev-list",
75            "--count",
76            &format!("origin/{default_branch}..HEAD"),
77        ])
78        .current_dir(dir)
79        .output()
80        .await;
81    match output {
82        Ok(o) if o.status.success() => {
83            let count: u32 = String::from_utf8_lossy(&o.stdout)
84                .trim()
85                .parse()
86                .unwrap_or(0);
87            count > 0
88        }
89        _ => {
90            tracing::debug!(
91                default_branch,
92                "git rev-list failed for compare ref, assuming commits ahead"
93            );
94            // If we can't determine, assume there ARE commits ahead so we
95            // attempt a push (better to try and fail loudly than silently
96            // skip push and lose the PR creation path).
97            true
98        }
99    }
100}
101
102/// Count the number of changed files in the working directory.
103pub async fn count_changed_files(dir: &Path) -> anyhow::Result<usize> {
104    // Count modified and new files (excluding deleted)
105    let output = Command::new("git")
106        .args(["status", "--porcelain"])
107        .current_dir(dir)
108        .output_with_context()
109        .await?;
110
111    let status_output = String::from_utf8_lossy(&output.stdout);
112    let count = status_output
113        .lines()
114        .filter(|line| {
115            let prefix = line.get(0..2).unwrap_or("");
116            // Count modified (M), added (A), renamed (R), copied (C), untracked (??)
117            prefix.starts_with('M')
118                || prefix.starts_with('A')
119                || prefix.starts_with('R')
120                || prefix.starts_with('C')
121                || prefix.starts_with('?')
122        })
123        .count();
124
125    Ok(count)
126}
127
128#[cfg(test)]
129mod tests {
130    use super::parse_unified_diff_hunks;
131
132    #[test]
133    fn parses_multi_file_hunks() {
134        let diff = r"diff --git a/src/a.rs b/src/a.rs
135index 1111111..2222222 100644
136--- a/src/a.rs
137+++ b/src/a.rs
138@@ -1,1 +1,2 @@
139+line
140@@ -10,2 +11,3 @@
141-line
142+line
143+line2
144diff --git a/src/b.rs b/src/b.rs
145index 3333333..4444444 100644
146--- a/src/b.rs
147+++ b/src/b.rs
148@@ -5 +5 @@
149-old
150+new
151";
152
153        let files = parse_unified_diff_hunks(diff);
154        assert_eq!(files.len(), 2);
155        assert_eq!(files[0].path, "src/a.rs");
156        assert_eq!(files[0].hunks.len(), 2);
157        assert_eq!(files[1].path, "src/b.rs");
158        assert_eq!(files[1].hunks.len(), 1);
159    }
160}