1use std::process::Command;
4
5use crate::error::{GwError, Result};
6use crate::output;
7
8fn git_run(args: &[&str], verbose: bool) -> Result<()> {
10 if verbose {
11 output::action(&format!("git {}", args.join(" ")));
12 }
13
14 let output = Command::new("git")
15 .args(args)
16 .output()
17 .map_err(|e| GwError::GitCommandFailed(format!("Failed to execute git: {e}")))?;
18
19 if output.status.success() {
20 Ok(())
21 } else {
22 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
23 Err(GwError::GitCommandFailed(stderr))
24 }
25}
26
27fn git_output(args: &[&str], verbose: bool) -> Result<String> {
29 if verbose {
30 output::action(&format!("git {}", args.join(" ")));
31 }
32
33 let output = Command::new("git")
34 .args(args)
35 .output()
36 .map_err(|e| GwError::GitCommandFailed(format!("Failed to execute git: {e}")))?;
37
38 if output.status.success() {
39 Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
40 } else {
41 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
42 Err(GwError::GitCommandFailed(stderr))
43 }
44}
45
46pub fn fetch_prune(verbose: bool) -> Result<()> {
48 git_run(&["fetch", "--prune", "--quiet"], verbose)
49}
50
51pub fn checkout(branch: &str, verbose: bool) -> Result<()> {
53 git_run(&["checkout", branch, "--quiet"], verbose).map_err(|e| map_checkout_error(branch, e))
54}
55
56pub fn checkout_new_branch(branch: &str, start_point: &str, verbose: bool) -> Result<()> {
58 git_run(&["checkout", "-b", branch, start_point, "--quiet"], verbose)
59 .map_err(|e| map_checkout_error(branch, e))
60}
61
62fn map_checkout_error(branch: &str, err: GwError) -> GwError {
68 let GwError::GitCommandFailed(ref msg) = err else {
69 return err;
70 };
71 if msg.contains("already checked out") || msg.contains("already used by worktree") {
72 return GwError::BranchCheckedOutElsewhere {
73 branch: branch.to_string(),
74 path: extract_worktree_path(msg),
75 };
76 }
77 err
78}
79
80fn extract_worktree_path(msg: &str) -> Option<String> {
83 let start = msg.find("at '")? + "at '".len();
84 let rest = &msg[start..];
85 let end = rest.find('\'')?;
86 Some(rest[..end].to_string())
87}
88
89pub fn pull_ff_only(remote: &str, branch: &str, verbose: bool) -> Result<()> {
94 git_run(&["pull", remote, branch, "--ff-only", "--quiet"], verbose)
95}
96
97pub fn delete_branch(branch: &str, verbose: bool) -> Result<()> {
99 git_run(&["branch", "-d", branch], verbose)
100}
101
102pub fn force_delete_branch(branch: &str, verbose: bool) -> Result<()> {
104 git_run(&["branch", "-D", branch], verbose)
105}
106
107#[allow(dead_code)]
109pub fn delete_remote_branch(branch: &str, verbose: bool) -> Result<()> {
110 git_run(&["push", "origin", "--delete", branch], verbose)
111}
112
113pub fn log_commits(from: &str, to: &str, verbose: bool) -> Result<Vec<String>> {
115 let output = git_output(&["log", &format!("{from}..{to}"), "--oneline"], verbose)?;
116 Ok(output.lines().map(String::from).collect())
117}
118
119pub fn add_all(verbose: bool) -> Result<()> {
121 git_run(&["add", "-A"], verbose)
122}
123
124pub fn commit(message: &str, verbose: bool) -> Result<()> {
126 git_run(&["commit", "-m", message], verbose)
127}
128
129pub fn reset_soft(target: &str, verbose: bool) -> Result<()> {
131 git_run(&["reset", "--soft", target], verbose)
132}
133
134pub fn discard_all_changes(verbose: bool) -> Result<()> {
136 git_run(&["reset", "--hard", "HEAD"], verbose)?;
138 git_run(&["clean", "-fd"], verbose)
140}
141
142pub fn rebase(target: &str, verbose: bool) -> Result<()> {
144 git_run(&["rebase", target], verbose)
145}
146
147pub fn rebase_onto(new_base: &str, old_base: &str, verbose: bool) -> Result<()> {
155 git_run(&["rebase", "--onto", new_base, old_base], verbose)
156}
157
158pub fn force_push_with_lease(branch: &str, verbose: bool) -> Result<()> {
160 git_run(&["push", "--force-with-lease", "origin", branch], verbose)
161}
162
163pub fn set_branch_base(branch: &str, base: &str, verbose: bool) -> Result<()> {
170 git_run(
171 &["config", &format!("branch.{branch}.gwBase"), base],
172 verbose,
173 )
174}
175
176pub fn set_branch_base_sha(branch: &str, sha: &str, verbose: bool) -> Result<()> {
180 git_run(
181 &["config", &format!("branch.{branch}.gwBaseSha"), sha],
182 verbose,
183 )
184}
185
186pub fn unset_branch_base(branch: &str, verbose: bool) -> Result<()> {
192 unset_config_key(&format!("branch.{branch}.gwBase"), verbose)?;
193 unset_config_key(&format!("branch.{branch}.gwBaseSha"), verbose)
194}
195
196fn unset_config_key(key: &str, verbose: bool) -> Result<()> {
198 if verbose {
199 output::action(&format!("git config --unset {key}"));
200 }
201 let output = Command::new("git")
202 .args(["config", "--unset", key])
203 .output()
204 .map_err(|e| GwError::GitCommandFailed(format!("Failed to execute git: {e}")))?;
205 match output.status.code() {
207 Some(0) | Some(5) => Ok(()),
208 _ => {
209 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
210 Err(GwError::GitCommandFailed(stderr))
211 }
212 }
213}
214
215pub fn worktree_add(path: &str, branch: &str, start_point: &str, verbose: bool) -> Result<()> {
217 git_run(
218 &["worktree", "add", "-b", branch, path, start_point],
219 verbose,
220 )
221}
222
223pub fn worktree_remove(path: &str, verbose: bool) -> Result<()> {
225 git_run(&["worktree", "remove", "--force", path], verbose)
226}
227
228pub fn worktree_prune(verbose: bool) -> Result<()> {
230 git_run(&["worktree", "prune"], verbose)
231}
232
233pub fn git_run_in_dir(dir: &str, args: &[&str], verbose: bool) -> Result<()> {
237 if verbose {
238 output::action(&format!("git -C {} {}", dir, args.join(" ")));
239 }
240
241 let output = Command::new("git")
242 .args(args)
243 .current_dir(dir)
244 .output()
245 .map_err(|e| GwError::GitCommandFailed(format!("Failed to execute git: {e}")))?;
246
247 if output.status.success() {
248 Ok(())
249 } else {
250 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
251 Err(GwError::GitCommandFailed(stderr))
252 }
253}