1use std::io::Write;
2use std::process::{Command, Stdio};
3use std::sync::atomic::{AtomicBool, Ordering};
4
5use anyhow::{Context, Result, anyhow, bail};
6
7static VERBOSE: AtomicBool = AtomicBool::new(false);
8
9pub fn set_verbose(verbose: bool) {
11 VERBOSE.store(verbose, Ordering::Relaxed);
12}
13
14fn verbose() -> bool {
15 VERBOSE.load(Ordering::Relaxed)
16}
17
18pub fn current_branch() -> Result<String> {
19 output(&["symbolic-ref", "--quiet", "--short", "HEAD"])
20 .context("failed to determine current branch")
21}
22
23pub fn is_in_repo() -> bool {
27 Command::new("git")
28 .args(["rev-parse", "--is-inside-work-tree"])
29 .stdout(Stdio::piped())
30 .stderr(Stdio::piped())
31 .output()
32 .is_ok_and(|out| out.status.success() && out.stdout.starts_with(b"true"))
33}
34
35pub fn local_branches() -> Result<Vec<String>> {
36 let output = output(&["for-each-ref", "--format=%(refname:short)", "refs/heads"])?;
37 Ok(output.lines().map(str::to_owned).collect())
38}
39
40pub fn git_path(path: &str) -> Result<String> {
41 output(&["rev-parse", "--git-path", path])
42}
43
44pub fn git_common_path(path: &str) -> Result<String> {
49 let common_dir = output(&["rev-parse", "--git-common-dir"])?;
50 Ok(std::path::Path::new(&common_dir)
51 .join(path)
52 .to_string_lossy()
53 .into_owned())
54}
55
56pub fn remote_url(remote: &str) -> Result<Option<String>> {
57 output_codes(&["remote", "get-url", remote], &[2], "git remote get-url")
59}
60
61pub fn checkout(branch: &str) -> Result<()> {
62 status(&["switch", branch]).with_context(|| format!("failed to check out {branch}"))?;
63 anstream::println!(
64 "switched to {}",
65 crate::style::paint(crate::style::BRANCH, branch)
66 );
67 Ok(())
68}
69
70pub fn create_branch(branch: &str) -> Result<()> {
71 status(&["switch", "-c", branch]).with_context(|| format!("failed to create branch {branch}"))
72}
73
74pub fn delete_branch(branch: &str) -> Result<()> {
78 status(&["branch", "-D", branch]).with_context(|| format!("failed to delete branch {branch}"))
79}
80
81pub fn rename_branch(old: &str, new: &str) -> Result<()> {
83 status(&["branch", "-m", old, new]).with_context(|| format!("failed to rename {old} to {new}"))
84}
85
86pub fn fetch_branch(remote: &str, branch: &str) -> Result<()> {
88 let refspec = format!("{branch}:{branch}");
89 status(&["fetch", remote, &refspec])
90 .with_context(|| format!("failed to fetch {branch} from {remote}"))
91}
92
93pub fn pull_ff_only() -> Result<()> {
94 status(&["pull", "--ff-only"]).context("failed to fast-forward from the remote")
95}
96
97pub fn push_force_with_lease(remote: &str, branches: &[String]) -> Result<()> {
98 let mut args = vec!["push", "--force-with-lease", remote];
99 args.extend(branches.iter().map(String::as_str));
100
101 status(&args).with_context(|| format!("failed to push branches to {remote}"))
102}
103
104pub fn push_set_upstream_force_with_lease(remote: &str, branches: &[String]) -> Result<()> {
107 let mut args = vec!["push", "--set-upstream", "--force-with-lease", remote];
108 args.extend(branches.iter().map(String::as_str));
109
110 status(&args).with_context(|| format!("failed to push branches to {remote}"))
111}
112
113pub fn write_blob_ref(reference: &str, file: &str, content: &str) -> Result<()> {
117 let blob = output_with_stdin(&["hash-object", "-w", "--stdin"], content)
118 .context("failed to hash stack metadata")?;
119 let tree = output_with_stdin(&["mktree"], &format!("100644 blob {blob}\t{file}\n"))
120 .context("failed to write stack metadata tree")?;
121 let commit = output(&["commit-tree", &tree, "-m", "git-stk stack metadata"])
122 .context("failed to commit stack metadata")?;
123 status(&["update-ref", reference, &commit])
124 .with_context(|| format!("failed to update {reference}"))
125}
126
127pub fn push_ref(remote: &str, reference: &str) -> Result<()> {
130 status(&[
131 "push",
132 "--force",
133 remote,
134 &format!("{reference}:{reference}"),
135 ])
136 .with_context(|| format!("failed to push {reference} to {remote}"))
137}
138
139pub fn fetch_ref(remote: &str, reference: &str) -> Result<()> {
141 status(&["fetch", remote, &format!("+{reference}:{reference}")])
142 .with_context(|| format!("failed to fetch {reference} from {remote}"))
143}
144
145pub fn read_ref_file(reference: &str, file: &str) -> Result<Option<String>> {
148 let output = Command::new("git")
149 .args(["cat-file", "blob", &format!("{reference}:{file}")])
150 .stdout(Stdio::piped())
151 .stderr(Stdio::piped())
152 .output()
153 .context("failed to run git cat-file")?;
154 if output.status.success() {
155 Ok(Some(String::from_utf8_lossy(&output.stdout).into_owned()))
156 } else {
157 Ok(None)
158 }
159}
160
161pub fn rebase(parent: &str, branch: &str, update_refs: bool) -> Result<()> {
162 let mut args = vec!["rebase"];
163 if update_refs {
164 args.push("--update-refs");
165 }
166 args.extend([parent, branch]);
167
168 status(&args).with_context(|| format!("failed to rebase {branch} onto {parent}"))
169}
170
171pub fn rebase_onto(parent: &str, base: &str, branch: &str, update_refs: bool) -> Result<()> {
175 let mut args = vec!["rebase"];
176 if update_refs {
177 args.push("--update-refs");
178 }
179 args.extend(["--onto", parent, base, branch]);
180
181 status(&args).with_context(|| format!("failed to rebase {branch} onto {parent} from {base}"))
182}
183
184pub fn rev_parse(rev: &str) -> Result<String> {
185 let spec = format!("{rev}^{{commit}}");
186 output(&["rev-parse", "--verify", &spec]).with_context(|| format!("failed to resolve {rev}"))
187}
188
189pub fn branch_sha(branch: &str) -> Option<String> {
191 rev_parse(branch).ok()
192}
193
194pub fn update_ref(branch: &str, sha: &str) -> Result<()> {
197 status(&["update-ref", &format!("refs/heads/{branch}"), sha])
198 .with_context(|| format!("failed to update {branch} to {sha}"))
199}
200
201pub fn reset_hard() -> Result<()> {
204 status(&["reset", "--hard"]).context("failed to reset the worktree")
205}
206
207pub fn worktree_is_clean() -> Result<bool> {
209 Ok(output(&["status", "--porcelain"])?.is_empty())
210}
211
212pub fn remote_default_branch(remote: &str) -> Option<String> {
214 let reference = format!("refs/remotes/{remote}/HEAD");
215 let full = output(&["symbolic-ref", "--short", &reference]).ok()?;
216 full.strip_prefix(&format!("{remote}/")).map(str::to_owned)
217}
218
219pub fn commits_behind(branch: &str, parent: &str) -> Result<usize> {
222 let range = format!("{branch}..{parent}");
223 let count = output(&["rev-list", "--count", &range])
224 .with_context(|| format!("failed to count commits in {range}"))?;
225 count
226 .trim()
227 .parse()
228 .context("failed to parse rev-list count")
229}
230
231pub fn merge_base(a: &str, b: &str) -> Result<String> {
232 output(&["merge-base", a, b])
233 .with_context(|| format!("failed to find merge base of {a} and {b}"))
234}
235
236pub fn diff_against_head(cached: bool) -> Result<String> {
240 let mut args = vec!["diff", "--unified=0", "--src-prefix=a/", "--dst-prefix=b/"];
243 if cached {
244 args.push("--cached");
245 }
246 args.push("HEAD");
247 output(&args).context("failed to diff against HEAD")
248}
249
250pub fn blame_line_shas(file: &str, start: usize, len: usize) -> Result<Vec<String>> {
253 if len == 0 {
254 return Ok(Vec::new());
255 }
256 let range = format!("{start},{}", start + len - 1);
257 let out = output(&[
258 "blame",
259 "HEAD",
260 "-L",
261 &range,
262 "--line-porcelain",
263 "--",
264 file,
265 ])
266 .with_context(|| format!("failed to blame {file}"))?;
267
268 let mut shas = Vec::new();
269 for line in out.lines() {
270 let token = line.split(' ').next().unwrap_or_default();
274 if token.len() == 40
275 && token.bytes().all(|byte| byte.is_ascii_hexdigit())
276 && !shas.iter().any(|seen| seen == token)
277 {
278 shas.push(token.to_owned());
279 }
280 }
281 Ok(shas)
282}
283
284pub fn rev_list(range: &str) -> Result<Vec<String>> {
286 Ok(output(&["rev-list", range])
287 .with_context(|| format!("failed to list commits in {range}"))?
288 .lines()
289 .map(str::to_owned)
290 .collect())
291}
292
293pub fn commit_subject(sha: &str) -> Result<String> {
295 output(&["show", "--no-patch", "--format=%s", sha])
296 .with_context(|| format!("failed to read subject of {sha}"))
297}
298
299pub fn apply_cached(patch: &str) -> Result<()> {
302 let mut child = Command::new("git")
303 .args(["apply", "--cached", "--unidiff-zero"])
304 .stdin(Stdio::piped())
305 .stdout(Stdio::piped())
306 .stderr(Stdio::piped())
307 .spawn()
308 .context("failed to run git apply")?;
309 {
310 let mut stdin = child.stdin.take().context("git apply has no stdin")?;
311 stdin
312 .write_all(patch.as_bytes())
313 .context("failed to write patch to git apply")?;
314 }
315 let output = child
316 .wait_with_output()
317 .context("failed to run git apply")?;
318 if output.status.success() {
319 Ok(())
320 } else {
321 Err(command_error("git apply", &output.stderr))
322 }
323}
324
325pub fn commit_fixup(sha: &str) -> Result<()> {
328 status(&["commit", "--no-verify", &format!("--fixup={sha}")])
329 .with_context(|| format!("failed to create fixup commit for {sha}"))
330}
331
332pub fn reset_index() -> Result<()> {
334 status(&["reset", "--quiet"]).context("failed to reset the index")
335}
336
337pub fn reset_soft(sha: &str) -> Result<()> {
339 status(&["reset", "--soft", sha]).with_context(|| format!("failed to reset to {sha}"))
340}
341
342pub fn stash_push() -> Result<()> {
344 status(&["stash", "push", "--quiet"]).context("failed to stash changes")
345}
346
347pub fn stash_pop() -> Result<()> {
349 status(&["stash", "pop", "--quiet"]).context("failed to restore stashed changes")
350}
351
352pub fn rebase_autosquash(base: &str, update_refs: bool) -> Result<()> {
355 let mut args = vec!["rebase", "--interactive", "--autosquash"];
356 if update_refs {
357 args.push("--update-refs");
358 }
359 args.push(base);
360
361 let output = Command::new("git")
362 .args(&args)
363 .env("GIT_SEQUENCE_EDITOR", "true")
364 .env("GIT_EDITOR", "true")
365 .output()
366 .context("failed to run git rebase")?;
367 if output.status.success() {
368 Ok(())
369 } else {
370 Err(command_error("git rebase --autosquash", &output.stderr))
371 }
372}
373
374pub fn is_ancestor(ancestor: &str, descendant: &str) -> Result<bool> {
375 Ok(output_codes(
377 &["merge-base", "--is-ancestor", ancestor, descendant],
378 &[1],
379 "git merge-base --is-ancestor",
380 )?
381 .is_some())
382}
383
384pub fn diff_numstat(base: &str, branch: &str) -> Result<(usize, usize)> {
389 let output = output(&["diff", "--numstat", &format!("{base}...{branch}")])?;
390 let mut added = 0;
391 let mut deleted = 0;
392 for line in output.lines() {
393 let mut columns = line.split('\t');
394 added += column_count(columns.next());
395 deleted += column_count(columns.next());
396 }
397 Ok((added, deleted))
398}
399
400fn column_count(column: Option<&str>) -> usize {
403 column
404 .and_then(|value| value.parse::<usize>().ok())
405 .unwrap_or(0)
406}
407
408pub fn supports_rebase_update_refs() -> Result<bool> {
409 let output = Command::new("git")
410 .args(["rebase", "-h"])
411 .stdout(Stdio::piped())
412 .stderr(Stdio::piped())
413 .output()
414 .context("failed to inspect git rebase help")?;
415
416 let help = format!(
417 "{}{}",
418 String::from_utf8_lossy(&output.stdout),
419 String::from_utf8_lossy(&output.stderr)
420 );
421 Ok(help_mentions_update_refs(&help))
422}
423
424fn help_mentions_update_refs(help: &str) -> bool {
427 help.contains("update-refs")
428}
429
430pub fn rebase_continue() -> Result<()> {
431 status_passthrough(&["rebase", "--continue"]).context("failed to continue rebase")
433}
434
435pub fn rebase_abort() -> Result<()> {
436 status(&["rebase", "--abort"]).context("failed to abort rebase")
437}
438
439pub fn config_get(key: &str) -> Result<Option<String>> {
440 output_codes(&["config", "--get", key], &[1], "git config --get")
442}
443
444pub fn config_get_bool(key: &str) -> Result<Option<bool>> {
445 let Some(value) = output_codes(
446 &["config", "--type=bool", "--get", key],
447 &[1],
448 "git config --type=bool --get",
449 )?
450 else {
451 return Ok(None);
452 };
453 match value.as_str() {
454 "true" => Ok(Some(true)),
455 "false" => Ok(Some(false)),
456 _ => bail!("git config {key} is not a boolean: {value}"),
457 }
458}
459
460pub fn config_get_regexp(pattern: &str) -> Result<Vec<(String, String)>> {
461 let Some(text) = output_codes(
463 &["config", "--get-regexp", pattern],
464 &[1],
465 "git config --get-regexp",
466 )?
467 else {
468 return Ok(Vec::new());
469 };
470 Ok(text
471 .lines()
472 .filter_map(|line| {
473 line.split_once(' ')
474 .map(|(key, value)| (key.to_owned(), value.to_owned()))
475 })
476 .collect())
477}
478
479pub fn config_set(key: &str, value: &str) -> Result<()> {
480 status(&["config", key, value]).with_context(|| format!("failed to set git config {key}"))
481}
482
483pub fn config_unset(key: &str) -> Result<()> {
484 output_codes(&["config", "--unset", key], &[5], "git config --unset").map(|_| ())
487}
488
489fn output_codes(args: &[&str], ok_empty: &[i32], label: &str) -> Result<Option<String>> {
494 let output = Command::new("git")
495 .args(args)
496 .stdout(Stdio::piped())
497 .stderr(Stdio::piped())
498 .output()
499 .context("failed to run git")?;
500
501 match output.status.code() {
502 Some(0) => Ok(Some(
503 String::from_utf8_lossy(&output.stdout).trim().to_owned(),
504 )),
505 Some(code) if ok_empty.contains(&code) => Ok(None),
506 _ => Err(command_error(label, &output.stderr)),
507 }
508}
509
510fn output(args: &[&str]) -> Result<String> {
511 let output = Command::new("git")
512 .args(args)
513 .stdout(Stdio::piped())
514 .stderr(Stdio::piped())
515 .output()
516 .context("failed to run git")?;
517
518 if output.status.success() {
519 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
520 } else {
521 Err(command_error("git", &output.stderr))
522 }
523}
524
525fn output_with_stdin(args: &[&str], input: &str) -> Result<String> {
528 let mut child = Command::new("git")
529 .args(args)
530 .stdin(Stdio::piped())
531 .stdout(Stdio::piped())
532 .stderr(Stdio::piped())
533 .spawn()
534 .context("failed to run git")?;
535 {
536 let mut stdin = child.stdin.take().context("git has no stdin")?;
537 stdin
538 .write_all(input.as_bytes())
539 .context("failed to write to git")?;
540 }
541 let output = child.wait_with_output().context("failed to run git")?;
542 if output.status.success() {
543 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
544 } else {
545 Err(command_error("git", &output.stderr))
546 }
547}
548
549fn status(args: &[&str]) -> Result<()> {
553 if verbose() {
554 return status_passthrough(args);
555 }
556
557 let output = Command::new("git")
558 .args(args)
559 .output()
560 .context("failed to run git")?;
561
562 if output.status.success() {
563 Ok(())
564 } else {
565 let _ = std::io::stdout().write_all(&output.stdout);
566 let _ = std::io::stderr().write_all(&output.stderr);
567 bail!("git exited with status {}", output.status)
568 }
569}
570
571fn status_passthrough(args: &[&str]) -> Result<()> {
574 let status = Command::new("git")
575 .args(args)
576 .status()
577 .context("failed to run git")?;
578
579 if status.success() {
580 Ok(())
581 } else {
582 bail!("git exited with status {status}")
583 }
584}
585
586fn command_error(command: &str, stderr: &[u8]) -> anyhow::Error {
587 let stderr = String::from_utf8_lossy(stderr).trim().to_owned();
588 if stderr.is_empty() {
589 anyhow!("{command} failed")
590 } else {
591 anyhow!("{command} failed: {stderr}")
592 }
593}
594
595#[cfg(test)]
596mod tests {
597 use super::*;
598
599 #[test]
600 fn help_mentions_update_refs_matches_pre_2_43_spelling() {
601 assert!(help_mentions_update_refs(
602 " --update-refs update branches that point to commits that are being rebased"
603 ));
604 }
605
606 #[test]
607 fn help_mentions_update_refs_matches_negatable_spelling() {
608 assert!(help_mentions_update_refs(
609 " --[no-]update-refs update branches that point to commits that are being rebased"
610 ));
611 }
612
613 #[test]
614 fn help_mentions_update_refs_rejects_help_without_the_option() {
615 assert!(!help_mentions_update_refs(
616 " --[no-]autosquash move commits that begin with squash!/fixup!"
617 ));
618 }
619
620 #[test]
621 fn detection_agrees_with_the_real_git_on_this_machine() {
622 let probe = Command::new("git")
625 .args(["rebase", "--update-refs", "-h"])
626 .stdout(Stdio::piped())
627 .stderr(Stdio::piped())
628 .output()
629 .expect("run git rebase probe");
630 let probe_text = format!(
631 "{}{}",
632 String::from_utf8_lossy(&probe.stdout),
633 String::from_utf8_lossy(&probe.stderr)
634 );
635 let real_support = !probe_text.contains("unknown option");
636
637 assert_eq!(
638 supports_rebase_update_refs().expect("detect support"),
639 real_support
640 );
641 }
642}