Skip to main content

specfold_core/workspace/vcs/
refs.rs

1//! Revisions: HEAD, the upstream branch, and whether a commit is in HEAD's history.
2
3use super::env::{Reach, command};
4use super::repo::git;
5use std::path::Path;
6use std::process::Stdio;
7
8/// The full hash of HEAD.
9pub fn head(root: &Path) -> Option<String> {
10    let out = git(root, &["rev-parse", "HEAD"])?;
11    Some(String::from_utf8_lossy(&out).trim().to_string())
12}
13
14/// The full hash `rev` names, None when git does not know it (C4).
15pub fn resolve(root: &Path, rev: &str) -> Option<String> {
16    let out = git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")])?;
17    let s = String::from_utf8_lossy(&out).trim().to_string();
18    if s.is_empty() { None } else { Some(s) }
19}
20
21/// The tree git diffs a root commit against.
22const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
23
24/// What `sha` is diffed against: its first parent, or the empty tree for a root commit (C260).
25pub fn parent_or_empty(root: &Path, sha: &str) -> String {
26    match resolve(root, &format!("{sha}^")) {
27        Some(_) => format!("{sha}^"),
28        None => EMPTY_TREE.to_string(),
29    }
30}
31
32/// The diff range of one commit, `sha^..sha`, or from the empty tree for a root commit (C260).
33pub fn commit_diff(root: &Path, sha: &str) -> String {
34    format!("{}..{sha}", parent_or_empty(root, sha))
35}
36
37/// The log range of one commit: `sha^..sha`, or `sha` alone for a root commit (C260).
38pub fn commit_log(root: &Path, sha: &str) -> String {
39    match resolve(root, &format!("{sha}^")) {
40        Some(_) => format!("{sha}^..{sha}"),
41        None => sha.to_string(),
42    }
43}
44
45/// The upstream of the current branch, used as the default push range base.
46pub fn upstream(root: &Path) -> Option<String> {
47    let out = git(root, &["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"])?;
48    let s = String::from_utf8(out).ok()?.trim().to_string();
49    if s.is_empty() { None } else { Some(s) }
50}
51
52/// Whether `rev` is HEAD or one of its ancestors; None when git cannot tell (unknown revision).
53pub fn is_ancestor_of_head(root: &Path, rev: &str) -> Option<bool> {
54    let status = command(root, Reach::Root)
55        .args(["merge-base", "--is-ancestor", rev, "HEAD"])
56        .stderr(Stdio::null())
57        .status()
58        .ok()?;
59    match status.code() {
60        Some(0) => Some(true),
61        Some(1) => Some(false),
62        _ => None,
63    }
64}