use std::fmt;
use std::io::{self, Write};
use std::path::Path;
use std::process::{Command, Output};
use std::time::Duration;
use oakum::discover::child::{output_within_reading, ChildFailure, Reach};
use super::Reply;
pub(super) struct DeadlinedGit(Command);
pub(super) enum RemoteFailure {
Spawn(io::Error),
BadDeadline(String),
Deadline {
limit: Duration,
reach: Reach,
},
DrainStalled {
limit: Duration,
status: std::process::ExitStatus,
},
Wait(io::Error, Reach),
Read(io::Error),
}
impl fmt::Display for RemoteFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Spawn(err) => write!(f, "could not run git: {err}"),
Self::BadDeadline(reason) => f.write_str(reason),
Self::Wait(err, reach) => write!(
f,
"git started but waiting on it failed ({err}); oakum {}",
reach.describe("it")
),
Self::Read(err) => {
write!(f, "git ran but its output could not be read: {err}")
}
Self::DrainStalled { limit, status } => write!(
f,
"git exited ({status}) but something it spawned still held its \
output open {}s later, so the answer could not be collected; a \
credential helper or an ssh control master is the likely cause. \
Set OAKUM_REMOTE_DEADLINE (seconds) to wait longer",
limit.as_secs()
),
Self::Deadline { limit, reach } => write!(
f,
"gave up after {}s with no answer and {}; a credential helper, an interactive \
ProxyCommand, or a signing program that prompts can \
block past every prompt oakum \
suppresses. Set OAKUM_REMOTE_DEADLINE (seconds) \
if this remote is legitimately slow",
limit.as_secs(),
reach.describe("git")
),
}
}
}
impl RemoteFailure {
pub(super) const fn left_no_answer(&self) -> bool {
!matches!(self, Self::Spawn(_))
}
}
impl From<ChildFailure> for RemoteFailure {
fn from(failure: ChildFailure) -> Self {
match failure {
ChildFailure::Spawn(err) => Self::Spawn(err),
ChildFailure::Deadline { limit, reach } => Self::Deadline { limit, reach },
ChildFailure::DrainStalled { limit, status } => Self::DrainStalled { limit, status },
ChildFailure::Wait(err, reach) => Self::Wait(err, reach),
ChildFailure::Read(err) => Self::Read(err),
}
}
}
impl DeadlinedGit {
pub(super) fn without_lazy_fetch(mut self) -> Self {
self.0.env("GIT_NO_LAZY_FETCH", "1");
self
}
pub(super) fn output(mut self, input: Option<&[u8]>) -> Result<Output, RemoteFailure> {
let limit = oakum::discover::child::deadline().map_err(RemoteFailure::BadDeadline)?;
Ok(output_within_reading(&mut self.0, limit, input)?)
}
}
pub(super) fn local_command(repo: &Path, args: &[&str]) -> Command {
let mut command = Command::new("git");
command
.args(args)
.current_dir(repo)
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_ASKPASS", "")
.env("LC_ALL", "C");
for name in PATHSPEC_SEMANTICS {
command.env_remove(name);
}
super::untrace(&mut command);
command
}
const PATHSPEC_SEMANTICS: [&str; 4] = [
"GIT_LITERAL_PATHSPECS",
"GIT_GLOB_PATHSPECS",
"GIT_NOGLOB_PATHSPECS",
"GIT_ICASE_PATHSPECS",
];
#[cfg(test)]
mod child_environment {
use super::local_command;
#[test]
fn every_child_is_spawned_in_one_language() {
let command = local_command(std::path::Path::new("."), &["status"]);
let pinned = command
.get_envs()
.find(|(name, _)| *name == std::ffi::OsStr::new("LC_ALL"))
.map(|(_, value)| value.map(std::ffi::OsStr::to_os_string));
assert_eq!(
pinned,
Some(Some(std::ffi::OsString::from("C"))),
"git's diagnostics are read, so the child cannot inherit a locale"
);
}
#[test]
fn every_child_drops_the_variables_that_reinterpret_pathspecs() {
let command = local_command(std::path::Path::new("."), &["status"]);
for name in [
"GIT_LITERAL_PATHSPECS",
"GIT_GLOB_PATHSPECS",
"GIT_NOGLOB_PATHSPECS",
"GIT_ICASE_PATHSPECS",
] {
let removed = command
.get_envs()
.any(|(key, value)| key == std::ffi::OsStr::new(name) && value.is_none());
assert!(removed, "{name} must not reach the child");
}
}
}
pub(super) fn protected_command(repo: &Path, args: &[&str], batch: &BatchSsh) -> Command {
let mut command = local_command(repo, args);
if let Some(ssh) = batch.ssh_command() {
command.env("GIT_SSH_COMMAND", ssh);
}
command
}
pub(super) fn deadlined_command(repo: &Path, args: &[&str], batch: &BatchSsh) -> DeadlinedGit {
DeadlinedGit(protected_command(repo, args, batch))
}
pub(super) fn batch_transport(repo: &Path) -> Result<BatchSsh, TransportUnknown> {
transport(repo).map(batch_ssh)
}
#[derive(Debug)]
pub(super) enum TransportUnknown {
SshConfig(String),
Repository(String),
Unasked(String),
Unanswered(String),
SshVariable(String),
}
impl TransportUnknown {
#[cfg(test)]
pub(super) fn detail(&self) -> &str {
match self {
Self::SshConfig(detail)
| Self::Repository(detail)
| Self::Unasked(detail)
| Self::Unanswered(detail)
| Self::SshVariable(detail) => detail,
}
}
}
#[derive(Debug)]
enum ProbeFailure {
Refused(String),
Unasked(String),
Unanswered(String),
}
impl ProbeFailure {
fn unreplied(failure: &RemoteFailure) -> Self {
if failure.left_no_answer() {
Self::Unanswered(failure.to_string())
} else {
Self::Unasked(failure.to_string())
}
}
fn from(reply: &Reply) -> Self {
match reply.code {
Some(_) => Self::Refused(reply.detail()),
None => Self::Unasked(reply.detail()),
}
}
}
fn repository_probe(probe: Probe<'_>) -> Result<(), ProbeFailure> {
let reply =
probe(&["rev-parse", "--git-dir"]).map_err(|failure| ProbeFailure::unreplied(&failure))?;
if reply.succeeded() {
return Ok(());
}
Err(ProbeFailure::from(&reply))
}
#[must_use = "a discarded refusal records an unsaid note as said"]
pub(super) fn warn(note: &str) -> bool {
say(io::stderr(), note)
}
fn say(out: impl Write, note: &str) -> bool {
crate::cli::printable::say(out, note).is_ok()
}
#[derive(Debug)]
enum SshTransport {
Composable(String),
Opaque(String),
Default,
}
#[derive(Debug)]
pub(super) enum BatchSsh {
Composed(String),
Inert {
ssh: String,
reason: String,
},
Unprotected(String),
}
impl BatchSsh {
fn ssh_command(&self) -> Option<&str> {
match self {
Self::Composed(ssh) | Self::Inert { ssh, .. } => Some(ssh),
Self::Unprotected(_) => None,
}
}
pub(super) fn unprotected_reason(&self) -> Option<&str> {
match self {
Self::Composed(_) => None,
Self::Inert { reason, .. } | Self::Unprotected(reason) => Some(reason),
}
}
}
type Probe<'a> = &'a dyn Fn(&[&str]) -> Result<Reply, RemoteFailure>;
type Env<'a> = &'a dyn Fn(&str) -> Result<Option<String>, String>;
fn transport(repo: &Path) -> Result<SshTransport, TransportUnknown> {
resolve_transport(&env_value, &|args| run_probe(repo, args))
}
fn run_probe(repo: &Path, args: &[&str]) -> Result<Reply, RemoteFailure> {
DeadlinedGit(local_command(repo, args))
.output(None)
.map(Reply::from)
}
fn resolve_transport(env: Env<'_>, probe: Probe<'_>) -> Result<SshTransport, TransportUnknown> {
let ssh_variable = TransportUnknown::SshVariable;
let env_command = env("GIT_SSH_COMMAND").map_err(ssh_variable)?;
let env_variant = env("GIT_SSH_VARIANT").map_err(ssh_variable)?;
let (command, variant) = if let (Some(command), Some(variant)) = (&env_command, &env_variant) {
(Some(command.clone()), Some(variant.clone()))
} else {
let config = config_probe(probe).map_err(|failure| match failure {
ProbeFailure::Unasked(why) => TransportUnknown::Unasked(why),
ProbeFailure::Unanswered(why) => TransportUnknown::Unanswered(why),
ProbeFailure::Refused(why) => match repository_probe(probe) {
Ok(()) => TransportUnknown::SshConfig(why),
Err(ProbeFailure::Refused(refusal)) => TransportUnknown::Repository(refusal),
Err(ProbeFailure::Unasked(second) | ProbeFailure::Unanswered(second)) => {
TransportUnknown::SshConfig(format!(
"{why}; whether git can open this repository could not be \
established either ({second})"
))
}
},
})?;
(
env_command.or(config.ssh_command),
env_variant.or(config.ssh_variant),
)
};
if let Some(reason) = opaque_variant(variant.as_deref(), command.as_deref()) {
return Ok(SshTransport::Opaque(reason));
}
if let Some(command) = command {
return Ok(SshTransport::Composable(command));
}
if let Some(program) = env("GIT_SSH").map_err(ssh_variable)? {
return Ok(SshTransport::Opaque(format!(
"GIT_SSH names `{program}`, which takes its arguments from git, not from oakum"
)));
}
Ok(SshTransport::Default)
}
fn opaque_variant(variant: Option<&str>, command: Option<&str>) -> Option<String> {
const OPAQUE_PROGRAMS: [&str; 3] = ["plink", "putty", "tortoiseplink"];
if let Some(variant) = variant {
return (!matches!(variant, "auto" | "ssh"))
.then(|| format!("ssh.variant is `{variant}`, which does not take `-o` options"));
}
let program = command?.split_whitespace().next()?;
let name = Path::new(program)
.file_stem()
.and_then(|stem| stem.to_str())?
.to_ascii_lowercase();
OPAQUE_PROGRAMS.contains(&name.as_str()).then(|| {
format!("`{program}` does not take `-o` options; git treats it as the `{name}` variant")
})
}
fn batch_ssh(transport: SshTransport) -> BatchSsh {
match transport {
SshTransport::Composable(command) => {
let ssh = format!("{command} -o BatchMode=yes");
if may_already_set_batch_mode(&command) {
return BatchSsh::Inert {
ssh,
reason: format!("`{command}` already sets BatchMode, which ssh reads first"),
};
}
BatchSsh::Composed(ssh)
}
SshTransport::Default => BatchSsh::Composed(String::from("ssh -o BatchMode=yes")),
SshTransport::Opaque(reason) => BatchSsh::Unprotected(reason),
}
}
fn may_already_set_batch_mode(command: &str) -> bool {
command.to_ascii_lowercase().contains("batchmode")
}
fn env_value(key: &str) -> Result<Option<String>, String> {
match std::env::var_os(key) {
None => Ok(None),
Some(raw) => raw
.into_string()
.map(non_blank)
.map_err(|_| format!("{key} is not valid UTF-8")),
}
}
fn non_blank(value: String) -> Option<String> {
(!value.trim().is_empty()).then_some(value)
}
struct GitConfig {
ssh_command: Option<String>,
ssh_variant: Option<String>,
}
fn config_probe(probe: Probe<'_>) -> Result<GitConfig, ProbeFailure> {
let reply = probe(&[
"config",
"--get-regexp",
r"^(core\.sshcommand|ssh\.variant)$",
])
.map_err(|failure| ProbeFailure::unreplied(&failure))?;
if reply.said_no() {
return Ok(GitConfig {
ssh_command: None,
ssh_variant: None,
});
}
if !reply.succeeded() {
return Err(ProbeFailure::from(&reply));
}
let listed = String::from_utf8(reply.stdout)
.map_err(|_| ProbeFailure::Refused(String::from("a value is not valid UTF-8")))?;
Ok(GitConfig {
ssh_command: config_value(&listed, "core.sshcommand"),
ssh_variant: config_value(&listed, "ssh.variant"),
})
}
fn config_value(listed: &str, key: &str) -> Option<String> {
listed
.lines()
.filter_map(|line| line.strip_prefix(key)?.strip_prefix(' '))
.next_back()
.and_then(|value| non_blank(value.trim().to_owned()))
}
#[cfg(test)]
mod tests {
#[test]
fn a_refused_write_is_reported() {
struct Full;
impl std::io::Write for Full {
fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut wrote = Vec::new();
assert!(super::say(&mut wrote, "a note"));
assert_eq!(wrote, b"a note\n");
assert!(!super::say(Full, "a note"));
let mut wrote = Vec::new();
assert!(super::say(&mut wrote, "a \u{1b}[2Jnote"));
assert_eq!(wrote, b"a \\u{1b}[2Jnote\n");
}
use super::super::Reply;
use super::{
batch_ssh, config_value, non_blank, opaque_variant, resolve_transport, BatchSsh,
RemoteFailure, SshTransport, TransportUnknown,
};
use oakum::discover::child::Reach;
use std::sync::Mutex;
use std::time::Duration;
struct Probes {
config: Mutex<Option<Result<Reply, RemoteFailure>>>,
repository: Mutex<Option<Result<Reply, RemoteFailure>>>,
asked: Mutex<Vec<String>>,
}
fn unran(why: &str) -> RemoteFailure {
RemoteFailure::Spawn(std::io::Error::other(why))
}
impl Probes {
fn new(
config: Result<Reply, RemoteFailure>,
repository: Result<Reply, RemoteFailure>,
) -> Self {
Self {
config: Mutex::new(Some(config)),
repository: Mutex::new(Some(repository)),
asked: Mutex::new(Vec::new()),
}
}
fn answer(&self, args: &[&str]) -> Result<Reply, RemoteFailure> {
self.asked.lock().expect("lock").push(args[0].to_owned());
let slot = match args[0] {
"config" => &self.config,
"rev-parse" => &self.repository,
other => panic!("no probe scripted for `git {other}`"),
};
slot.lock()
.expect("lock")
.take()
.unwrap_or_else(|| panic!("`git {}` probed twice", args[0]))
}
fn asked(&self) -> Vec<String> {
self.asked.lock().expect("lock").clone()
}
}
const NO_ENV: fn(&str) -> Result<Option<String>, String> = |_| Ok(None);
const CONFIG_REFUSED: &str =
"fatal: unable to read config file '.git/config': Permission denied";
#[test]
fn a_repository_probe_that_could_not_run_is_not_a_verdict_about_the_repository() {
let probes = Probes::new(
Ok(Reply::failed(128, CONFIG_REFUSED)),
Err(unran("Resource temporarily unavailable (os error 35)")),
);
let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
.expect_err("an unreadable config over an unprobed repository");
let TransportUnknown::SshConfig(detail) = &unknown else {
panic!("a probe that never ran must not decide the repository: {unknown:?}");
};
assert!(detail.contains("unable to read config file"), "{detail}");
assert!(
detail.contains(
"could not be established either (could not run git: Resource temporarily unavailable"
),
"{detail}"
);
assert_eq!(probes.asked(), ["config", "rev-parse"]);
}
#[test]
fn a_config_refusal_is_classed_by_what_the_repository_probe_established() {
let opens = Probes::new(
Ok(Reply::failed(128, CONFIG_REFUSED)),
Ok(Reply::said(".git\n")),
);
let unknown = resolve_transport(&NO_ENV, &|args| opens.answer(args))
.expect_err("config refused over an openable repository");
assert!(
matches!(&unknown, TransportUnknown::SshConfig(detail) if detail.contains("unable to read config file") && !detail.contains("either")),
"{unknown:?}"
);
let closed = Probes::new(
Ok(Reply::failed(128, CONFIG_REFUSED)),
Ok(Reply::failed(
128,
"fatal: not a git repository (or any of the parent directories): .git",
)),
);
let unknown = resolve_transport(&NO_ENV, &|args| closed.answer(args))
.expect_err("config refused over a repository git will not open");
assert!(
matches!(&unknown, TransportUnknown::Repository(detail) if detail.contains("not a git repository")),
"{unknown:?}"
);
assert_eq!(closed.asked(), ["config", "rev-parse"]);
}
#[test]
fn a_config_probe_that_never_ran_asks_nothing_more() {
let probes = Probes::new(
Err(unran("No such file or directory (os error 2)")),
Ok(Reply::said(".git\n")),
);
let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
.expect_err("git could not be run");
assert!(
matches!(&unknown, TransportUnknown::Unasked(detail) if detail.contains("No such file or directory")),
"{unknown:?}"
);
assert_eq!(probes.asked(), ["config"]);
}
#[test]
fn a_hung_repository_probe_after_a_config_refusal_stays_ssh_config() {
let probes = Probes::new(
Ok(Reply::failed(128, CONFIG_REFUSED)),
Err(RemoteFailure::Deadline {
limit: Duration::from_secs(2),
reach: Reach::Killed(Vec::new()),
}),
);
let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
.expect_err("an unreadable config");
assert!(
matches!(&unknown, TransportUnknown::SshConfig(detail) if detail.contains("could not be established either (gave up after 2s")),
"{unknown:?}"
);
}
#[test]
fn a_config_probe_that_never_answered_is_unanswered() {
let probes = Probes::new(
Err(RemoteFailure::Deadline {
limit: Duration::from_secs(2),
reach: Reach::Killed(Vec::new()),
}),
Ok(Reply::said(".git\n")),
);
let unknown = resolve_transport(&NO_ENV, &|args| probes.answer(args))
.expect_err("the probe never answered");
assert!(
matches!(&unknown, TransportUnknown::Unanswered(detail) if detail.contains("gave up after 2s")),
"{unknown:?}"
);
assert_eq!(probes.asked(), ["config"]);
}
#[test]
fn every_failure_but_spawn_left_no_answer() {
let limit = Duration::from_secs(2);
assert!(!unran("No such file or directory").left_no_answer());
for failure in [
RemoteFailure::Deadline {
limit,
reach: Reach::Killed(Vec::new()),
},
RemoteFailure::DrainStalled {
limit,
status: std::process::ExitStatus::default(),
},
RemoteFailure::Wait(
std::io::Error::other("interrupted"),
Reach::Killed(Vec::new()),
),
RemoteFailure::Read(std::io::Error::other("broken pipe")),
RemoteFailure::BadDeadline(String::from("not a number")),
] {
assert!(failure.left_no_answer(), "{failure}");
}
}
#[test]
fn both_ssh_variables_set_skip_both_probes() {
let probes = Probes::new(
Err(unran("the config probe must not run")),
Err(unran("the repository probe must not run")),
);
let env = |key: &str| -> Result<Option<String>, String> {
Ok(match key {
"GIT_SSH_COMMAND" => Some(String::from("ssh -i /dev/null")),
"GIT_SSH_VARIANT" => Some(String::from("ssh")),
_ => None,
})
};
let transport = resolve_transport(&env, &|args| probes.answer(args))
.expect("the variables decide the transport");
assert!(
matches!(&transport, SshTransport::Composable(command) if command == "ssh -i /dev/null"),
"{transport:?}"
);
assert!(probes.asked().is_empty(), "{:?}", probes.asked());
}
#[test]
fn an_unreadable_ssh_variable_is_not_an_unset_one() {
let probes = Probes::new(
Err(unran("no probe may run")),
Err(unran("no probe may run")),
);
let env = |key: &str| -> Result<Option<String>, String> {
if key == "GIT_SSH_COMMAND" {
Err(String::from("GIT_SSH_COMMAND is not valid UTF-8"))
} else {
Ok(None)
}
};
let unknown = resolve_transport(&env, &|args| probes.answer(args))
.expect_err("an unreadable variable decides nothing");
assert!(
matches!(&unknown, TransportUnknown::SshVariable(detail) if detail.contains("not valid UTF-8")),
"{unknown:?}"
);
assert!(probes.asked().is_empty(), "{:?}", probes.asked());
}
#[test]
fn a_config_ssh_command_is_read_through_the_probe() {
let probes = Probes::new(
Ok(Reply::said("core.sshcommand ssh -i ~/.ssh/deploy\n")),
Err(unran("the repository probe must not run")),
);
let transport =
resolve_transport(&NO_ENV, &|args| probes.answer(args)).expect("a readable config");
assert!(
matches!(&transport, SshTransport::Composable(command) if command == "ssh -i ~/.ssh/deploy"),
"{transport:?}"
);
assert_eq!(probes.asked(), ["config"]);
}
fn composed(transport: SshTransport) -> Option<String> {
match batch_ssh(transport) {
BatchSsh::Composed(ssh) | BatchSsh::Inert { ssh, .. } => Some(ssh),
BatchSsh::Unprotected(_) => None,
}
}
#[test]
fn a_composable_command_keeps_its_own_arguments() {
assert_eq!(
composed(SshTransport::Composable(String::from(
"ssh -i ~/.ssh/deploy"
)))
.as_deref(),
Some("ssh -i ~/.ssh/deploy -o BatchMode=yes")
);
}
#[test]
fn nothing_configured_still_gets_batch_mode() {
assert_eq!(
composed(SshTransport::Default).as_deref(),
Some("ssh -o BatchMode=yes")
);
}
#[test]
fn an_existing_batchmode_choice_is_appended_past_and_reported() {
match batch_ssh(SshTransport::Composable(String::from(
"ssh -o BatchMode=no",
))) {
BatchSsh::Inert { ssh, reason } => {
assert_eq!(ssh, "ssh -o BatchMode=no -o BatchMode=yes");
assert!(reason.contains("BatchMode"), "{reason}");
}
BatchSsh::Composed(ssh) => panic!("an inert append must be reported, got {ssh}"),
BatchSsh::Unprotected(reason) => panic!("must still append, got {reason}"),
}
}
#[test]
fn a_nested_batchmode_does_not_suppress_the_option() {
let nested = String::from("ssh -o ProxyCommand='ssh -o BatchMode=no bastion nc %h %p'");
assert_eq!(
composed(SshTransport::Composable(nested)).as_deref(),
Some("ssh -o ProxyCommand='ssh -o BatchMode=no bastion nc %h %p' -o BatchMode=yes")
);
}
#[test]
fn only_a_transport_that_cannot_take_batch_mode_owes_a_reason() {
assert_eq!(
BatchSsh::Composed(String::from("ssh -o BatchMode=yes")).unprotected_reason(),
None
);
assert_eq!(
BatchSsh::Inert {
ssh: String::from("ssh -o BatchMode=no"),
reason: String::from("the transport already chose BatchMode"),
}
.unprotected_reason(),
Some("the transport already chose BatchMode")
);
assert_eq!(
BatchSsh::Unprotected(String::from("ssh.variant is opaque")).unprotected_reason(),
Some("ssh.variant is opaque")
);
}
#[test]
fn an_opaque_transport_is_unprotected_and_says_why() {
match batch_ssh(SshTransport::Opaque(String::from(
"GIT_SSH names `/x/my-ssh`",
))) {
BatchSsh::Unprotected(reason) => {
assert!(reason.contains("/x/my-ssh"), "{reason}");
}
BatchSsh::Composed(ssh) | BatchSsh::Inert { ssh, .. } => {
panic!("GIT_SSH cannot take appended options, got {ssh}")
}
}
}
#[test]
fn an_explicit_non_ssh_variant_is_opaque() {
let reason = opaque_variant(Some("simple"), Some("/x/wrapper")).expect("opaque");
assert!(reason.contains("simple"), "{reason}");
assert!(opaque_variant(Some("putty"), None).is_some());
}
#[test]
fn the_openssh_variants_still_take_options() {
assert_eq!(opaque_variant(Some("ssh"), Some("plink")), None);
assert_eq!(opaque_variant(Some("auto"), Some("plink")), None);
}
#[test]
fn a_plink_basename_is_opaque_under_auto() {
assert!(opaque_variant(None, Some("C:/PuTTY/plink.exe -batch")).is_some());
assert!(opaque_variant(None, Some("/usr/bin/tortoiseplink")).is_some());
assert_eq!(opaque_variant(None, Some("/usr/bin/ssh -i /k")), None);
assert_eq!(opaque_variant(None, None), None);
}
#[test]
fn config_values_are_read_per_key_and_last_wins() {
let listed =
"core.sshcommand ssh -i /first\nssh.variant simple\ncore.sshcommand ssh -i /last\n";
assert_eq!(
config_value(listed, "core.sshcommand").as_deref(),
Some("ssh -i /last")
);
assert_eq!(
config_value(listed, "ssh.variant").as_deref(),
Some("simple")
);
assert_eq!(config_value(listed, "core.askpass"), None);
}
#[test]
fn blank_and_whitespace_values_are_unset() {
assert_eq!(non_blank(String::new()), None);
assert_eq!(non_blank(String::from(" ")), None);
assert_eq!(non_blank(String::from("ssh")).as_deref(), Some("ssh"));
}
fn exit_status(code: i32) -> std::process::ExitStatus {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
std::process::ExitStatus::from_raw(code)
}
#[cfg(windows)]
{
use std::os::windows::process::ExitStatusExt;
std::process::ExitStatus::from_raw(code.cast_unsigned())
}
}
#[test]
fn a_stalled_drain_names_the_lever() {
let err = RemoteFailure::from(oakum::discover::child::ChildFailure::DrainStalled {
limit: Duration::from_secs(5),
status: exit_status(0),
});
let text = err.to_string();
assert!(text.contains("still held its output open"), "{text}");
assert!(text.contains("OAKUM_REMOTE_DEADLINE"), "{text}");
}
#[test]
fn a_failed_read_names_the_read() {
let err = RemoteFailure::from(oakum::discover::child::ChildFailure::Read(
std::io::Error::other("pipe broke"),
));
let text = err.to_string();
assert!(text.contains("could not be read"), "{text}");
assert!(text.contains("pipe broke"), "{text}");
}
#[test]
fn wait_failure_names_the_kill() {
let err = RemoteFailure::Wait(
std::io::Error::other("wait interrupted"),
Reach::Unknown(String::from("could not list them: no ps")),
);
let text = err.to_string();
assert!(text.contains("waiting on it failed"), "{text}");
assert!(
text.contains("oakum killed it, but what it started may still be running"),
"{text}"
);
assert!(text.contains("wait interrupted"), "{text}");
}
#[test]
fn deadline_failure_names_the_lever() {
let err = RemoteFailure::Deadline {
limit: Duration::from_secs(2),
reach: Reach::Killed(Vec::from([String::from("gpg")])),
};
let text = err.to_string();
assert!(text.contains("gave up after 2s"), "{text}");
assert!(
text.contains("killed git and what was still running under it (`gpg`)"),
"{text}"
);
assert!(text.contains("OAKUM_REMOTE_DEADLINE"), "{text}");
}
#[test]
fn only_a_child_that_exited_counts_as_a_refusal() {
use super::super::Reply;
use super::ProbeFailure;
let refused = ProbeFailure::from(&Reply::failed(128, "fatal: detected dubious ownership"));
assert!(
matches!(refused, ProbeFailure::Refused(_)),
"a stated reason"
);
let on_stdout = ProbeFailure::from(&Reply::exactly(Some(128), b"fatal: refused", b""));
let ProbeFailure::Refused(why) = &on_stdout else {
panic!("a child that exited has run, whichever stream it wrote to: {on_stdout:?}");
};
assert!(why.contains("fatal: refused"), "{why}");
let signaled = ProbeFailure::from(&Reply::was_signalled());
assert!(
matches!(signaled, ProbeFailure::Unasked(_)),
"a signal is not evidence about what was asked"
);
}
#[test]
fn a_refused_config_probe_is_not_reported_as_never_asked() {
let said = super::super::Op::AdvertisedTags { remote: "origin" }
.shape()
.unreadable_transport(&super::TransportUnknown::SshConfig(String::from(
"exit 128: fatal: unable to read config file; whether git can open this \
repository could not be established either (terminated by a signal with no \
diagnostic)",
)))
.to_string();
assert!(said.contains("unable to read config file"), "{said}");
assert!(
said.contains("could not be established either"),
"both facts travel: {said}"
);
assert!(!said.contains("did not run"), "{said}");
}
}