1use std::ffi::OsStr;
2use std::path::Path;
3use std::process::{Command, Output};
4
5pub(crate) fn 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
14pub(crate) fn 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
147pub(crate) fn 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
170pub(crate) fn run_gh(
171 root: &Path,
172 gh_bin: &OsStr,
173 args: &[&str],
174 label: &str,
175) -> Result<Output, String> {
176 let out = Command::new(gh_bin)
177 .args(args)
178 .current_dir(root)
179 .env("GH_PROMPT_DISABLED", "1")
180 .output()
181 .map_err(|e| {
182 if e.kind() == std::io::ErrorKind::NotFound {
183 "gh CLI is not installed or not found on PATH".to_string()
184 } else {
185 format!("failed to run {label}: {e}")
186 }
187 })?;
188
189 if !out.status.success() {
190 let detail = output_detail(&out);
191 if is_gh_auth_error(&out) {
192 return Err(format!(
193 "gh is not signed in (run `gh auth login`): {detail}"
194 ));
195 }
196 return Err(format!("{label} failed: {detail}"));
197 }
198
199 Ok(out)
200}
201
202fn extract_pr_url(stdout: &str) -> Option<String> {
203 stdout
204 .lines()
205 .rev()
206 .map(str::trim)
207 .find(|line| line.starts_with("https://") || line.starts_with("http://"))
208 .map(String::from)
209}
210
211pub fn push_branch(root: &Path, branch: &str) -> Result<(), String> {
212 validate_branch_name(branch)?;
213 ensure_origin_remote(root)?;
214 let default_branch = default_branch_from_origin_head(root)?;
215 if branch == default_branch {
216 return Err(format!(
217 "refusing to push default branch '{default_branch}'"
218 ));
219 }
220 ensure_local_branch(root, branch)?;
221
222 let out = run_git(root, &["push", "-u", "origin", branch])?;
223 if !out.status.success() {
224 let detail = output_detail(&out);
225 return Err(format!("git push -u origin {branch} failed: {detail}"));
226 }
227 Ok(())
228}
229
230pub fn open_pull_request(
231 root: &Path,
232 branch: &str,
233 title: &str,
234 body: &str,
235) -> Result<String, String> {
236 open_pull_request_with_gh(root, branch, title, body, OsStr::new("gh"))
237}
238
239pub fn open_pull_request_with_gh(
240 root: &Path,
241 branch: &str,
242 title: &str,
243 body: &str,
244 gh_bin: &OsStr,
245) -> Result<String, String> {
246 let title = title.trim();
247 if title.is_empty() {
248 return Err("pull request title must not be empty".to_string());
249 }
250 validate_branch_name(branch)?;
251 ensure_origin_remote(root)?;
252 let default_branch = default_branch_from_origin_head(root)?;
253 if branch == default_branch {
254 return Err(format!(
255 "refusing to open a pull request from default branch '{default_branch}'"
256 ));
257 }
258 ensure_local_branch(root, branch)?;
259
260 let out = run_gh(
261 root,
262 gh_bin,
263 &[
264 "pr",
265 "create",
266 "--base",
267 &default_branch,
268 "--head",
269 branch,
270 "--title",
271 title,
272 "--body",
273 body,
274 ],
275 "gh pr create",
276 )?;
277
278 let stdout = String::from_utf8_lossy(&out.stdout);
279 extract_pr_url(&stdout).ok_or_else(|| {
280 let trimmed = stdout.trim();
281 if trimmed.is_empty() {
282 "gh pr create succeeded but returned no pull request URL".to_string()
283 } else {
284 format!("gh pr create did not return a pull request URL: {trimmed}")
285 }
286 })
287}