bcore_mutation/
git_changes.rs1use 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"; if let Some(pr) = pr_number {
30 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 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 }
62 }
63 }
64 }
65 }
66
67 let diff_args = &[
69 "diff",
70 "--name-only",
71 &format!("{}/master...HEAD", used_remote),
72 ];
73 match run_git_command(diff_args).await {
74 Ok(result) => Ok(result),
75 Err(_) if used_remote == "upstream" => {
76 println!("Diff with upstream/master failed, trying origin/master...");
78 let diff_args_origin = &["diff", "--name-only", "origin/master...HEAD"];
79 run_git_command(diff_args_origin).await
80 }
81 Err(e) => Err(e),
82 }
83}
84
85pub async fn get_lines_touched(file_path: &str) -> Result<Vec<usize>> {
86 let diff_args_upstream = &[
88 "diff",
89 "--unified=0",
90 "upstream/master...HEAD",
91 "--",
92 file_path,
93 ];
94
95 let diff_output = match run_git_command(diff_args_upstream).await {
96 Ok(output) => output,
97 Err(_) => {
98 println!("Diff with upstream/master failed, trying origin/master...");
100 let diff_args_origin = &[
101 "diff",
102 "--unified=0",
103 "origin/master...HEAD",
104 "--",
105 file_path,
106 ];
107 run_git_command(diff_args_origin).await?
108 }
109 };
110
111 let mut lines = Vec::new();
112 let line_range_regex = Regex::new(r"@@.*\+(\d+)(?:,(\d+))?.*@@")?;
113 for line in diff_output {
114 if line.starts_with("@@") {
115 if let Some(captures) = line_range_regex.captures(&line) {
116 let start_line: usize = captures[1]
117 .parse()
118 .map_err(|_| MutationError::Git("Invalid line number in diff".to_string()))?;
119 let num_lines = if let Some(count_match) = captures.get(2) {
120 count_match
121 .as_str()
122 .parse::<usize>()
123 .map_err(|_| MutationError::Git("Invalid line count in diff".to_string()))?
124 } else {
125 1
126 };
127 lines.extend(start_line..start_line + num_lines);
128 }
129 }
130 }
131 Ok(lines)
132}
133
134#[cfg(test)]
135mod tests {
136 use super::*;
137
138 #[tokio::test]
139 async fn test_get_lines_touched_parsing() {
140 let line_range_regex = Regex::new(r"@@.*\+(\d+)(?:,(\d+))?.*@@").unwrap();
142
143 let single_line = "@@ -10,0 +11 @@ some context";
145 if let Some(captures) = line_range_regex.captures(single_line) {
146 let start_line: usize = captures[1].parse().unwrap();
147 let num_lines = if let Some(count_match) = captures.get(2) {
148 count_match.as_str().parse::<usize>().unwrap()
149 } else {
150 1
151 };
152 assert_eq!(start_line, 11);
153 assert_eq!(num_lines, 1);
154 }
155
156 let multi_line = "@@ -10,3 +11,5 @@ some context";
158 if let Some(captures) = line_range_regex.captures(multi_line) {
159 let start_line: usize = captures[1].parse().unwrap();
160 let num_lines = captures.get(2).unwrap().as_str().parse::<usize>().unwrap();
161 assert_eq!(start_line, 11);
162 assert_eq!(num_lines, 5);
163 }
164 }
165}