mod env;
#[cfg(test)]
mod fake;
mod op;
mod reach;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::{Mutex, OnceLock};
use cap_std::fs::Dir;
use super::CliError;
pub(super) use op::Op;
use op::{Answer, Contact, Direction, OpShape, SKIP_CHECKS_ATOM};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Reads {
Text,
Paths,
}
const TRACE2: [&str; 3] = ["GIT_TRACE2", "GIT_TRACE2_EVENT", "GIT_TRACE2_PERF"];
fn traces_to_a_file(value: &std::ffi::OsStr) -> bool {
Path::new(value).is_absolute()
}
pub(super) fn untrace(command: &mut Command) {
untrace_from(command, std::env::vars_os());
}
fn untrace_from(
command: &mut Command,
env: impl IntoIterator<Item = (std::ffi::OsString, std::ffi::OsString)>,
) {
let mut keeps_a_file = [false; TRACE2.len()];
for (name, value) in env {
let Some(name) = name.to_str() else { continue };
if !name.starts_with("GIT_TRACE") {
continue;
}
let to_a_file = traces_to_a_file(&value);
if let Some(at) = TRACE2.iter().position(|trace2| *trace2 == name) {
keeps_a_file[at] = to_a_file;
}
if !to_a_file {
command.env_remove(name);
}
}
for (at, name) in TRACE2.iter().enumerate() {
if !keeps_a_file[at] {
command.env(name, "0");
}
}
}
fn hides_part_of_the_tree(said: &str) -> bool {
let said = said.to_ascii_lowercase();
[
"could not open directory",
"cannot opendir",
"opendir(",
"cannot lstat",
]
.iter()
.any(|form| said.contains(form))
}
fn split_nul_paths(stdout: &[u8]) -> Option<Vec<String>> {
stdout
.split(|byte| *byte == 0)
.filter(|record| !record.is_empty())
.map(|record| String::from_utf8(record.to_vec()).ok())
.collect()
}
#[derive(Debug)]
pub(super) struct Reply {
code: Option<i32>,
stdout: Vec<u8>,
stderr: Vec<u8>,
}
impl Reply {
fn succeeded(&self) -> bool {
self.code == Some(0)
}
fn spoke(&self, reads: Reads) -> bool {
match reads {
Reads::Text => !String::from_utf8_lossy(&self.stdout).trim().is_empty(),
Reads::Paths => self
.stdout
.split(|byte| *byte == 0)
.any(|record| !record.is_empty()),
}
}
fn said_no(&self) -> bool {
self.code == Some(1) && self.stdout.is_empty() && self.stderr.is_empty()
}
fn diagnostic(&self) -> Option<String> {
let wrote = |bytes: &[u8]| {
let text = String::from_utf8_lossy(bytes).trim().to_owned();
(!text.is_empty()).then_some(text)
};
wrote(&self.stderr).or_else(|| (!self.succeeded()).then(|| wrote(&self.stdout)).flatten())
}
fn detail(&self) -> String {
let status = match self.code {
Some(code) => format!("exit {code}"),
None => String::from("terminated by a signal"),
};
match self.diagnostic() {
Some(said) => format!("{status}: {said}"),
None => format!("{status} with no diagnostic"),
}
}
}
impl From<std::process::Output> for Reply {
fn from(output: std::process::Output) -> Self {
Self {
code: output.status.code(),
stdout: output.stdout,
stderr: output.stderr,
}
}
}
#[cfg(test)]
impl Reply {
pub(super) fn said(stdout: impl Into<Vec<u8>>) -> Self {
Self {
code: Some(0),
stdout: stdout.into(),
stderr: Vec::new(),
}
}
pub(super) fn absent() -> Self {
Self {
code: Some(1),
stdout: Vec::new(),
stderr: Vec::new(),
}
}
pub(super) fn warned(stderr: &str) -> Self {
Self {
code: Some(0),
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
}
}
pub(super) fn said_and_warned(stdout: impl Into<Vec<u8>>, stderr: &str) -> Self {
Self {
code: Some(0),
stdout: stdout.into(),
stderr: stderr.as_bytes().to_vec(),
}
}
pub(super) fn failed(code: i32, stderr: &str) -> Self {
assert!(
code != 0,
"a failure exits non-zero; exit 0 is `said` or `warned`"
);
assert!(
!stderr.is_empty(),
"a diagnosed failure writes a diagnostic; exit 1 with nothing written is `absent`"
);
Self {
code: Some(code),
stdout: Vec::new(),
stderr: stderr.as_bytes().to_vec(),
}
}
pub(super) fn exactly(code: Option<i32>, stdout: &[u8], stderr: &[u8]) -> Self {
Self {
code,
stdout: stdout.to_vec(),
stderr: stderr.to_vec(),
}
}
pub(super) fn was_signalled() -> Self {
Self {
code: None,
stdout: Vec::new(),
stderr: Vec::new(),
}
}
}
enum Runner {
Child,
#[cfg(test)]
Fake(fake::Fake),
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Commit(String);
#[derive(Debug)]
pub(super) enum BlobKind {
Absent,
Symlink(String),
Other,
}
impl Commit {
pub(super) fn as_str(&self) -> &str {
&self.0
}
pub(super) fn from_advertised(sha: &str) -> Result<Self, CliError> {
if sha.is_empty() {
return Err(CliError::unverified(
"unverified: ls-remote advertised an empty commit id",
));
}
Ok(Self(sha.to_owned()))
}
}
#[derive(Debug)]
pub(super) struct CommitText {
pub(super) message: String,
pub(super) skip_checks: String,
}
pub(super) struct Git {
repo: PathBuf,
held: Option<Dir>,
runner: Runner,
transport: OnceLock<std::sync::Arc<Result<env::BatchSsh, env::TransportUnknown>>>,
reach_by_remote: Mutex<BTreeMap<(String, Direction), reach::Reach>>,
warned: Mutex<BTreeSet<String>>,
}
impl Git {
pub(super) fn at(repo: impl Into<PathBuf>) -> Self {
Self::new(repo.into(), Runner::Child, None)
}
pub(super) fn at_repository(
repo: &super::repository::Repository,
) -> Result<Self, Box<dyn std::error::Error>> {
let path = repo.ambient_path()?.to_path_buf();
let held = repo.dir().try_clone().map_err(|err| {
CliError::new(format!("failed to clone the repository capability: {err}"))
})?;
Ok(Self::new(path, Runner::Child, Some(held)))
}
#[cfg(test)]
pub(super) fn answering(replies: impl IntoIterator<Item = (&'static str, Reply)>) -> Self {
Self::answering_over(
Ok(env::BatchSsh::Composed(String::from(
"ssh -o BatchMode=yes",
))),
replies,
)
}
#[cfg(test)]
fn answering_over(
transport: Result<env::BatchSsh, env::TransportUnknown>,
replies: impl IntoIterator<Item = (&'static str, Reply)>,
) -> Self {
Self::new(
PathBuf::new(),
Runner::Fake(fake::Fake::answering(transport, replies)),
None,
)
}
fn new(repo: PathBuf, runner: Runner, held: Option<Dir>) -> Self {
Self {
repo,
held,
runner,
transport: OnceLock::new(),
reach_by_remote: Mutex::new(BTreeMap::new()),
warned: Mutex::new(BTreeSet::new()),
}
}
#[cfg(test)]
pub(super) fn asked(&self) -> Vec<String> {
match &self.runner {
Runner::Fake(fake) => fake.asked(),
Runner::Child => panic!("only a scripted Git records what it was asked"),
}
}
#[cfg(test)]
pub(super) fn said(&self) -> Vec<String> {
match &self.runner {
Runner::Fake(fake) => fake.heard(),
Runner::Child => panic!("only a scripted Git records what it said"),
}
}
pub(super) fn blob_kind(&self, commit: &Commit, path: &str) -> Result<BlobKind, CliError> {
let entries = self.paths(Op::TreeEntry { commit, path })?;
let Some(entry) = entries.first() else {
return Ok(BlobKind::Absent);
};
if entry.starts_with("120000 ") {
let target = self.text(Op::BlobText { commit, path })?;
return Ok(BlobKind::Symlink(target));
}
Ok(BlobKind::Other)
}
pub(super) fn raw_text(&self, op: Op<'_>) -> Result<String, CliError> {
let shape = op.shape();
let reply = self.checked(&shape, Reads::Text)?;
String::from_utf8(reply.stdout).map_err(|_| shape.fail("output is not valid UTF-8"))
}
pub(super) fn text(&self, op: Op<'_>) -> Result<String, CliError> {
let shape = op.shape();
let reply = self.checked(&shape, Reads::Text)?;
if shape.spec.lossy {
return Ok(String::from_utf8_lossy(&reply.stdout).trim().to_owned());
}
String::from_utf8(reply.stdout)
.map(|text| text.trim().to_owned())
.map_err(|_| shape.fail("output is not valid UTF-8"))
}
pub(super) fn head(&self) -> Result<Commit, CliError> {
self.text(Op::Head).map(Commit)
}
pub(super) fn tag_commit(&self, tag: &str) -> Result<Option<Commit>, CliError> {
Ok(self.optional_text(Op::LocalTagCommit { tag })?.map(Commit))
}
pub(super) fn blob(&self, op: Op<'_>) -> Result<String, CliError> {
let shape = op.shape();
let reply = self.checked(&shape, Reads::Text)?;
String::from_utf8(reply.stdout).map_err(|_| shape.fail("blob is not valid UTF-8"))
}
pub(super) fn paths(&self, op: Op<'_>) -> Result<Vec<String>, CliError> {
let shape = op.shape();
let stdout = self.checked(&shape, Reads::Paths)?.stdout;
split_nul_paths(&stdout).ok_or_else(|| {
shape.fail(
"listed a path that is not valid UTF-8; oakum cannot attribute it to a package",
)
})
}
pub(super) fn run(&self, op: Op<'_>) -> Result<(), CliError> {
self.checked(&op.shape(), Reads::Text)?;
Ok(())
}
pub(super) fn predicate(&self, op: Op<'_>) -> Result<bool, CliError> {
let shape = op.shape();
let reply = self.answered(&shape, Reads::Text)?;
if reply.succeeded() {
return Ok(true);
}
if reply.said_no() {
return Ok(false);
}
Err(shape.fail(&reply.detail()))
}
pub(super) fn matched_paths(&self, op: Op<'_>) -> Result<Option<Vec<String>>, CliError> {
let shape = op.shape();
let reply = self.answered(&shape, Reads::Paths)?;
if !reply.succeeded() {
if reply.said_no() {
return Ok(None);
}
return Err(shape.fail(&reply.detail()));
}
split_nul_paths(&reply.stdout).map(Some).ok_or_else(|| {
shape.fail("listed a path that is not valid UTF-8; oakum cannot name it as a gate")
})
}
pub(super) fn optional_text(&self, op: Op<'_>) -> Result<Option<String>, CliError> {
let shape = op.shape();
let reply = self.answered(&shape, Reads::Text)?;
if !reply.succeeded() {
if reply.said_no() {
return Ok(None);
}
return Err(shape.fail(&reply.detail()));
}
let text =
String::from_utf8(reply.stdout).map_err(|_| shape.fail("output is not valid UTF-8"))?;
Ok(Some(text.trim().to_owned()).filter(|text| !text.is_empty()))
}
fn checked(&self, shape: &OpShape<'_>, reads: Reads) -> Result<Reply, CliError> {
let reply = self.answered(shape, reads)?;
if reply.succeeded() {
return Ok(reply);
}
Err(shape.fail(&reply.detail()))
}
fn answered(&self, shape: &OpShape<'_>, reads: Reads) -> Result<Reply, CliError> {
let reply = self.child(shape)?;
if shape.spec.answer == Answer::Whole && reply.succeeded() {
if let Some(said) = reply
.diagnostic()
.filter(|said| hides_part_of_the_tree(said))
{
return Err(shape.phrase(|what| {
format!("git {what} may have listed only part of the tree, reporting: {said}")
}));
}
}
if !reply.succeeded() || reply.spoke(reads) {
return Ok(reply);
}
match shape.spec.answer {
Answer::Always => Err(Self::unanswered(shape, &reply)),
Answer::Sometimes if reply.diagnostic().is_some() => {
Err(Self::unanswered(shape, &reply))
}
Answer::Sometimes | Answer::Never | Answer::Whole => Ok(reply),
}
}
pub(super) fn commit_text(&self, commit: &str) -> Result<CommitText, CliError> {
let raw = self.text(Op::CommitMessage { commit })?;
let Some((message, trailers)) = raw.split_once('\0') else {
return Err(CliError::new(format!(
"git log for `{commit}` omitted the trailer separator oakum's \
format requests"
)));
};
if trailers.trim() == SKIP_CHECKS_ATOM && !message.contains(SKIP_CHECKS_ATOM) {
return Err(CliError::new(format!(
"this git did not parse the skip-checks trailers for \
`{commit}`; oakum cannot tell whether the commit suppresses \
CI"
)));
}
Ok(CommitText {
message: message.to_owned(),
skip_checks: trailers.to_owned(),
})
}
fn transport(&self) -> Result<&env::BatchSsh, &env::TransportUnknown> {
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
type Resolved =
Mutex<HashMap<std::path::PathBuf, Arc<Result<env::BatchSsh, env::TransportUnknown>>>>;
static RESOLVED: OnceLock<Resolved> = OnceLock::new();
#[cfg(test)]
if let Runner::Fake(fake) = &self.runner {
return fake.transport();
}
self.transport
.get_or_init(|| {
let mut resolved = RESOLVED
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
resolved
.entry(self.repo.clone())
.or_insert_with(|| Arc::new(env::batch_transport(&self.repo)))
.clone()
})
.as_ref()
.as_ref()
}
fn say_once(&self, note: &str) {
match &self.runner {
Runner::Child => {
self.say_once_with(note, env::warn);
}
#[cfg(test)]
Runner::Fake(fake) => {
self.say_once_with(note, |note| fake.hear(note));
}
}
}
fn say_once_with(&self, note: &str, say: impl FnOnce(&str) -> bool) -> bool {
let key = note.to_owned();
let mut warned = self
.warned
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if !warned.insert(key.clone()) {
return false;
}
let said = say(note);
if !said {
warned.remove(&key);
}
said
}
fn remote_reach(&self, contact: Contact<'_>) -> reach::Reach {
let key = contact.key();
if let Some(answer) = self.remembered_reach(&key) {
return answer;
}
let parsed = self.text(Op::RemoteNames).and_then(|names| {
let names: Vec<&str> = names.lines().collect();
let listing = self.text(Op::RemoteUrls)?;
reach::parse_remote_urls(&listing, &names)
});
let mut cache = self
.reach_by_remote
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let answer = match parsed {
Ok(urls) => {
for (entry, urls) in urls {
cache.insert(entry, reach::classify(Ok(&urls)));
}
cache.get(&key).cloned().unwrap_or_else(|| {
let direction = match contact.direction {
Direction::Fetch => "fetch",
Direction::Push => "push",
};
reach::classify(Err(&CliError::new(format!(
"the listing shows no {direction} URL for remote {:?}",
contact.remote
))))
})
}
Err(err) => reach::classify(Err(&err)),
};
cache.insert(key, answer.clone());
answer
}
fn remembered_reach(&self, key: &(String, Direction)) -> Option<reach::Reach> {
self.reach_by_remote
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(key)
.cloned()
}
fn child(&self, shape: &OpShape<'_>) -> Result<Reply, CliError> {
if let Some(held) = &self.held {
super::repository::confirm_ambient(held, &self.repo)
.map_err(|err| shape.fail(&err.to_string()))?;
}
let batch = self
.transport()
.map_err(|unknown| shape.unreadable_transport(unknown))?;
if let Some(contact) = shape.contact {
let reach = self.remote_reach(contact);
for note in reach::notes_for(contact, &reach, batch) {
self.say_once(¬e);
}
}
self.spawn(shape, batch)
}
fn spawn(&self, shape: &OpShape<'_>, batch: &env::BatchSsh) -> Result<Reply, CliError> {
match &self.runner {
Runner::Child => {
let args: Vec<&str> = shape.argv.iter().map(String::as_str).collect();
env::deadlined_command(&self.repo, &args, batch)
.output()
.map(Reply::from)
.map_err(|failure| shape.fail(&failure.to_string()))
}
#[cfg(test)]
Runner::Fake(fake) => Ok(fake.answer(shape.name)),
}
}
fn unanswered(shape: &OpShape<'_>, reply: &Reply) -> CliError {
shape.phrase(|what| match reply.diagnostic() {
Some(said) => format!("git {what} answered nothing while reporting: {said}"),
None => format!("git {what} exited 0 without answering"),
})
}
}
#[cfg(test)]
mod tests {
use super::env::{BatchSsh, TransportUnknown};
use super::op::fixture_commit;
use super::{split_nul_paths, CliError, Contact, Direction, Git, Op, Reply};
const SSH_URL: &str = "git@example.invalid:demo/demo.git";
const HTTPS_URL: &str = "https://example.invalid/demo/demo.git";
const HELPER_URL: &str = "ext::ssh -p 22 git@example.invalid %S demo.git";
const WORKTREE: &str = "status --porcelain -z";
#[test]
fn a_whole_listing_that_names_unread_tree_is_refused() {
let err = Git::answering([(
WORKTREE,
Reply::said_and_warned(
" M alpha/src/lib.rs\0",
"warning: could not open directory 'beta/hidden/': Permission denied",
),
)])
.paths(Op::UncommittedPaths)
.expect_err("refused");
assert_eq!(err.exit_code(), 2, "{err}");
assert!(err.to_string().contains("only part of the tree"), "{err}");
}
#[test]
fn a_whole_listing_is_kept_when_the_warning_is_not_about_unread_tree() {
assert_eq!(
Git::answering([(
WORKTREE,
Reply::said_and_warned(
" M alpha/src/lib.rs\0",
"warning: unable to access '.git/info/exclude': Permission denied",
),
)])
.paths(Op::UncommittedPaths)
.expect("kept"),
[" M alpha/src/lib.rs"]
);
}
#[test]
fn every_shape_of_unread_tree_is_recognised() {
for said in [
"cannot lstat 'beta/x'",
"Cannot lstat 'beta/x'",
"cannot opendir 'beta/hidden'",
"cannot opendir beta/hidden",
"warning: could not open directory 'beta/hidden/': Permission denied",
"Could not open directory beta/hidden",
"opendir('beta/hidden') failed",
] {
let err = Git::answering([(
WORKTREE,
Reply::said_and_warned(" M alpha/src/lib.rs\0", said),
)])
.paths(Op::UncommittedPaths)
.expect_err(said);
assert!(
err.to_string().contains("only part of the tree"),
"{said}: {err}"
);
}
}
#[test]
fn a_whole_listing_that_failed_outright_is_not_called_partial() {
let err = Git::answering([(
WORKTREE,
Reply::failed(128, "fatal: cannot opendir 'beta/hidden'"),
)])
.paths(Op::UncommittedPaths)
.expect_err("refused");
assert_eq!(err.exit_code(), 2, "{err}");
assert!(err.to_string().contains("failed: exit 128"), "{err}");
assert!(
!err.to_string().contains("only part of the tree"),
"it listed none of it: {err}"
);
}
fn at_remote(url: &str, replies: impl IntoIterator<Item = (&'static str, Reply)>) -> Git {
Git::answering(listing(url).into_iter().chain(replies))
}
fn listing(url: &str) -> [(&'static str, Reply); 2] {
[
("remote", Reply::said("origin")),
(
"remote -v",
Reply::said(format!("origin\t{url} (fetch)\norigin\t{url} (push)")),
),
]
}
fn advertised() -> (&'static str, Reply) {
("ls-remote --tags", Reply::said("cafe\trefs/tags/v1.0.0\n"))
}
fn opaque() -> BatchSsh {
BatchSsh::Unprotected(String::from(
"GIT_SSH names `my-ssh`, which takes its arguments from git, not from oakum",
))
}
#[test]
fn exit_one_with_nothing_written_is_how_git_says_absent() {
assert_eq!(
Git::answering([("config --get-regexp tagopt", Reply::absent())])
.optional_text(Op::TagOptRemotes)
.expect("absent"),
None
);
assert!(!Git::answering([("rev-parse --verify", Reply::absent())])
.predicate(Op::RefExists {
reference: "refs/tags/v1.0.0",
})
.expect("absent"));
}
#[test]
fn only_exit_one_with_both_streams_empty_means_absent() {
let diagnosed = Git::answering([(
"config --get-regexp tagopt",
Reply::failed(1, "fatal: not a git repository"),
)])
.optional_text(Op::TagOptRemotes)
.expect_err("a diagnosed exit must not read as absence");
assert!(
matches!(diagnosed, CliError::Unverified { .. }),
"{diagnosed:?}"
);
assert!(
diagnosed.to_string().contains("not a git repository"),
"{diagnosed}"
);
let silent = Git::answering([(
"config --get-regexp tagopt",
Reply::exactly(Some(128), b"", b""),
)])
.optional_text(Op::TagOptRemotes)
.expect_err("exit 128 is not exit 1");
assert!(silent.to_string().contains("exit 128"), "{silent}");
let spoke = Git::answering([(
"config --get-regexp tagopt",
Reply::exactly(Some(1), b"remote.origin.tagopt --no-tags", b""),
)])
.optional_text(Op::TagOptRemotes)
.expect_err("a child that wrote an answer did not say no");
assert!(spoke.to_string().contains("exit 1"), "{spoke}");
let killed = Git::answering([("rev-parse --verify", Reply::was_signalled())])
.predicate(Op::RefExists {
reference: "refs/tags/v1.0.0",
})
.expect_err("a signal is not an answer of no");
assert!(
killed.to_string().contains("terminated by a signal"),
"{killed}"
);
}
#[test]
fn a_cached_transport_failure_is_repeated_verbatim() {
let git = Git::at("/nonexistent");
git.transport
.set(
Err(super::env::TransportUnknown::SshConfig(String::from(
"git config was killed by a signal",
)))
.into(),
)
.expect("the cache starts empty");
for _ in 0..3 {
assert_eq!(
git.transport().expect_err("a cached failure").detail(),
"git config was killed by a signal"
);
}
let raised = Op::AdvertisedTags { remote: "origin" }
.shape()
.unreadable_transport(&super::env::TransportUnknown::SshConfig(String::from(
"git config was killed by a signal",
)));
assert!(matches!(raised, CliError::Unverified { .. }), "{raised:?}");
assert!(
raised.to_string().contains("killed by a signal"),
"{raised}"
);
}
#[test]
fn only_a_trace_that_names_a_file_is_left_in_place() {
for value in ["1", "2", "true", "relative.log", ""] {
assert!(
!super::traces_to_a_file(std::ffi::OsStr::new(value)),
"{value:?} reaches our stderr"
);
}
let file = std::env::temp_dir().join("oakum-trace.event");
assert!(super::traces_to_a_file(file.as_os_str()));
}
#[test]
fn untrace_silences_every_channel_and_leaves_the_rest_alone() {
let file = std::env::temp_dir().join("oakum-trace.perf");
let inherited = [
(
std::ffi::OsString::from("GIT_TRACE"),
std::ffi::OsString::from("1"),
),
(
std::ffi::OsString::from("GIT_TRACE_PACKET"),
std::ffi::OsString::from("1"),
),
(
std::ffi::OsString::from("GIT_TRACE_A_CHANNEL_ADDED_LATER"),
std::ffi::OsString::from("1"),
),
(
std::ffi::OsString::from("GIT_TRACE2_EVENT"),
std::ffi::OsString::from("relative.log"),
),
(
std::ffi::OsString::from("GIT_TRACE2_PERF"),
file.into_os_string(),
),
];
let mut command = std::process::Command::new("git");
command.env("GIT_TERMINAL_PROMPT", "0");
super::untrace_from(&mut command, inherited);
let envs: Vec<(String, Option<String>)> = command
.get_envs()
.map(|(name, value)| {
(
name.to_string_lossy().into_owned(),
value.map(|value| value.to_string_lossy().into_owned()),
)
})
.collect();
let setting = |name: &str| {
envs.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.clone())
};
for name in [
"GIT_TRACE",
"GIT_TRACE_PACKET",
"GIT_TRACE_A_CHANNEL_ADDED_LATER",
] {
assert_eq!(setting(name), Some(None), "{name} still reaches the child");
}
assert_eq!(
setting("GIT_TRACE2_EVENT"),
Some(Some(String::from("0"))),
"config-driven trace2 is still live"
);
assert_eq!(
setting("GIT_TRACE2_PERF"),
None,
"a trace2 file target was overridden"
);
assert_eq!(
setting("GIT_TERMINAL_PROMPT"),
Some(Some(String::from("0")))
);
}
#[test]
#[should_panic(expected = "nothing scripted answers")]
fn a_command_that_only_shares_a_character_prefix_does_not_answer() {
let git = Git::answering([(
"rev-parse --verify --quiet refs/tags/v1.0.0",
Reply::said("cafebabe"),
)]);
let _ = git.optional_text(Op::LocalTagCommit { tag: "v1.0.0" });
}
#[test]
fn a_child_that_always_prints_and_printed_nothing_is_refused_on_every_accessor() {
let warning = "warning: unable to access '/etc/gitconfig': Permission denied";
let asked = Git::answering([("config --get-regexp tagopt", Reply::warned(warning))])
.optional_text(Op::TagOptRemotes)
.expect_err("optional_text");
assert!(matches!(asked, CliError::Unverified { .. }), "{asked:?}");
assert!(asked.to_string().contains("Permission denied"), "{asked}");
let voted = Git::answering([("rev-parse --verify", Reply::warned(warning))])
.predicate(Op::RefExists {
reference: "refs/tags/v1.0.0",
})
.expect_err("predicate");
assert!(voted.to_string().contains("answered nothing"), "{voted}");
let read = Git::answering([("rev-parse HEAD", Reply::warned(warning))])
.text(Op::Head)
.expect_err("text");
assert!(read.to_string().contains("Permission denied"), "{read}");
let mute = Git::answering([(
"config --get-regexp tagopt",
Reply::exactly(Some(0), b"", b""),
)])
.optional_text(Op::TagOptRemotes)
.expect_err("silence is not absence");
assert!(
mute.to_string().contains("exited 0 without answering"),
"{mute}"
);
}
#[test]
fn a_verification_that_reported_nothing_while_warning_is_not_an_empty_look() {
let err = Git::answering([(
"for-each-ref --merged HEAD",
Reply::warned("warning: refname 'v1.0.0' is ambiguous"),
)])
.text(Op::ReachableTags)
.expect_err("a warned look must not read as no tags");
assert!(matches!(err, CliError::Unverified { .. }), "{err:?}");
assert!(err.to_string().contains("ambiguous"), "{err}");
}
#[test]
fn a_refusal_gate_that_never_looked_is_not_a_clean_answer() {
for (command, op) in [
("status --porcelain", Op::WorktreeStatus),
("log -1", Op::CommitMessage { commit: "HEAD" }),
("diff-tree", Op::CommitPaths { hash: "cafebabe" }),
] {
let err = Git::answering([(command, Reply::warned("fatal: could not read index"))])
.text(op)
.expect_err("{op:?} must not read as an empty answer");
assert!(err.to_string().contains("could not read index"), "{err}");
}
}
#[test]
fn work_that_answers_through_its_exit_code_is_not_refused_for_writing_to_stderr() {
at_remote(
SSH_URL,
[(
"push",
Reply::warned("To github.com:oakoss/oakum.git\n * [new tag] v1.0.0 -> v1.0.0"),
)],
)
.run(Op::PushTag {
remote: "origin",
tag: "v1.0.0",
})
.expect("push reports through stderr on success");
assert!(Git::answering([(
"check-ref-format",
Reply::warned("warning: unable to access '/etc/gitconfig'"),
)])
.predicate(Op::ValidRefName {
reference: "v1.0.0",
})
.expect("check-ref-format reports through its exit code"));
}
#[test]
fn a_non_utf8_path_fails_in_the_operations_own_voice() {
let err = Git::answering([("diff --name-only", Reply::said(b"pkg/\xff.bin\0".to_vec()))])
.paths(Op::ChangedPaths { from: "v1.0.0" })
.expect_err("a non-UTF-8 path cannot name a package");
assert!(
err.to_string().contains("cannot attribute it to a package"),
"{err}"
);
assert!(
matches!(err, CliError::Unverified { .. }),
"`diff --name-only` is a verification: {err:?}"
);
}
#[test]
fn each_accessor_draws_the_silence_line_where_it_reads() {
for stdout in ["\u{0B}", "\u{A0}", "\u{2028}"] {
let err = Git::answering([(
"status --porcelain",
Reply::exactly(
Some(0),
stdout.as_bytes(),
b"fatal: could not read the index",
),
)])
.text(Op::WorktreeStatus)
.expect_err("whitespace is not a clean worktree");
assert!(
err.to_string().contains("could not read the index"),
"{err}"
);
}
let listed = Git::answering([(
"diff --name-only",
Reply::exactly(
Some(0),
b" \0",
b"warning: unable to access '/etc/gitconfig'",
),
)])
.paths(Op::ChangedPaths { from: "v1.0.0" })
.expect("a whitespace filename is a filename");
assert_eq!(listed, [" "]);
let none = Git::answering([(
"diff --name-only",
Reply::exactly(
Some(0),
b"\0\0",
b"warning: unable to access '/etc/gitconfig'",
),
)])
.paths(Op::ChangedPaths { from: "v1.0.0" })
.expect_err("empty records listed nothing");
assert!(none.to_string().contains("answered nothing"), "{none}");
let absent = Git::answering([("rev-parse --verify refs/tags", Reply::said(" \n"))])
.optional_text(Op::LocalTagCommit { tag: "v1.0.0" })
.expect_err("whitespace is not a commit");
assert!(absent.to_string().contains("without answering"), "{absent}");
assert_eq!(
Git::answering([("remote", Reply::exactly(Some(0), b"", b" \n"))])
.text(Op::RemoteNames)
.expect("a blank diagnostic is not a diagnostic"),
""
);
}
#[test]
fn whitespace_on_stdout_is_not_an_answer() {
let err = Git::answering([(
"config --get-regexp tagopt",
Reply::exactly(Some(0), b" \n\t", b"fatal: bad config line 9"),
)])
.optional_text(Op::TagOptRemotes)
.expect_err("whitespace is not an answer");
assert!(err.to_string().contains("bad config line 9"), "{err}");
let looked = Git::answering([(
"status --porcelain",
Reply::exactly(Some(0), b"\n", b"fatal: could not read index"),
)])
.text(Op::WorktreeStatus)
.expect_err("nor for a gate whose empty answer means clean");
assert!(
looked.to_string().contains("could not read index"),
"{looked}"
);
}
#[test]
fn a_child_that_answered_or_had_nothing_to_answer_is_not_refused() {
let listed = Git::answering([(
"for-each-ref --merged HEAD",
Reply::said_and_warned(
"refs/tags/v1.0.0\0commit\0cafebabe\0\0",
"warning: ignoring broken ref refs/tags/junk",
),
)])
.text(Op::ReachableTags)
.expect("a warning alongside an answer leaves the answer standing");
assert!(listed.contains("v1.0.0"), "{listed}");
at_remote(
SSH_URL,
[(
"push",
Reply::warned("To github.com:oakoss/oakum.git\n * [new tag] v1.0.0"),
)],
)
.run(Op::PushTag {
remote: "origin",
tag: "v1.0.0",
})
.expect("push reports through stderr on success");
}
#[test]
fn a_silent_failure_and_a_signal_do_not_render_alike() {
let silent = Git::answering([("rev-parse HEAD", Reply::exactly(Some(128), b"", b""))])
.text(Op::Head)
.expect_err("exit 128");
assert!(
silent.to_string().contains("exit 128 with no diagnostic"),
"{silent}"
);
let killed = Git::answering([("rev-parse HEAD", Reply::was_signalled())])
.text(Op::Head)
.expect_err("signalled");
assert!(
killed.to_string().contains("terminated by a signal"),
"{killed}"
);
let banner = at_remote(
SSH_URL,
[(
"push",
Reply::exactly(None, b"", b"To /private/tmp/origin.git\n"),
)],
)
.run(Op::PushTag {
remote: "origin",
tag: "v1.0.0",
})
.expect_err("a signal death with stderr");
assert!(
banner.to_string().contains("terminated by a signal"),
"{banner}"
);
assert!(
banner.to_string().contains("To /private/tmp/origin.git"),
"git's words stay as evidence: {banner}"
);
}
#[test]
fn only_a_lossy_read_accepts_bytes_that_are_not_utf8() {
let message = Git::answering([("log -1", Reply::said(b"fix: caf\xff\n".to_vec()))])
.text(Op::CommitMessage { commit: "HEAD" })
.expect("a commit message is read lossily");
assert_eq!(message, "fix: caf\u{fffd}");
let err = Git::answering([("rev-parse HEAD", Reply::said(b"\xff".to_vec()))])
.text(Op::Head)
.expect_err("an object name must be valid UTF-8");
assert!(err.to_string().contains("not valid UTF-8"), "{err}");
}
#[test]
fn a_failed_action_is_not_unverified() {
let err = Git::answering([("tag", Reply::failed(128, "fatal: tag already exists"))])
.run(Op::AnnotatedTag {
name: "v1.0.0",
commit: fixture_commit(),
})
.expect_err("tag failed");
assert!(matches!(err, CliError::Other(_)), "{err:?}");
}
#[test]
fn a_credential_starved_remote_failure_names_the_fix() {
for starved in [
"fatal: could not read Username for 'https://gitlab.com': prompts off",
"fatal: could not read Password for 'https://gitlab.com': prompts off",
"fatal: Authentication failed for 'https://gitlab.com/'",
"fatal: Username not available: terminal prompts disabled",
] {
let err = at_remote(
HTTPS_URL,
[("ls-remote --tags", Reply::failed(128, starved))],
)
.text(Op::AdvertisedTags { remote: "origin" })
.expect_err("a starved remote read fails");
let text = err.to_string();
assert!(text.contains(starved), "{text}");
assert!(text.contains("credential helper"), "{text}");
assert!(text.contains("gh auth setup-git"), "{text}");
assert!(text.starts_with("unverified:"), "{text}");
}
let err = at_remote(
SSH_URL,
[(
"ls-remote --tags",
Reply::failed(128, "fatal: repository not found"),
)],
)
.text(Op::AdvertisedTags { remote: "origin" })
.expect_err("an unrelated remote failure");
assert!(!err.to_string().contains("credential helper"), "{err}");
let starved =
"fatal: could not read Username for 'https://gitlab.com': terminal prompts disabled";
let err = Git::answering([("log -1", Reply::failed(128, starved))])
.text(Op::CommitMessage { commit: "HEAD" })
.expect_err("a local child never gets the note");
assert!(!err.to_string().contains("credential helper"), "{err}");
}
#[test]
fn the_unparsed_trailer_guard_spares_a_value_that_quotes_the_atom() {
let old_git = Git::answering([(
"log -1",
Reply::said(format!("chore: release\0{}\n", super::SKIP_CHECKS_ATOM)),
)]);
let err = old_git.commit_text("cafe").expect_err("old git refuses");
assert!(err.to_string().contains("did not parse"), "{err}");
let quoting = Git::answering([(
"log -1",
Reply::said(format!(
"chore: x\n\nskip-checks: {atom}\0{atom}\n",
atom = super::SKIP_CHECKS_ATOM
)),
)]);
let text = quoting
.commit_text("cafe")
.expect("a quoting value is a value");
assert_eq!(text.skip_checks.trim(), super::SKIP_CHECKS_ATOM);
}
#[test]
fn an_unlisted_remote_is_unread_not_safe() {
let git = Git::answering([
("remote", Reply::said("other")),
(
"remote -v",
Reply::said("other\thttps://host/r.git (fetch)"),
),
]);
let reach = git.remote_reach(Contact {
remote: "origin",
direction: Direction::Fetch,
});
let unread = reach.unread.expect("an unlisted remote is unread");
assert!(!reach.ssh && !reach.helper);
assert!(
unread.to_string().contains("shows no fetch URL"),
"{unread}"
);
}
#[test]
fn a_refused_note_stays_owed_until_it_lands() {
let git = Git::answering([]);
let mut offered = String::new();
assert!(
!git.say_once_with("a note", |note| {
offered.push_str(note);
false
}),
"a refused write must not report the note as said"
);
assert_eq!(offered, "a note", "the sayer is given the note verbatim");
assert!(
git.say_once_with("a note", |_| true),
"a refused note is still owed, so the next child may say it"
);
assert!(
!git.say_once_with("a note", |_| panic!("said twice")),
"once it lands it must not repeat, once per remote child"
);
}
#[test]
fn distinct_notes_say_themselves_and_identical_ones_do_not_repeat() {
let git = Git::answering([]);
assert!(git.say_once_with("fetch note", |_| true));
assert!(git.say_once_with("push note", |_| true));
assert!(!git.say_once_with("fetch note", |_| panic!("repeated")));
}
#[test]
fn an_unreadable_transport_stops_every_child_before_it_spawns() {
let git = Git::answering_over(
Err(TransportUnknown::SshConfig(String::from(
"fatal: unable to read config file",
))),
[
advertised(),
("push", Reply::warned("To example.invalid:demo/demo.git")),
("log -1", Reply::said("fix: typo\0\n")),
],
);
let looked = git
.text(Op::AdvertisedTags { remote: "origin" })
.expect_err("a look whose transport could not be resolved");
assert!(matches!(looked, CliError::Unverified { .. }), "{looked:?}");
let text = looked.to_string();
assert!(
text.contains(
"git ls-remote --tags origin needs an ssh configuration oakum could not read"
),
"{text}"
);
assert!(text.contains("unable to read config file"), "{text}");
assert!(text.contains("will not guess a transport"), "{text}");
let acted = git
.run(Op::PushTag {
remote: "origin",
tag: "v1.0.0",
})
.expect_err("a push that never ran");
assert!(matches!(acted, CliError::Other(_)), "{acted:?}");
let local = git
.commit_text("HEAD")
.expect_err("a local child carries the transport too");
assert!(
local
.to_string()
.contains("git log -1 HEAD needs an ssh configuration"),
"{local}"
);
assert!(
git.asked().is_empty(),
"no child may spawn without a resolved transport: {:?}",
git.asked()
);
assert!(git.said().is_empty(), "{:?}", git.said());
}
#[test]
fn a_local_child_reads_no_remote_listing() {
let git = Git::answering([("log -1", Reply::said("fix: typo\0\n"))]);
git.commit_text("HEAD").expect("a local read");
assert_eq!(git.asked(), ["log -1"]);
assert!(git.said().is_empty(), "{:?}", git.said());
}
#[test]
fn a_helper_remote_owes_its_note_under_a_composed_transport() {
let git = at_remote(HELPER_URL, [advertised()]);
git.text(Op::AdvertisedTags { remote: "origin" })
.expect("the look runs; the note is advisory");
let said = git.said();
assert_eq!(said.len(), 1, "{said:?}");
assert!(
said[0].contains("\"origin\" runs a helper command oakum cannot inspect"),
"{said:?}"
);
assert!(
!said[0].contains("could not be protected"),
"a composed transport owes no transport rider: {said:?}"
);
assert!(
!said[0].contains("could not read that remote's URL"),
"the note must not claim a read failed when it did not: {said:?}"
);
}
#[test]
fn only_an_ssh_remote_is_told_about_ssh_prompts() {
let quiet = Git::answering_over(
Ok(opaque()),
listing(HTTPS_URL).into_iter().chain([advertised()]),
);
quiet
.text(Op::AdvertisedTags { remote: "origin" })
.expect("an https look");
assert_eq!(
quiet.asked(),
["remote", "remote -v", "ls-remote --tags"],
"an absent note reads the same when no remote child ran"
);
assert!(quiet.said().is_empty(), "{:?}", quiet.said());
let told = Git::answering_over(
Ok(opaque()),
listing(SSH_URL).into_iter().chain([advertised()]),
);
told.text(Op::AdvertisedTags { remote: "origin" })
.expect("an ssh look");
let said = told.said();
assert_eq!(said.len(), 1, "{said:?}");
assert!(
said[0].contains("cannot refuse ssh prompts for the transport \"origin\" uses"),
"{said:?}"
);
assert!(said[0].contains("GIT_SSH names `my-ssh`"), "{said:?}");
}
#[test]
fn the_listing_is_read_once_and_a_note_said_once_per_run() {
let git = at_remote(
HELPER_URL,
[
advertised(),
("push", Reply::warned("To example.invalid:demo/demo.git")),
],
);
git.text(Op::AdvertisedTags { remote: "origin" })
.expect("the look");
git.run(Op::PushTag {
remote: "origin",
tag: "v1.0.0",
})
.expect("the push");
assert_eq!(
git.asked(),
["remote", "remote -v", "ls-remote --tags", "push"]
);
assert_eq!(git.said().len(), 1, "{:?}", git.said());
}
#[test]
fn an_unreadable_listing_still_gets_a_hedged_note() {
let unread = |transport| {
Git::answering_over(
transport,
[
("remote", Reply::said("origin")),
("remote -v", Reply::failed(2, "fatal: unreadable")),
advertised(),
],
)
};
let unprotected = unread(Ok(opaque()));
unprotected
.text(Op::AdvertisedTags { remote: "origin" })
.expect("the look still runs");
let said = unprotected.said();
assert_eq!(said.len(), 1, "{said:?}");
assert!(
said[0].contains("could not establish what transport \"origin\" uses"),
"{said:?}"
);
assert!(
said[0].contains("could not read that remote's URL"),
"{said:?}"
);
assert!(said[0].contains("fatal: unreadable"), "{said:?}");
assert!(
said[0].contains("could not be protected either: GIT_SSH names"),
"{said:?}"
);
assert!(
!said[0].contains("cannot refuse ssh prompts"),
"an unread URL is not an ssh URL: {said:?}"
);
let composed = unread(Ok(BatchSsh::Composed(String::from("ssh -o BatchMode=yes"))));
composed
.text(Op::AdvertisedTags { remote: "origin" })
.expect("the look still runs");
let said = composed.said();
assert_eq!(said.len(), 1, "{said:?}");
assert!(
said[0].contains("could not establish what transport"),
"{said:?}"
);
assert!(
!said[0].contains("could not be protected"),
"a composed transport owes no transport rider: {said:?}"
);
}
#[test]
fn a_repository_git_cannot_open_is_not_reported_as_an_ssh_problem() {
let refused = Op::AdvertisedTags { remote: "origin" }
.shape()
.unreadable_transport(&super::env::TransportUnknown::Repository(String::from(
"exit 128: fatal: Expected git repo version <= 1, found 99",
)))
.to_string();
assert!(
refused.contains("could not read this repository"),
"{refused}"
);
assert!(refused.contains("found 99"), "{refused}");
assert!(!refused.contains("ssh"), "{refused}");
assert!(!refused.contains("GIT_SSH_COMMAND"), "{refused}");
}
#[test]
fn an_unreadable_ssh_variable_is_not_answered_by_setting_it() {
let said = Op::AdvertisedTags { remote: "origin" }
.shape()
.unreadable_transport(&super::env::TransportUnknown::SshVariable(String::from(
"GIT_SSH_COMMAND is not valid UTF-8",
)))
.to_string();
assert!(
said.contains("GIT_SSH_COMMAND is not valid UTF-8"),
"{said}"
);
assert!(said.contains("repair or unset that variable"), "{said}");
assert!(
!said.contains("set both GIT_SSH_COMMAND and GIT_SSH_VARIANT"),
"circular: {said}"
);
}
#[test]
fn a_probe_that_never_reached_git_claims_neither_cause() {
let unasked = Op::AdvertisedTags { remote: "origin" }
.shape()
.unreadable_transport(&super::env::TransportUnknown::Unasked(String::from(
"could not run git: No such file or directory (os error 2)",
)))
.to_string();
assert!(unasked.contains("could not ask git"), "{unasked}");
assert!(unasked.contains("No such file or directory"), "{unasked}");
assert!(!unasked.contains("GIT_SSH_COMMAND"), "{unasked}");
assert!(
!unasked.contains("could not read this repository"),
"a probe that did not run says nothing about the repository: {unasked}"
);
}
#[test]
fn nul_records_are_preserved_exactly() {
let parsed = split_nul_paths(b"pkg/a b\0pkg/\n weird \0pkg/caf\xc3\xa9.rs\0")
.expect("valid utf-8 records");
assert_eq!(parsed, ["pkg/a b", "pkg/\n weird ", "pkg/caf\u{e9}.rs"]);
assert_eq!(split_nul_paths(b"").expect("empty"), Vec::<String>::new());
}
#[test]
fn a_non_utf8_record_is_refused_rather_than_lossily_rewritten() {
assert_eq!(split_nul_paths(b"pkg/\xff.bin\0"), None);
}
}