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
40fn ensure_origin_remote(root: &Path) -> Result<(), 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(());
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 default_branch_from_origin_head(root: &Path) -> Result<String, String> {
56 let out = run_git(root, &["symbolic-ref", "refs/remotes/origin/HEAD"])?;
57 if !out.status.success() {
58 let detail = output_detail(&out);
59 return Err(format!(
60 "could not read default branch from origin/HEAD: {detail}"
61 ));
62 }
63 let full_ref = String::from_utf8_lossy(&out.stdout).trim().to_string();
64 match full_ref.strip_prefix("refs/remotes/origin/") {
65 Some(name) if !name.is_empty() => Ok(name.to_string()),
66 _ => Err(format!("origin/HEAD points to unexpected ref '{full_ref}'")),
67 }
68}
69
70fn ensure_local_branch(root: &Path, branch: &str) -> Result<(), String> {
71 let full_ref = format!("refs/heads/{branch}");
72 let out = run_git(root, &["show-ref", "--verify", "--quiet", &full_ref])?;
73 if out.status.success() {
74 return Ok(());
75 }
76 Err(format!("branch '{branch}' does not exist"))
77}
78
79fn is_gh_auth_error(out: &Output) -> bool {
80 if out.status.code() == Some(4) {
81 return true;
82 }
83 let combined = format!(
84 "{}\n{}",
85 String::from_utf8_lossy(&out.stderr),
86 String::from_utf8_lossy(&out.stdout)
87 )
88 .to_ascii_lowercase();
89 [
90 "gh auth login",
91 "not logged in",
92 "not logged into",
93 "not signed in",
94 "authentication",
95 "unauthorized",
96 "http 401",
97 ]
98 .iter()
99 .any(|needle| combined.contains(needle))
100}
101
102fn extract_pr_url(stdout: &str) -> Option<String> {
103 stdout
104 .lines()
105 .rev()
106 .map(str::trim)
107 .find(|line| line.starts_with("https://") || line.starts_with("http://"))
108 .map(String::from)
109}
110
111pub fn push_branch(root: &Path, branch: &str) -> Result<(), String> {
112 validate_branch_name(branch)?;
113 ensure_origin_remote(root)?;
114 let default_branch = default_branch_from_origin_head(root)?;
115 if branch == default_branch {
116 return Err(format!(
117 "refusing to push default branch '{default_branch}'"
118 ));
119 }
120 ensure_local_branch(root, branch)?;
121
122 let out = run_git(root, &["push", "-u", "origin", branch])?;
123 if !out.status.success() {
124 let detail = output_detail(&out);
125 return Err(format!("git push -u origin {branch} failed: {detail}"));
126 }
127 Ok(())
128}
129
130pub fn open_pull_request(
131 root: &Path,
132 branch: &str,
133 title: &str,
134 body: &str,
135) -> Result<String, String> {
136 open_pull_request_with_gh(root, branch, title, body, OsStr::new("gh"))
137}
138
139pub fn open_pull_request_with_gh(
140 root: &Path,
141 branch: &str,
142 title: &str,
143 body: &str,
144 gh_bin: &OsStr,
145) -> Result<String, String> {
146 let title = title.trim();
147 if title.is_empty() {
148 return Err("pull request title must not be empty".to_string());
149 }
150 validate_branch_name(branch)?;
151 ensure_origin_remote(root)?;
152 let default_branch = default_branch_from_origin_head(root)?;
153 if branch == default_branch {
154 return Err(format!(
155 "refusing to open a pull request from default branch '{default_branch}'"
156 ));
157 }
158 ensure_local_branch(root, branch)?;
159
160 let out = Command::new(gh_bin)
161 .args([
162 "pr",
163 "create",
164 "--base",
165 &default_branch,
166 "--head",
167 branch,
168 "--title",
169 title,
170 "--body",
171 body,
172 ])
173 .current_dir(root)
174 .env("GH_PROMPT_DISABLED", "1")
175 .output()
176 .map_err(|e| {
177 if e.kind() == std::io::ErrorKind::NotFound {
178 "gh CLI is not installed or not found on PATH".to_string()
179 } else {
180 format!("failed to run gh pr create: {e}")
181 }
182 })?;
183
184 if !out.status.success() {
185 let detail = output_detail(&out);
186 if is_gh_auth_error(&out) {
187 return Err(format!(
188 "gh is not signed in (run `gh auth login`): {detail}"
189 ));
190 }
191 return Err(format!("gh pr create failed: {detail}"));
192 }
193
194 let stdout = String::from_utf8_lossy(&out.stdout);
195 extract_pr_url(&stdout).ok_or_else(|| {
196 let trimmed = stdout.trim();
197 if trimmed.is_empty() {
198 "gh pr create succeeded but returned no pull request URL".to_string()
199 } else {
200 format!("gh pr create did not return a pull request URL: {trimmed}")
201 }
202 })
203}