1use std::ffi::OsStr;
2use std::path::Path;
3use std::process::{Command, Output};
4
5fn run_git(root: &Path, args: &[&str]) -> Result<Output, String> {
6 Command::new("git")
7 .args(args)
8 .current_dir(root)
9 .env("GIT_TERMINAL_PROMPT", "0")
10 .output()
11 .map_err(|e| format!("failed to run git {}: {e}", args.join(" ")))
12}
13
14fn output_detail(out: &Output) -> String {
15 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
16 if !stderr.is_empty() {
17 return stderr;
18 }
19 let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
20 if !stdout.is_empty() {
21 return stdout;
22 }
23 format!("exit status {}", out.status)
24}
25
26fn validate_branch_name(branch: &str) -> Result<(), String> {
27 if branch.trim().is_empty() {
28 return Err("branch name must not be empty".to_string());
29 }
30 if branch != branch.trim()
31 || branch.starts_with('-')
32 || branch.starts_with('+')
33 || branch.contains(':')
34 {
35 return Err(format!("invalid branch name '{branch}'"));
36 }
37 Ok(())
38}
39
40pub fn origin_remote_url(root: &Path) -> Result<String, String> {
41 let out = run_git(root, &["remote", "get-url", "origin"])?;
42 if out.status.success() {
43 let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
44 if !url.is_empty() {
45 return Ok(url);
46 }
47 }
48 let detail = output_detail(&out);
49 if detail.to_ascii_lowercase().contains("not a git repository") {
50 return Err(format!("{}: not a git repository", root.display()));
51 }
52 Err(format!("repository has no 'origin' remote: {detail}"))
53}
54
55fn ensure_origin_remote(root: &Path) -> Result<(), String> {
56 origin_remote_url(root).map(|_| ())
57}
58
59pub fn default_branch(root: &Path) -> Result<String, String> {
60 default_branch_from_origin_head(root)
61}
62
63fn default_branch_from_origin_head(root: &Path) -> Result<String, String> {
64 let out = run_git(root, &["symbolic-ref", "refs/remotes/origin/HEAD"])?;
65 if !out.status.success() {
66 let detail = output_detail(&out);
67 return Err(format!(
68 "could not read default branch from origin/HEAD: {detail}"
69 ));
70 }
71 let full_ref = String::from_utf8_lossy(&out.stdout).trim().to_string();
72 match full_ref.strip_prefix("refs/remotes/origin/") {
73 Some(name) if !name.is_empty() => Ok(name.to_string()),
74 _ => Err(format!("origin/HEAD points to unexpected ref '{full_ref}'")),
75 }
76}
77
78fn ensure_local_branch(root: &Path, branch: &str) -> Result<(), String> {
79 let full_ref = format!("refs/heads/{branch}");
80 let out = run_git(root, &["show-ref", "--verify", "--quiet", &full_ref])?;
81 if out.status.success() {
82 return Ok(());
83 }
84 Err(format!("branch '{branch}' does not exist"))
85}
86
87pub fn branch_commit(root: &Path, branch: &str) -> Result<String, String> {
88 validate_branch_name(branch)?;
89 ensure_local_branch(root, branch)?;
90 let spec = format!("refs/heads/{branch}^{{commit}}");
91 let out = run_git(root, &["rev-parse", "--verify", &spec])?;
92 if !out.status.success() {
93 let detail = output_detail(&out);
94 return Err(format!("could not read commit for '{branch}': {detail}"));
95 }
96 let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
97 if sha.is_empty() {
98 return Err(format!("could not read commit for '{branch}'"));
99 }
100 Ok(sha)
101}
102
103pub fn verify_branch_commit(root: &Path, branch: &str, expected: &str) -> Result<(), String> {
104 let current = branch_commit(root, branch)?;
105 if current != expected {
106 return Err(format!(
107 "branch '{branch}' moved after approval (expected {expected}, now {current}); nothing was pushed"
108 ));
109 }
110 Ok(())
111}
112
113pub fn branch_commit_subjects(
114 root: &Path,
115 branch: &str,
116 base: &str,
117) -> Result<Vec<String>, String> {
118 validate_branch_name(branch)?;
119 validate_branch_name(base)?;
120 ensure_local_branch(root, branch)?;
121 let origin_base = format!("refs/remotes/origin/{base}");
122 let base_ref = if run_git(root, &["show-ref", "--verify", "--quiet", &origin_base])
123 .map(|o| o.status.success())
124 .unwrap_or(false)
125 {
126 origin_base
127 } else {
128 format!("refs/heads/{base}")
129 };
130 let range = format!("{base_ref}..refs/heads/{branch}");
131 let out = run_git(root, &["log", "--format=%s", &range])?;
132 if !out.status.success() {
133 let detail = output_detail(&out);
134 return Err(format!(
135 "could not list commits on '{branch}' not on '{base}': {detail}"
136 ));
137 }
138 let stdout = String::from_utf8_lossy(&out.stdout);
139 Ok(stdout
140 .lines()
141 .map(str::trim)
142 .filter(|line| !line.is_empty())
143 .map(String::from)
144 .collect())
145}
146
147fn is_gh_auth_error(out: &Output) -> bool {
148 if out.status.code() == Some(4) {
149 return true;
150 }
151 let combined = format!(
152 "{}\n{}",
153 String::from_utf8_lossy(&out.stderr),
154 String::from_utf8_lossy(&out.stdout)
155 )
156 .to_ascii_lowercase();
157 [
158 "gh auth login",
159 "not logged in",
160 "not logged into",
161 "not signed in",
162 "authentication",
163 "unauthorized",
164 "http 401",
165 ]
166 .iter()
167 .any(|needle| combined.contains(needle))
168}
169
170fn extract_pr_url(stdout: &str) -> Option<String> {
171 stdout
172 .lines()
173 .rev()
174 .map(str::trim)
175 .find(|line| line.starts_with("https://") || line.starts_with("http://"))
176 .map(String::from)
177}
178
179pub fn push_branch(root: &Path, branch: &str) -> Result<(), String> {
180 validate_branch_name(branch)?;
181 ensure_origin_remote(root)?;
182 let default_branch = default_branch_from_origin_head(root)?;
183 if branch == default_branch {
184 return Err(format!(
185 "refusing to push default branch '{default_branch}'"
186 ));
187 }
188 ensure_local_branch(root, branch)?;
189
190 let out = run_git(root, &["push", "-u", "origin", branch])?;
191 if !out.status.success() {
192 let detail = output_detail(&out);
193 return Err(format!("git push -u origin {branch} failed: {detail}"));
194 }
195 Ok(())
196}
197
198pub fn open_pull_request(
199 root: &Path,
200 branch: &str,
201 title: &str,
202 body: &str,
203) -> Result<String, String> {
204 open_pull_request_with_gh(root, branch, title, body, OsStr::new("gh"))
205}
206
207pub fn open_pull_request_with_gh(
208 root: &Path,
209 branch: &str,
210 title: &str,
211 body: &str,
212 gh_bin: &OsStr,
213) -> Result<String, String> {
214 let title = title.trim();
215 if title.is_empty() {
216 return Err("pull request title must not be empty".to_string());
217 }
218 validate_branch_name(branch)?;
219 ensure_origin_remote(root)?;
220 let default_branch = default_branch_from_origin_head(root)?;
221 if branch == default_branch {
222 return Err(format!(
223 "refusing to open a pull request from default branch '{default_branch}'"
224 ));
225 }
226 ensure_local_branch(root, branch)?;
227
228 let out = Command::new(gh_bin)
229 .args([
230 "pr",
231 "create",
232 "--base",
233 &default_branch,
234 "--head",
235 branch,
236 "--title",
237 title,
238 "--body",
239 body,
240 ])
241 .current_dir(root)
242 .env("GH_PROMPT_DISABLED", "1")
243 .output()
244 .map_err(|e| {
245 if e.kind() == std::io::ErrorKind::NotFound {
246 "gh CLI is not installed or not found on PATH".to_string()
247 } else {
248 format!("failed to run gh pr create: {e}")
249 }
250 })?;
251
252 if !out.status.success() {
253 let detail = output_detail(&out);
254 if is_gh_auth_error(&out) {
255 return Err(format!(
256 "gh is not signed in (run `gh auth login`): {detail}"
257 ));
258 }
259 return Err(format!("gh pr create failed: {detail}"));
260 }
261
262 let stdout = String::from_utf8_lossy(&out.stdout);
263 extract_pr_url(&stdout).ok_or_else(|| {
264 let trimmed = stdout.trim();
265 if trimmed.is_empty() {
266 "gh pr create succeeded but returned no pull request URL".to_string()
267 } else {
268 format!("gh pr create did not return a pull request URL: {trimmed}")
269 }
270 })
271}