Skip to main content

bcore_mutation/
git_changes.rs

1use crate::error::{MutationError, Result};
2use regex::Regex;
3use std::process::Command;
4use std::str;
5
6pub async fn run_git_command(args: &[&str]) -> Result<Vec<String>> {
7    let output = Command::new("git")
8        .args(args)
9        .output()
10        .map_err(|e| MutationError::Git(format!("Failed to execute git command: {}", e)))?;
11
12    if !output.status.success() {
13        let stderr = str::from_utf8(&output.stderr).unwrap_or("Unknown error");
14        return Err(MutationError::Git(format!(
15            "Git command failed: {}",
16            stderr
17        )));
18    }
19
20    let stdout = str::from_utf8(&output.stdout)
21        .map_err(|e| MutationError::Git(format!("Invalid UTF-8 in git output: {}", e)))?;
22
23    Ok(stdout.lines().map(|s| s.to_string()).collect())
24}
25
26pub async fn get_changed_files(pr_number: Option<u32>) -> Result<Vec<String>> {
27    let mut used_remote = "upstream"; // Track which remote we successfully used
28
29    if let Some(pr) = pr_number {
30        // Try to fetch the PR from upstream first
31        let fetch_upstream_args = &["fetch", "upstream", &format!("pull/{}/head:pr/{}", pr, pr)];
32        match run_git_command(fetch_upstream_args).await {
33            Ok(_) => {
34                println!("Successfully fetched from upstream");
35                println!("Checking out...");
36                let checkout_args = &["checkout", &format!("pr/{}", pr)];
37                run_git_command(checkout_args).await?;
38            }
39            Err(upstream_err) => {
40                println!("Failed to fetch from upstream: {:?}", upstream_err);
41                println!("Trying to fetch from origin...");
42
43                // Try to fetch from origin as fallback
44                let fetch_origin_args =
45                    &["fetch", "origin", &format!("pull/{}/head:pr/{}", pr, pr)];
46                match run_git_command(fetch_origin_args).await {
47                    Ok(_) => {
48                        println!("Successfully fetched from origin");
49                        used_remote = "origin";
50                        println!("Checking out...");
51                        let checkout_args = &["checkout", &format!("pr/{}", pr)];
52                        run_git_command(checkout_args).await?;
53                    }
54                    Err(origin_err) => {
55                        println!("Failed to fetch from origin: {:?}", origin_err);
56                        println!("Attempting to rebase existing pr/{} branch...", pr);
57                        let rebase_args = &["rebase", &format!("pr/{}", pr)];
58                        run_git_command(rebase_args).await?;
59                        // In rebase case, we don't know which remote was used originally
60                        // Try upstream first, fall back to origin if it fails
61                    }
62                }
63            }
64        }
65    }
66
67    // Try diff with the appropriate remote
68    let diff_args = &[
69        "diff",
70        "--name-only",
71        "--diff-filter=d",
72        &format!("{}/master...HEAD", used_remote),
73    ];
74    match run_git_command(diff_args).await {
75        Ok(result) => Ok(result),
76        Err(_) if used_remote == "upstream" => {
77            // If upstream diff failed, try origin
78            println!("Diff with upstream/master failed, trying origin/master...");
79            let diff_args_origin = &["diff", "--name-only", "origin/master...HEAD"];
80            run_git_command(diff_args_origin).await
81        }
82        Err(e) => Err(e),
83    }
84}
85
86pub async fn get_lines_touched(file_path: &str) -> Result<Vec<usize>> {
87    // Try upstream first
88    let diff_args_upstream = &[
89        "diff",
90        "--unified=0",
91        "upstream/master...HEAD",
92        "--",
93        file_path,
94    ];
95
96    let diff_output = match run_git_command(diff_args_upstream).await {
97        Ok(output) => output,
98        Err(_) => {
99            // Fall back to origin if upstream fails
100            println!("Diff with upstream/master failed, trying origin/master...");
101            let diff_args_origin = &[
102                "diff",
103                "--unified=0",
104                "origin/master...HEAD",
105                "--",
106                file_path,
107            ];
108            run_git_command(diff_args_origin).await?
109        }
110    };
111
112    let mut lines = Vec::new();
113    let line_range_regex = Regex::new(r"@@.*\+(\d+)(?:,(\d+))?.*@@")?;
114    for line in diff_output {
115        if line.starts_with("@@") {
116            if let Some(captures) = line_range_regex.captures(&line) {
117                let start_line: usize = captures[1]
118                    .parse()
119                    .map_err(|_| MutationError::Git("Invalid line number in diff".to_string()))?;
120                let num_lines = if let Some(count_match) = captures.get(2) {
121                    count_match
122                        .as_str()
123                        .parse::<usize>()
124                        .map_err(|_| MutationError::Git("Invalid line count in diff".to_string()))?
125                } else {
126                    1
127                };
128                lines.extend(start_line..start_line + num_lines);
129            }
130        }
131    }
132    Ok(lines)
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[tokio::test]
140    async fn test_get_lines_touched_parsing() {
141        // This would require a git repository setup, so we'll test the regex parsing logic
142        let line_range_regex = Regex::new(r"@@.*\+(\d+)(?:,(\d+))?.*@@").unwrap();
143
144        // Test single line change
145        let single_line = "@@ -10,0 +11 @@ some context";
146        if let Some(captures) = line_range_regex.captures(single_line) {
147            let start_line: usize = captures[1].parse().unwrap();
148            let num_lines = if let Some(count_match) = captures.get(2) {
149                count_match.as_str().parse::<usize>().unwrap()
150            } else {
151                1
152            };
153            assert_eq!(start_line, 11);
154            assert_eq!(num_lines, 1);
155        }
156
157        // Test multiple line change
158        let multi_line = "@@ -10,3 +11,5 @@ some context";
159        if let Some(captures) = line_range_regex.captures(multi_line) {
160            let start_line: usize = captures[1].parse().unwrap();
161            let num_lines = captures.get(2).unwrap().as_str().parse::<usize>().unwrap();
162            assert_eq!(start_line, 11);
163            assert_eq!(num_lines, 5);
164        }
165    }
166}