Skip to main content

git_stk/
git.rs

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
9/// Pass raw git output through instead of capturing it.
10pub 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
23/// Whether the working directory is inside a git work tree. Used for a clean
24/// "not a git repository" message instead of letting git's raw error surface
25/// from the first command that needs the repo.
26pub 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
44/// Resolve `path` under the repo's *common* git dir, which all linked
45/// worktrees share, rather than the per-worktree dir `git_path` returns. Use
46/// this for state that guards or mirrors the shared config (`branch.*`), so
47/// every worktree of a repo agrees on one file.
48pub 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    // git remote get-url exits 2 when the remote does not exist.
58    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
74/// Force-delete a branch. Use only once review state confirms it landed: a
75/// squash merge leaves the commits non-ancestry-merged, so `git branch -d`
76/// would refuse even though the work is in.
77pub fn delete_branch(branch: &str) -> Result<()> {
78    status(&["branch", "-D", branch]).with_context(|| format!("failed to delete branch {branch}"))
79}
80
81/// Rename a branch; git moves its `branch.<name>.*` config along with it.
82pub 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
86/// Fast-forward a local branch from its remote without checking it out.
87pub 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
104/// Push branches and set upstream tracking; used before submitting so new
105/// branches exist remotely and rebased ones are safely updated.
106pub 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
113/// Store `content` as a single-file commit and point `reference` at it, so the
114/// data rides along a normal ref push. Orphan each time: the ref just moves to
115/// the new commit (callers force-push it, as it is regenerable).
116pub 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
127/// Force-push a single ref to `remote` (the value is regenerable, so
128/// last-writer-wins is fine).
129pub 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
139/// Force-fetch a single ref from `remote` into the same local ref.
140pub 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
145/// The contents of `file` in the commit `reference` points at, or None when
146/// the ref or file is absent.
147pub 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
171/// Rebase only the commits after `base`, replaying `base..branch` onto
172/// `parent`. Used when the recorded fork point is known so commits that
173/// landed upstream by squash or rebase are not replayed.
174pub 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
189/// The commit a branch points at, or None when the branch does not exist.
190pub fn branch_sha(branch: &str) -> Option<String> {
191    rev_parse(branch).ok()
192}
193
194/// Point a branch at a commit, creating it if absent. Does not touch the
195/// worktree.
196pub 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
201/// Reset the worktree and index to HEAD. Safe to lose nothing only on a
202/// clean tree; callers must check [`worktree_is_clean`] first.
203pub fn reset_hard() -> Result<()> {
204    status(&["reset", "--hard"]).context("failed to reset the worktree")
205}
206
207/// Whether the worktree and index have no uncommitted changes.
208pub fn worktree_is_clean() -> Result<bool> {
209    Ok(output(&["status", "--porcelain"])?.is_empty())
210}
211
212/// Default branch of `remote` (from its locally-known HEAD symref), if any.
213pub 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
219/// How many commits `parent` has that `branch` does not: nonzero means the
220/// branch needs a restack.
221pub 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
236/// A unified-0 diff against HEAD: just the staged changes when `cached`,
237/// otherwise all tracked changes (staged and unstaged). Zero context lines
238/// so each hunk's pre-image range pinpoints exactly the lines it touches.
239pub fn diff_against_head(cached: bool) -> Result<String> {
240    // Pin a/ b/ prefixes: diff.mnemonicPrefix / diff.noprefix would otherwise
241    // emit headers absorb's parser and `git apply` cannot read.
242    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
250/// The distinct commits that last touched lines `start..start+len` of `file`
251/// in HEAD, newest blame wins per line. An empty range yields nothing.
252pub 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        // Each porcelain block opens with "<40-hex sha> <orig> <final> ...";
271        // other fields (author, summary, "previous", the tab-led content) do
272        // not start with a bare 40-hex token.
273        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
284/// The commits in `range` (e.g. "main..HEAD"), newest first.
285pub 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
293/// A commit's subject line.
294pub 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
299/// A commit's body - everything after the subject line; empty when there is none.
300pub 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
305/// Stage a unified-0 patch into the index. `--unidiff-zero` is required for
306/// git to accept the zero-context hunks absorb works with.
307pub 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
331/// Commit the staged index as a `fixup!` of `sha`, for a later autosquash
332/// rebase to fold in. Skips hooks: these are internal, transient commits.
333pub 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
338/// Unstage everything, leaving the worktree contents untouched.
339pub fn reset_index() -> Result<()> {
340    status(&["reset", "--quiet"]).context("failed to reset the index")
341}
342
343/// Move HEAD to `sha`, returning any commits after it to the index.
344pub fn reset_soft(sha: &str) -> Result<()> {
345    status(&["reset", "--soft", sha]).with_context(|| format!("failed to reset to {sha}"))
346}
347
348/// Stash tracked worktree changes; pair with [`stash_pop`].
349pub fn stash_push() -> Result<()> {
350    status(&["stash", "push", "--quiet"]).context("failed to stash changes")
351}
352
353/// Restore the most recently stashed changes.
354pub fn stash_pop() -> Result<()> {
355    status(&["stash", "pop", "--quiet"]).context("failed to restore stashed changes")
356}
357
358/// Rebase `base..HEAD`, folding `fixup!` commits into their targets. The
359/// generated todo is accepted unedited, so it needs no terminal.
360pub 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    // merge-base --is-ancestor exits 0 when it is, 1 when it is not.
382    Ok(output_codes(
383        &["merge-base", "--is-ancestor", ancestor, descendant],
384        &[1],
385        "git merge-base --is-ancestor",
386    )?
387    .is_some())
388}
389
390/// Lines added and deleted in `branch` relative to `base`, over the symmetric
391/// `base...branch` range a forge uses for a review diff (the branch's own work
392/// since it diverged). Binary files, which `--numstat` marks with `-`, count
393/// as zero.
394pub 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
406/// A `--numstat` count column: a number, or 0 for `-` (binary) or anything
407/// unparseable.
408fn 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
430/// Whether the short help advertises --update-refs. Match the option name:
431/// git renders it as `--update-refs` or `--[no-]update-refs` by version.
432fn help_mentions_update_refs(help: &str) -> bool {
433    help.contains("update-refs")
434}
435
436pub fn rebase_continue() -> Result<()> {
437    // Passthrough: continuing a rebase can open the user's editor.
438    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    // git config --get exits 1 when the key is unset.
447    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    // git config --get-regexp exits 1 when nothing matches.
468    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    // git config --unset exits 5 when the key was not set; either way it is now
491    // gone, so treat that as success.
492    output_codes(&["config", "--unset", key], &[5], "git config --unset").map(|_| ())
493}
494
495/// Run a git command and map its exit code: trimmed stdout on success, `None`
496/// for any code in `ok_empty` (an expected "nothing here" - e.g. `config
497/// --get`'s 1, or `config --unset`'s 5), and an error otherwise. `label` names
498/// the command for the error message.
499fn 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
531/// Like [`output`], but feeds `input` to the command on stdin (for plumbing
532/// such as `hash-object --stdin` and `mktree`).
533fn 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
555/// Run git quietly: progress and advice only matter when something goes
556/// wrong, so capture them and replay on failure. `--verbose` passes
557/// everything through.
558fn 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
577/// Inherit stdio unconditionally, for git commands that may need the
578/// terminal (e.g. `rebase --continue` opening the editor).
579fn 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        // Ground truth: `--update-refs -h` fails with "unknown option" on a
629        // git without the flag and prints help on one that has it.
630        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}