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 commit_body(sha: &str) -> Result<String> {
301 output(&["show", "--no-patch", "--format=%b", sha])
302 .with_context(|| format!("failed to read body of {sha}"))
303}
304
305pub fn apply_cached(patch: &str) -> Result<()> {
308 let mut child = Command::new("git")
309 .args(["apply", "--cached", "--unidiff-zero"])
310 .stdin(Stdio::piped())
311 .stdout(Stdio::piped())
312 .stderr(Stdio::piped())
313 .spawn()
314 .context("failed to run git apply")?;
315 {
316 let mut stdin = child.stdin.take().context("git apply has no stdin")?;
317 stdin
318 .write_all(patch.as_bytes())
319 .context("failed to write patch to git apply")?;
320 }
321 let output = child
322 .wait_with_output()
323 .context("failed to run git apply")?;
324 if output.status.success() {
325 Ok(())
326 } else {
327 Err(command_error("git apply", &output.stderr))
328 }
329}
330
331pub fn commit_fixup(sha: &str) -> Result<()> {
334 status(&["commit", "--no-verify", &format!("--fixup={sha}")])
335 .with_context(|| format!("failed to create fixup commit for {sha}"))
336}
337
338pub fn reset_index() -> Result<()> {
340 status(&["reset", "--quiet"]).context("failed to reset the index")
341}
342
343pub fn reset_soft(sha: &str) -> Result<()> {
345 status(&["reset", "--soft", sha]).with_context(|| format!("failed to reset to {sha}"))
346}
347
348pub fn stash_push() -> Result<()> {
350 status(&["stash", "push", "--quiet"]).context("failed to stash changes")
351}
352
353pub fn stash_pop() -> Result<()> {
355 status(&["stash", "pop", "--quiet"]).context("failed to restore stashed changes")
356}
357
358pub fn rebase_autosquash(base: &str, update_refs: bool) -> Result<()> {
361 let mut args = vec!["rebase", "--interactive", "--autosquash"];
362 if update_refs {
363 args.push("--update-refs");
364 }
365 args.push(base);
366
367 let output = Command::new("git")
368 .args(&args)
369 .env("GIT_SEQUENCE_EDITOR", "true")
370 .env("GIT_EDITOR", "true")
371 .output()
372 .context("failed to run git rebase")?;
373 if output.status.success() {
374 Ok(())
375 } else {
376 Err(command_error("git rebase --autosquash", &output.stderr))
377 }
378}
379
380pub fn is_ancestor(ancestor: &str, descendant: &str) -> Result<bool> {
381 Ok(output_codes(
383 &["merge-base", "--is-ancestor", ancestor, descendant],
384 &[1],
385 "git merge-base --is-ancestor",
386 )?
387 .is_some())
388}
389
390pub fn diff_numstat(base: &str, branch: &str) -> Result<(usize, usize)> {
395 let output = output(&["diff", "--numstat", &format!("{base}...{branch}")])?;
396 let mut added = 0;
397 let mut deleted = 0;
398 for line in output.lines() {
399 let mut columns = line.split('\t');
400 added += column_count(columns.next());
401 deleted += column_count(columns.next());
402 }
403 Ok((added, deleted))
404}
405
406fn column_count(column: Option<&str>) -> usize {
409 column
410 .and_then(|value| value.parse::<usize>().ok())
411 .unwrap_or(0)
412}
413
414pub fn supports_rebase_update_refs() -> Result<bool> {
415 let output = Command::new("git")
416 .args(["rebase", "-h"])
417 .stdout(Stdio::piped())
418 .stderr(Stdio::piped())
419 .output()
420 .context("failed to inspect git rebase help")?;
421
422 let help = format!(
423 "{}{}",
424 String::from_utf8_lossy(&output.stdout),
425 String::from_utf8_lossy(&output.stderr)
426 );
427 Ok(help_mentions_update_refs(&help))
428}
429
430fn help_mentions_update_refs(help: &str) -> bool {
433 help.contains("update-refs")
434}
435
436pub fn rebase_continue() -> Result<()> {
437 status_passthrough(&["rebase", "--continue"]).context("failed to continue rebase")
439}
440
441pub fn rebase_abort() -> Result<()> {
442 status(&["rebase", "--abort"]).context("failed to abort rebase")
443}
444
445pub fn config_get(key: &str) -> Result<Option<String>> {
446 output_codes(&["config", "--get", key], &[1], "git config --get")
448}
449
450pub fn config_get_bool(key: &str) -> Result<Option<bool>> {
451 let Some(value) = output_codes(
452 &["config", "--type=bool", "--get", key],
453 &[1],
454 "git config --type=bool --get",
455 )?
456 else {
457 return Ok(None);
458 };
459 match value.as_str() {
460 "true" => Ok(Some(true)),
461 "false" => Ok(Some(false)),
462 _ => bail!("git config {key} is not a boolean: {value}"),
463 }
464}
465
466pub fn config_get_regexp(pattern: &str) -> Result<Vec<(String, String)>> {
467 let Some(text) = output_codes(
469 &["config", "--get-regexp", pattern],
470 &[1],
471 "git config --get-regexp",
472 )?
473 else {
474 return Ok(Vec::new());
475 };
476 Ok(text
477 .lines()
478 .filter_map(|line| {
479 line.split_once(' ')
480 .map(|(key, value)| (key.to_owned(), value.to_owned()))
481 })
482 .collect())
483}
484
485pub fn config_set(key: &str, value: &str) -> Result<()> {
486 status(&["config", key, value]).with_context(|| format!("failed to set git config {key}"))
487}
488
489pub fn config_unset(key: &str) -> Result<()> {
490 output_codes(&["config", "--unset", key], &[5], "git config --unset").map(|_| ())
493}
494
495fn output_codes(args: &[&str], ok_empty: &[i32], label: &str) -> Result<Option<String>> {
500 let output = Command::new("git")
501 .args(args)
502 .stdout(Stdio::piped())
503 .stderr(Stdio::piped())
504 .output()
505 .context("failed to run git")?;
506
507 match output.status.code() {
508 Some(0) => Ok(Some(
509 String::from_utf8_lossy(&output.stdout).trim().to_owned(),
510 )),
511 Some(code) if ok_empty.contains(&code) => Ok(None),
512 _ => Err(command_error(label, &output.stderr)),
513 }
514}
515
516fn output(args: &[&str]) -> Result<String> {
517 let output = Command::new("git")
518 .args(args)
519 .stdout(Stdio::piped())
520 .stderr(Stdio::piped())
521 .output()
522 .context("failed to run git")?;
523
524 if output.status.success() {
525 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
526 } else {
527 Err(command_error("git", &output.stderr))
528 }
529}
530
531fn output_with_stdin(args: &[&str], input: &str) -> Result<String> {
534 let mut child = Command::new("git")
535 .args(args)
536 .stdin(Stdio::piped())
537 .stdout(Stdio::piped())
538 .stderr(Stdio::piped())
539 .spawn()
540 .context("failed to run git")?;
541 {
542 let mut stdin = child.stdin.take().context("git has no stdin")?;
543 stdin
544 .write_all(input.as_bytes())
545 .context("failed to write to git")?;
546 }
547 let output = child.wait_with_output().context("failed to run git")?;
548 if output.status.success() {
549 Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
550 } else {
551 Err(command_error("git", &output.stderr))
552 }
553}
554
555fn status(args: &[&str]) -> Result<()> {
559 if verbose() {
560 return status_passthrough(args);
561 }
562
563 let output = Command::new("git")
564 .args(args)
565 .output()
566 .context("failed to run git")?;
567
568 if output.status.success() {
569 Ok(())
570 } else {
571 let _ = std::io::stdout().write_all(&output.stdout);
572 let _ = std::io::stderr().write_all(&output.stderr);
573 bail!("git exited with status {}", output.status)
574 }
575}
576
577fn status_passthrough(args: &[&str]) -> Result<()> {
580 let status = Command::new("git")
581 .args(args)
582 .status()
583 .context("failed to run git")?;
584
585 if status.success() {
586 Ok(())
587 } else {
588 bail!("git exited with status {status}")
589 }
590}
591
592fn command_error(command: &str, stderr: &[u8]) -> anyhow::Error {
593 let stderr = String::from_utf8_lossy(stderr).trim().to_owned();
594 if stderr.is_empty() {
595 anyhow!("{command} failed")
596 } else {
597 anyhow!("{command} failed: {stderr}")
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn help_mentions_update_refs_matches_pre_2_43_spelling() {
607 assert!(help_mentions_update_refs(
608 " --update-refs update branches that point to commits that are being rebased"
609 ));
610 }
611
612 #[test]
613 fn help_mentions_update_refs_matches_negatable_spelling() {
614 assert!(help_mentions_update_refs(
615 " --[no-]update-refs update branches that point to commits that are being rebased"
616 ));
617 }
618
619 #[test]
620 fn help_mentions_update_refs_rejects_help_without_the_option() {
621 assert!(!help_mentions_update_refs(
622 " --[no-]autosquash move commits that begin with squash!/fixup!"
623 ));
624 }
625
626 #[test]
627 fn detection_agrees_with_the_real_git_on_this_machine() {
628 let probe = Command::new("git")
631 .args(["rebase", "--update-refs", "-h"])
632 .stdout(Stdio::piped())
633 .stderr(Stdio::piped())
634 .output()
635 .expect("run git rebase probe");
636 let probe_text = format!(
637 "{}{}",
638 String::from_utf8_lossy(&probe.stdout),
639 String::from_utf8_lossy(&probe.stderr)
640 );
641 let real_support = !probe_text.contains("unknown option");
642
643 assert_eq!(
644 supports_rebase_update_refs().expect("detect support"),
645 real_support
646 );
647 }
648}