use super::{CliError, Commit};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Outcome {
Verification,
Action,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub(super) enum Direction {
Fetch,
Push,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct Contact<'a> {
pub(super) remote: &'a str,
pub(super) direction: Direction,
}
impl Contact<'_> {
pub(super) fn key(self) -> (String, Direction) {
(self.remote.to_owned(), self.direction)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Answer {
Always,
Sometimes,
Never,
}
pub(super) struct Spec {
outcome: Outcome,
pub(super) answer: Answer,
pub(super) lossy: bool,
}
impl Spec {
const LOOK: Self = Self {
outcome: Outcome::Verification,
answer: Answer::Sometimes,
lossy: false,
};
const ANSWERING_LOOK: Self = Self {
answer: Answer::Always,
..Self::LOOK
};
const ACT: Self = Self {
outcome: Outcome::Action,
answer: Answer::Sometimes,
lossy: false,
};
const ANSWERING_ACT: Self = Self {
answer: Answer::Always,
..Self::ACT
};
const LOSSY_ACT: Self = Self {
lossy: true,
..Self::ACT
};
const PERFORM: Self = Self {
answer: Answer::Never,
..Self::ACT
};
}
pub(super) const SKIP_CHECKS_ATOM: &str = "%(trailers:key=skip-checks,valueonly,unfold)";
#[derive(Clone, Copy, Debug)]
pub(in crate::cli) enum Op<'a> {
ReachableTags,
AllTags,
IsShallow,
TagOptRemotes,
RemoteNames,
AdvertisedTags {
remote: &'a str,
},
ChangedPaths {
from: &'a str,
},
Head,
RemoteUrl {
remote: &'a str,
},
RemoteUrls,
MergeBase {
tip: &'a str,
},
Commits {
from: &'a str,
},
CommitPaths {
hash: &'a str,
},
CommitParents {
hash: &'a str,
},
LocalTagCommit {
tag: &'a str,
},
WorktreeStatus,
CommitMessage {
commit: &'a str,
},
RefExists {
reference: &'a str,
},
ValidRefName {
reference: &'a str,
},
WorkflowTree {
commit: &'a Commit,
},
BlobText {
commit: &'a Commit,
path: &'a str,
},
TreeEntry {
commit: &'a Commit,
path: &'a str,
},
FileAddedBy {
path: &'a str,
},
AnnotatedTag {
name: &'a str,
commit: &'a Commit,
},
PushTag {
remote: &'a str,
tag: &'a str,
},
}
#[cfg(test)]
pub(super) fn fixture_commit() -> &'static Commit {
static FIXTURE: std::sync::OnceLock<Commit> = std::sync::OnceLock::new();
FIXTURE.get_or_init(|| Commit(String::from("cafebabe")))
}
pub(super) struct OpShape<'a> {
pub(super) argv: Vec<String>,
pub(super) spec: Spec,
pub(super) name: &'static str,
pub(super) contact: Option<Contact<'a>>,
pub(super) operand: Option<String>,
}
impl<'a> Op<'a> {
#[expect(
clippy::too_many_lines,
reason = "a table, one row per operation; it grows with the enum"
)]
pub(super) fn shape(&self) -> OpShape<'a> {
let owned = |parts: &[&str]| parts.iter().map(|part| (*part).to_owned()).collect();
let named = |value: &str| Some(value.to_owned());
match *self {
Self::ReachableTags => OpShape {
argv: owned(&[
"for-each-ref",
"--merged=HEAD",
"--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)",
"refs/tags",
]),
spec: Spec::LOOK,
name: "for-each-ref --merged HEAD",
contact: None,
operand: None,
},
Self::AllTags => OpShape {
argv: owned(&[
"for-each-ref",
"--format=%(refname)%00%(objectname)",
"refs/tags",
]),
spec: Spec::LOOK,
name: "for-each-ref refs/tags",
contact: None,
operand: None,
},
Self::IsShallow => OpShape {
argv: owned(&["rev-parse", "--is-shallow-repository"]),
spec: Spec::ANSWERING_LOOK,
name: "rev-parse --is-shallow-repository",
contact: None,
operand: None,
},
Self::TagOptRemotes => OpShape {
argv: owned(&["config", "--get-regexp", r"^remote\..*\.tagopt$"]),
spec: Spec::ANSWERING_LOOK,
name: "config --get-regexp tagopt",
contact: None,
operand: None,
},
Self::RemoteNames => OpShape {
argv: owned(&["remote"]),
spec: Spec::LOOK,
name: "remote",
contact: None,
operand: None,
},
Self::AdvertisedTags { remote } => OpShape {
argv: owned(&["ls-remote", "--tags", "--", remote]),
spec: Spec::LOOK,
name: "ls-remote --tags",
contact: Some(Contact {
remote,
direction: Direction::Fetch,
}),
operand: named(remote),
},
Self::ChangedPaths { from } => OpShape {
argv: vec![
String::from("diff"),
String::from("-z"),
String::from("--name-only"),
format!("{from}...HEAD"),
],
spec: Spec::LOOK,
name: "diff --name-only",
contact: None,
operand: Some(format!("{from}...HEAD")),
},
Self::Head => OpShape {
argv: owned(&["rev-parse", "HEAD"]),
spec: Spec::ANSWERING_ACT,
name: "rev-parse HEAD",
contact: None,
operand: None,
},
Self::RemoteUrl { remote } => OpShape {
argv: owned(&["remote", "get-url", "--", remote]),
spec: Spec::ANSWERING_ACT,
name: "remote get-url",
contact: None,
operand: named(remote),
},
Self::RemoteUrls => OpShape {
argv: owned(&["remote", "-v"]),
spec: Spec::ACT,
name: "remote -v",
contact: None,
operand: None,
},
Self::MergeBase { tip } => OpShape {
argv: owned(&["merge-base", tip, "HEAD"]),
spec: Spec::ANSWERING_ACT,
name: "merge-base",
contact: None,
operand: named(tip),
},
Self::Commits { from } => OpShape {
argv: vec![
String::from("log"),
format!("{from}..HEAD"),
String::from("--reverse"),
String::from("--format=%H%x00%s%x00%b%x00"),
],
spec: Spec::LOSSY_ACT,
name: "log",
contact: None,
operand: Some(format!("{from}..HEAD")),
},
Self::CommitPaths { hash } => OpShape {
argv: owned(&[
"diff-tree",
"--no-commit-id",
"--name-only",
"-z",
"-r",
"--root",
hash,
]),
spec: Spec::ACT,
name: "diff-tree",
contact: None,
operand: named(hash),
},
Self::CommitParents { hash } => OpShape {
argv: owned(&["rev-list", "--parents", "-n", "1", hash]),
spec: Spec::ANSWERING_ACT,
name: "rev-list --parents",
contact: None,
operand: named(hash),
},
Self::LocalTagCommit { tag } => OpShape {
argv: vec![
String::from("rev-parse"),
String::from("--verify"),
String::from("--quiet"),
format!("refs/tags/{tag}^{{}}"),
],
spec: Spec::ANSWERING_ACT,
name: "rev-parse --verify refs/tags",
contact: None,
operand: named(tag),
},
Self::WorktreeStatus => OpShape {
argv: owned(&[
"-c",
"core.fsmonitor=false",
"status",
"--porcelain",
"--untracked-files=all",
]),
spec: Spec::ACT,
name: "status --porcelain",
contact: None,
operand: None,
},
Self::CommitMessage { commit } => OpShape {
argv: vec![
String::from("log"),
String::from("-1"),
format!("--format=%B%x00{SKIP_CHECKS_ATOM}"),
String::from(commit),
],
spec: Spec::LOSSY_ACT,
name: "log -1",
contact: None,
operand: named(commit),
},
Self::RefExists { reference } => OpShape {
argv: owned(&["rev-parse", "--verify", "--quiet", reference]),
spec: Spec::ANSWERING_ACT,
name: "rev-parse --verify",
contact: None,
operand: named(reference),
},
Self::ValidRefName { reference } => OpShape {
argv: vec![
String::from("check-ref-format"),
format!("refs/tags/{reference}"),
],
spec: Spec::PERFORM,
name: "check-ref-format",
contact: None,
operand: named(reference),
},
Self::WorkflowTree { commit } => OpShape {
argv: vec![
String::from("ls-tree"),
String::from("--name-only"),
String::from("-r"),
String::from("-z"),
commit.as_str().to_owned(),
String::from("--"),
String::from(".github/workflows/"),
],
spec: Spec::LOOK,
name: "ls-tree",
contact: None,
operand: named(commit.as_str()),
},
Self::BlobText { commit, path } => OpShape {
argv: vec![
String::from("cat-file"),
String::from("blob"),
format!("{}:{path}", commit.as_str()),
],
spec: Spec::LOOK,
name: "cat-file blob",
contact: None,
operand: Some(format!("{}:{path}", commit.as_str())),
},
Self::TreeEntry { commit, path } => OpShape {
argv: vec![
String::from("ls-tree"),
String::from("-z"),
commit.as_str().to_owned(),
String::from("--"),
format!(":(literal){path}"),
],
spec: Spec::LOOK,
name: "ls-tree --",
contact: None,
operand: Some(format!("{} -- {path}", commit.as_str())),
},
Self::FileAddedBy { path } => OpShape {
argv: vec![
String::from("log"),
String::from("--ignore-missing"),
String::from("--diff-filter=A"),
String::from("-n"),
String::from("1"),
String::from("--format=%H%x00%an%x00%ae%x00%s"),
String::from("HEAD"),
String::from("--"),
format!(":(literal){path}"),
],
spec: Spec::LOOK,
name: "log --diff-filter=A",
contact: None,
operand: named(path),
},
Self::AnnotatedTag { name, commit } => OpShape {
argv: vec![
String::from("tag"),
String::from("-m"),
name.to_owned(),
String::from("--"),
name.to_owned(),
commit.as_str().to_owned(),
],
spec: Spec::PERFORM,
name: "tag",
contact: None,
operand: named(name),
},
Self::PushTag { remote, tag } => OpShape {
argv: vec![
String::from("push"),
String::from("--"),
remote.to_owned(),
format!("refs/tags/{tag}"),
],
spec: Spec::PERFORM,
name: "push",
contact: Some(Contact {
remote,
direction: Direction::Push,
}),
operand: Some(format!("{remote} {tag}")),
},
}
}
}
impl OpShape<'_> {
pub(super) fn fail(&self, detail: &str) -> CliError {
let note = self.credentials_note(detail).unwrap_or("");
self.phrase(|what| format!("git {what} failed: {detail}{note}"))
}
fn credentials_note(&self, detail: &str) -> Option<&'static str> {
self.contact?;
let starved = detail.contains("terminal prompts disabled")
|| detail.contains("could not read Username")
|| detail.contains("could not read Password")
|| detail.contains("Authentication failed");
starved.then_some(
" (oakum disables git's credential prompts so a release cannot \
hang on one; configure or refresh a git credential helper for \
this remote — with the GitHub CLI, `gh auth setup-git` sets one \
up)",
)
}
pub(super) fn unreadable_transport(&self, detail: &str) -> CliError {
self.phrase(|what| {
format!(
"git {what} needs an ssh configuration oakum could not read \
({detail}); to skip an unreadable repository ssh config, set \
both GIT_SSH_COMMAND and GIT_SSH_VARIANT — oakum will not \
guess a transport, because those variables outrank every other \
source and guessing would replace a key or proxy the user \
configured"
)
})
}
pub(super) fn phrase(&self, message: impl FnOnce(&str) -> String) -> CliError {
let what = match &self.operand {
Some(operand) => format!("{} {operand}", self.name),
None => self.name.to_owned(),
};
let message = message(&what);
match self.spec.outcome {
Outcome::Verification => CliError::unverified(format!("unverified: {message}")),
Outcome::Action => CliError::new(message),
}
}
}
#[cfg(test)]
mod tests {
use super::Answer::{Always, Never, Sometimes};
use super::Outcome::{Action, Verification};
use super::{fixture_commit, Answer, Contact, Direction, Op, Outcome};
#[test]
fn only_the_remote_operations_contact_one() {
assert_eq!(
Op::AdvertisedTags { remote: "upstream" }.shape().contact,
Some(Contact {
remote: "upstream",
direction: Direction::Fetch
})
);
assert_eq!(
Op::PushTag {
remote: "upstream",
tag: "v1.0.0"
}
.shape()
.contact,
Some(Contact {
remote: "upstream",
direction: Direction::Push
})
);
for op in [Op::RemoteUrl { remote: "origin" }, Op::RemoteUrls] {
assert!(
op.shape().contact.is_none(),
"{op:?} answers the reach question and must not ask it"
);
}
}
#[test]
fn every_operation_has_its_own_name() {
let every = every();
let mut names: Vec<&str> = every.iter().map(|op| op.shape().name).collect();
let listed = names.len();
names.sort_unstable();
names.dedup();
assert_eq!(
names.len(),
listed,
"two operations share a name: {names:?}"
);
}
#[test]
fn the_worktree_read_overrides_a_broken_fsmonitor_rather_than_tolerating_it() {
let argv = Op::WorktreeStatus.shape().argv;
assert_eq!(&argv[..2], ["-c", "core.fsmonitor=false"], "{argv:?}");
}
#[test]
fn a_network_verb_and_a_contact_agree() {
for op in every() {
let shape = op.shape();
let argv = shape.argv;
assert_eq!(
reaches_the_network(&argv),
shape.contact.is_some(),
"{op:?} runs `git {}` but disagrees about contacting a remote",
argv.join(" ")
);
}
}
fn reaches_the_network(argv: &[String]) -> bool {
let mut rest = argv.iter().map(String::as_str);
let mut verb = rest.next().unwrap_or_default();
while verb == "-c" {
rest.next();
verb = rest.next().unwrap_or_default();
}
match verb {
"fetch" | "push" | "ls-remote" | "clone" | "pull" => true,
"remote" => rest.next() == Some("update"),
_ => false,
}
}
#[test]
fn the_network_check_reads_past_config_and_subcommands() {
let argv = |args: &[&str]| {
args.iter()
.copied()
.map(String::from)
.collect::<Vec<String>>()
};
for reaching in [
&["fetch", "--tags", "--", "origin"][..],
&["-c", "protocol.version=2", "fetch", "origin"][..],
&["-c", "a=b", "-c", "c=d", "push", "origin"][..],
&["remote", "update", "origin"][..],
] {
assert!(
reaches_the_network(&argv(reaching)),
"`git {}` reaches the network",
reaching.join(" ")
);
}
for local in [
&["remote", "get-url", "--", "origin"][..],
&["remote"][..],
&["-c", "core.fsmonitor=false", "status", "--porcelain"][..],
&["-c", "a=b"][..],
&[][..],
] {
assert!(
!reaches_the_network(&argv(local)),
"`git {}` does not",
local.join(" ")
);
}
}
#[test]
fn every_variant_is_listed_in_every() {
let source = include_str!("op.rs");
let opener = concat!("pub(in crate::cli) ", "enum Op<'a> {");
let body = source
.split_once(opener)
.expect("the Op enum")
.1
.split_once("\n}\n")
.expect("the end of the Op enum")
.0;
let declared = body
.lines()
.filter(|line| {
let trimmed = line.trim_start();
line.len() - trimmed.len() == 4
&& trimmed.starts_with(|c: char| c.is_ascii_uppercase())
})
.count();
assert_eq!(
declared,
every().len(),
"`Op` declares {declared} variants and the operation table lists {}",
every().len()
);
}
const OPERATIONS: usize = 25;
#[expect(
clippy::too_many_lines,
reason = "a table, one row per operation; it grows with the enum"
)]
fn operations() -> [(Op<'static>, Outcome, Option<Direction>, Answer, bool); OPERATIONS] {
[
(Op::ReachableTags, Verification, None, Sometimes, false),
(Op::AllTags, Verification, None, Sometimes, false),
(Op::IsShallow, Verification, None, Always, false),
(Op::TagOptRemotes, Verification, None, Always, false),
(Op::RemoteNames, Verification, None, Sometimes, false),
(
Op::AdvertisedTags { remote: "origin" },
Verification,
Some(Direction::Fetch),
Sometimes,
false,
),
(
Op::ChangedPaths { from: "v1.0.0" },
Verification,
None,
Sometimes,
false,
),
(Op::Head, Action, None, Always, false),
(
Op::RemoteUrl { remote: "origin" },
Action,
None,
Always,
false,
),
(Op::RemoteUrls, Action, None, Sometimes, false),
(Op::MergeBase { tip: "main" }, Action, None, Always, false),
(
Op::Commits { from: "v1.0.0" },
Action,
None,
Sometimes,
true,
),
(
Op::CommitPaths { hash: "cafebabe" },
Action,
None,
Sometimes,
false,
),
(
Op::CommitParents { hash: "cafebabe" },
Action,
None,
Always,
false,
),
(
Op::LocalTagCommit { tag: "v1.0.0" },
Action,
None,
Always,
false,
),
(Op::WorktreeStatus, Action, None, Sometimes, false),
(
Op::CommitMessage { commit: "HEAD" },
Action,
None,
Sometimes,
true,
),
(
Op::RefExists {
reference: "refs/tags/v1.0.0",
},
Action,
None,
Always,
false,
),
(
Op::ValidRefName {
reference: "v1.0.0",
},
Action,
None,
Never,
false,
),
(
Op::WorkflowTree {
commit: fixture_commit(),
},
Verification,
None,
Sometimes,
false,
),
(
Op::BlobText {
commit: fixture_commit(),
path: ".github/workflows/release.yml",
},
Verification,
None,
Sometimes,
false,
),
(
Op::TreeEntry {
commit: fixture_commit(),
path: "CHANGELOG.md",
},
Verification,
None,
Sometimes,
false,
),
(
Op::FileAddedBy {
path: ".changeset/one.md",
},
Verification,
None,
Sometimes,
false,
),
(
Op::AnnotatedTag {
name: "v1.0.0",
commit: fixture_commit(),
},
Action,
None,
Never,
false,
),
(
Op::PushTag {
remote: "origin",
tag: "v1.0.0",
},
Action,
Some(Direction::Push),
Never,
false,
),
]
}
fn every() -> [Op<'static>; OPERATIONS] {
operations().map(|(op, ..)| op)
}
#[test]
fn every_operation_states_every_axis() {
for (op, outcome, contacts, answer, lossy) in operations() {
let shape = op.shape();
assert_eq!(shape.spec.outcome, outcome, "{op:?} outcome");
assert_eq!(
shape.contact.map(|contact| contact.direction),
contacts,
"{op:?} contacts"
);
assert_eq!(shape.spec.answer, answer, "{op:?} answer");
assert_eq!(shape.spec.lossy, lossy, "{op:?} lossy");
}
}
#[test]
fn a_failure_names_what_it_was_pointed_at() {
assert_eq!(
Op::AdvertisedTags { remote: "upstream" }
.shape()
.operand
.as_deref(),
Some("upstream")
);
assert_eq!(
Op::ChangedPaths { from: "v1.0.0" }
.shape()
.operand
.as_deref(),
Some("v1.0.0...HEAD")
);
assert_eq!(Op::ReachableTags.shape().operand, None);
}
}