use std::fmt;
use std::sync::LazyLock;
use regex::Regex;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitStep {
Probe,
Pull,
Push,
Sync,
}
impl GitStep {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Probe => "probe",
Self::Pull => "pull",
Self::Push => "push",
Self::Sync => "sync",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitFailureKind {
Unreachable,
AccessRefused,
UpdateRejected,
Local,
Unknown,
}
impl GitFailureKind {
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Unreachable => "unreachable",
Self::AccessRefused => "access-refused",
Self::UpdateRejected => "update-rejected",
Self::Local => "local",
Self::Unknown => "unknown",
}
}
const fn clause(self) -> Option<&'static str> {
match self {
Self::Unreachable => Some("the remote could not be reached"),
Self::AccessRefused => Some("the remote refused access"),
Self::UpdateRejected => Some("the remote rejected the update"),
Self::Local => Some("the failure was local"),
Self::Unknown => None,
}
}
}
const MAX_REASON_BYTES: usize = 600;
const MAX_SHORT_REASON_BYTES: usize = 160;
const CAUSE_SKIP_PREFIXES: &[&str] = &["hint:", "note:", "...", "to ", "from "];
fn cut_line(line: &str) -> String {
if line.len() <= MAX_SHORT_REASON_BYTES {
return line.to_string();
}
let head = MAX_SHORT_REASON_BYTES * 2 / 3;
let tail = MAX_SHORT_REASON_BYTES / 3;
format!(
"{}\u{2026}{}",
&line[..line.floor_char_boundary(head)],
&line[line.ceil_char_boundary(line.len() - tail)..],
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitFailure {
step: GitStep,
remote: Option<String>,
kind: GitFailureKind,
reason: String,
}
impl GitFailure {
#[must_use]
pub(crate) fn new(
step: GitStep,
remote: Option<&str>,
kind: GitFailureKind,
reason: &str,
) -> Self {
Self {
step,
remote: remote.map(str::to_string),
kind,
reason: crate::util::truncate_sandwich(
&redact(reason.trim()),
MAX_REASON_BYTES,
"git output",
)
.trim()
.to_string(),
}
}
#[must_use]
pub(crate) fn local(step: GitStep, remote: Option<&str>, reason: &str) -> Self {
Self::new(step, remote, GitFailureKind::Local, reason)
}
#[must_use]
pub(crate) fn classified(step: GitStep, remote: Option<&str>, report: &str) -> Self {
Self::new(step, remote, classify(report), report)
}
#[must_use]
pub const fn step(&self) -> GitStep {
self.step
}
#[must_use]
pub const fn kind(&self) -> GitFailureKind {
self.kind
}
#[must_use]
pub fn remote(&self) -> Option<&str> {
self.remote.as_deref()
}
#[must_use]
pub fn message(&self) -> String {
self.sentence(&self.compose((!self.reason.is_empty()).then_some(self.reason.as_str())))
}
#[must_use]
pub fn toast(&self) -> String {
self.sentence(&self.short())
}
#[must_use]
pub fn short(&self) -> String {
self.compose(self.cause_line().map(cut_line).as_deref())
}
fn sentence(&self, text: &str) -> String {
format!(
"Sync could not {}: {text}",
self.action().unwrap_or_else(|| "run".to_string())
)
}
fn compose(&self, text: Option<&str>) -> String {
match (self.kind.clause(), text) {
(Some(claim), Some(text)) => format!("{claim} \u{2014} {text}"),
(Some(claim), None) => claim.to_string(),
(None, Some(text)) => text.to_string(),
(None, None) => "git gave no reason".to_string(),
}
}
fn cause_line(&self) -> Option<&str> {
let mut first = None;
let mut last = None;
for line in self
.reason
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
{
let skipped = CAUSE_SKIP_PREFIXES
.iter()
.any(|prefix| starts_with_ignore_case(line, prefix));
if first.is_none() && !skipped {
first = Some(line);
}
last = Some(line);
}
first.or(last)
}
#[must_use]
pub fn dedupe_key(&self) -> String {
static ELAPSED: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)\bafter \d+ (?:ms|milliseconds?)\b")
.expect("the elapsed pattern compiles")
});
format!(
"{}:{}",
self.step.label(),
ELAPSED.replace_all(&self.reason, "after ? ms")
)
}
fn action(&self) -> Option<String> {
match self.step {
GitStep::Probe => Some(format!(
"ask {} what it carries",
self.remote.as_deref().unwrap_or("the remote")
)),
GitStep::Pull => Some("pull".to_string()),
GitStep::Push => Some("push".to_string()),
GitStep::Sync => None,
}
}
}
fn starts_with_ignore_case(line: &str, prefix: &str) -> bool {
line.get(..prefix.len())
.is_some_and(|head| head.eq_ignore_ascii_case(prefix))
}
pub(crate) fn report(stderr: &str, stdout: &str) -> String {
[stderr.trim(), stdout.trim()]
.into_iter()
.filter(|stream| !stream.is_empty())
.collect::<Vec<_>>()
.join("\n")
}
#[derive(Debug)]
pub(crate) enum GitNetworkFailure {
Spawn { command: String, error: String },
WaitFailed { command: String, error: String },
TimedOut { command: String, secs: u64 },
Exited {
command: String,
status: Option<i32>,
stderr: String,
stdout: String,
},
}
impl GitNetworkFailure {
#[must_use]
pub(crate) fn into_failure(self, step: GitStep, remote: Option<&str>) -> GitFailure {
match self {
Self::Spawn { error, .. } => {
GitFailure::local(step, remote, &format!("git could not be started: {error}"))
}
Self::WaitFailed { command, error } => GitFailure::local(
step,
remote,
&format!("git {command} could not be waited for: {error}"),
),
Self::TimedOut { secs, .. } => GitFailure::new(
step,
remote,
GitFailureKind::Unreachable,
&format!("no answer came back within {secs}s"),
),
Self::Exited {
status,
stderr,
stdout,
..
} => {
let report = report(&stderr, &stdout);
let reason = if report.is_empty() {
status.map_or_else(String::new, |code| {
format!("git exited with status {code} and printed nothing")
})
} else {
report
};
GitFailure::classified(step, remote, &reason)
}
}
}
}
impl fmt::Display for GitNetworkFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Spawn { command, error } => {
write!(f, "git {command} could not be started: {error}")
}
Self::WaitFailed { command, error } => {
write!(f, "git {command} could not be waited for: {error}")
}
Self::TimedOut { command, secs } => {
write!(f, "git {command} timed out after {secs}s")
}
Self::Exited {
command,
stderr,
stdout,
..
} => write!(
f,
"git {command} failed: {}",
redact(&report(stderr, stdout))
),
}
}
}
impl std::error::Error for GitNetworkFailure {}
const LOCAL_MARKERS: &[&str] = &[
"terminal prompts disabled",
"could not read username",
"could not read password",
"not a git repository:",
"not a git repository (or any",
"index.lock",
"is not a git command",
"unable to create",
"could not create directory",
"unable to write",
"unable to open",
"could not open",
"cannot open",
"unable to unlink",
"could not unlink",
"unable to reset",
"could not reset index",
"unable to update ref",
"could not update ref",
];
const ACCESS_MARKERS: &[&str] = &[
"authentication failed",
"authentication required",
"access denied",
"permission denied",
"invalid username or password",
"invalid credentials",
"returned error: 401",
"returned error: 403",
"http 401",
"http 403",
"denied to ",
"not allowed to push",
"not permitted to access",
"not authorized to access",
"not authorized to push",
];
const POLICY_MARKERS: &[&str] = &[
"protected branch",
"branch is protected",
"gh006",
"pushes to this branch are not permitted",
"prohibited by",
];
const REJECTED_MARKERS: &[&str] = &[
"[rejected]",
"[remote rejected]",
"non-fast-forward",
"fetch first",
"failed to push some refs",
"hook declined",
"pre-receive hook",
"update declined",
"stale info",
];
const UNREACHABLE_MARKERS: &[&str] = &[
"could not resolve host",
"failed to connect",
"couldn't connect to server",
"connection refused",
"connection timed out",
"operation timed out",
"connection reset",
"remote end hung up",
"network is unreachable",
"no route to host",
"name or service not known",
"temporary failure in name resolution",
];
fn classify(report: &str) -> GitFailureKind {
let local_text = report
.lines()
.filter(|line| !line.trim_start().starts_with("remote:"))
.collect::<Vec<_>>()
.join("\n")
.to_lowercase();
let text = report.to_lowercase();
let has =
|haystack: &str, markers: &[&str]| markers.iter().any(|marker| haystack.contains(marker));
if has(&local_text, LOCAL_MARKERS) {
GitFailureKind::Local
} else if has(&text, POLICY_MARKERS) {
GitFailureKind::UpdateRejected
} else if has(&text, ACCESS_MARKERS) {
GitFailureKind::AccessRefused
} else if has(&text, REJECTED_MARKERS) {
GitFailureKind::UpdateRejected
} else if has(&text, UNREACHABLE_MARKERS) {
GitFailureKind::Unreachable
} else {
GitFailureKind::Unknown
}
}
fn redact(text: &str) -> String {
static USERINFO: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)(https?|ssh|git|ftp)://(?:[^/\s@]*:[^\s@]*|[^/\s@]+)@")
.expect("the credential pattern compiles")
});
USERINFO.replace_all(text, "${1}://***@").into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[expect(clippy::too_many_lines)] #[test]
fn classification_cases() {
struct Case {
name: &'static str,
stderr: &'static str,
kind: GitFailureKind,
}
let cases: &[Case] = &[
Case {
name: "https bad credentials",
stderr: "remote: Invalid username or password.\n\
fatal: Authentication failed for 'https://github.com/o/r.git/'",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "https 403",
stderr: "fatal: unable to access 'https://github.com/o/r.git/': \
The requested URL returned error: 403",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "ssh publickey refused",
stderr: "git@github.com: Permission denied (publickey).\n\
fatal: Could not read from remote repository.",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "permission denied to the repository",
stderr: "remote: Permission to o/r.git denied to someone.\n\
fatal: unable to access 'https://github.com/o/r.git/': \
The requested URL returned error: 403",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "no credential and prompting disabled",
stderr: "fatal: could not read Username for 'https://github.com': \
terminal prompts disabled",
kind: GitFailureKind::Local,
},
Case {
name: "dns failure",
stderr: "fatal: unable to access 'https://github.com/o/r.git/': \
Could not resolve host: github.com",
kind: GitFailureKind::Unreachable,
},
Case {
name: "ssh connect timeout",
stderr: "ssh: connect to host github.com port 22: Connection timed out\n\
fatal: Could not read from remote repository.",
kind: GitFailureKind::Unreachable,
},
Case {
name: "diverged push",
stderr: " ! [rejected] main -> main (non-fast-forward)\n\
error: failed to push some refs to 'origin'",
kind: GitFailureKind::UpdateRejected,
},
Case {
name: "protected branch",
stderr: "remote: error: GH006: Protected branch update failed for refs/heads/main.\n\
! [remote rejected] main -> main (protected branch hook declined)",
kind: GitFailureKind::UpdateRejected,
},
Case {
name: "pre-receive hook",
stderr: "remote: pre-receive hook declined\n\
! [remote rejected] main -> main (pre-receive hook declined)",
kind: GitFailureKind::UpdateRejected,
},
Case {
name: "gerrit policy refusal",
stderr: "remote: You are not permitted to perform this action.\n\
! [remote rejected] refs/heads/main -> refs/heads/main \
(prohibited by Gerrit)",
kind: GitFailureKind::UpdateRejected,
},
Case {
name: "bitbucket access refusal",
stderr: "remote: You are not authorized to access this repository.\n\
fatal: unable to access 'https://bitbucket.example/o/r.git/': \
The requested URL returned error: 401",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "a redirected url base is not a local failure",
stderr: "fatal: unable to update url base from redirection:\n\
asked for: https://x/r.git/info/refs?service=git-upload-pack\n\
redirect: https://y/r.git/info/refs?service=git-upload-pack",
kind: GitFailureKind::Unknown,
},
Case {
name: "azure devops branch policy",
stderr: "remote: TF402455: Pushes to this branch are not permitted; you must use a \
pull request.\n\
! [remote rejected] main -> main (TF402455)",
kind: GitFailureKind::UpdateRejected,
},
Case {
name: "gitlab protected branch",
stderr: "remote: GitLab: You are not allowed to push code to protected branches \
on this project.\n\
! [remote rejected] main -> main (pre-receive hook declined)",
kind: GitFailureKind::UpdateRejected,
},
Case {
name: "gitlab no write access refused by a hook",
stderr: "remote: GitLab: You are not allowed to push code to this project.\n\
! [remote rejected] main -> main (pre-receive hook declined)\n\
error: failed to push some refs to 'git@gitlab.com:o/r.git'",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "gitea no write access refused by a hook",
stderr: "remote: User permission denied for writing.\n\
! [remote rejected] main -> main (pre-receive hook declined)\n\
error: failed to push some refs to 'git@gitea.com:o/r.git'",
kind: GitFailureKind::AccessRefused,
},
Case {
name: "local write denial during a pull",
stderr: "error: unable to unlink old 'README.md': Permission denied\n\
fatal: Could not reset index file to revision 'FETCH_HEAD'.",
kind: GitFailureKind::Local,
},
Case {
name: "the destination's own disk failure is not local",
stderr: "remote: error: unable to create temporary file: No space left on device\n\
error: unpack failed: unpack-objects abnormal exit",
kind: GitFailureKind::Unknown,
},
Case {
name: "dropped connection",
stderr: "fatal: the remote end hung up unexpectedly",
kind: GitFailureKind::Unreachable,
},
Case {
name: "https 404 picks no cause",
stderr: "fatal: unable to access 'https://github.com/o/r.git/': \
The requested URL returned error: 404",
kind: GitFailureKind::Unknown,
},
Case {
name: "tls failure claims nothing",
stderr: "fatal: unable to access 'https://github.com/o/r.git/': \
SSL certificate problem: unable to get local issuer certificate",
kind: GitFailureKind::Unknown,
},
Case {
name: "local write denial is not an access refusal",
stderr: "error: unable to write file src/main.rs: Permission denied",
kind: GitFailureKind::Local,
},
Case {
name: "a path that is not a repository is the destination answering",
stderr: "fatal: '/tmp/x/origin.git' does not appear to be a git repository\n\
fatal: Could not read from remote repository.",
kind: GitFailureKind::Unknown,
},
Case {
name: "nothing printed",
stderr: "",
kind: GitFailureKind::Unknown,
},
];
for case in cases {
assert_eq!(
classify(case.stderr),
case.kind,
"case {}: {:?}",
case.name,
case.stderr
);
}
}
#[test]
fn message_keeps_the_claim_and_the_cause() {
let refused = GitFailure::new(
GitStep::Push,
Some("origin"),
GitFailureKind::AccessRefused,
"remote: Invalid username or password.",
);
assert_eq!(
refused.message(),
"Sync could not push: the remote refused access \u{2014} \
remote: Invalid username or password."
);
let unreachable = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::Unreachable,
"fatal: unable to access 'https://github.com/o/r.git/': Could not resolve host: github.com",
);
assert!(
unreachable.message().starts_with(
"Sync could not ask origin what it carries: the remote could not be reached \u{2014} "
),
"{}",
unreachable.message()
);
let unknown = GitFailure::new(GitStep::Pull, None, GitFailureKind::Unknown, "fatal: odd");
assert_eq!(unknown.message(), "Sync could not pull: fatal: odd");
let silent = GitFailure::new(GitStep::Push, None, GitFailureKind::UpdateRejected, "");
assert_eq!(
silent.message(),
"Sync could not push: the remote rejected the update"
);
let nothing = GitFailure::new(GitStep::Push, None, GitFailureKind::Unknown, "");
assert_eq!(nothing.message(), "Sync could not push: git gave no reason");
let no_branch = GitFailure::local(GitStep::Sync, None, "no branch is checked out");
assert_eq!(
no_branch.message(),
"Sync could not run: the failure was local \u{2014} no branch is checked out"
);
}
#[test]
fn toast_keeps_the_step_and_the_cause_line() {
let failure = GitFailure::new(
GitStep::Push,
Some("origin"),
GitFailureKind::AccessRefused,
"remote: Permission to o/r.git denied to someone.\n\
fatal: unable to access 'https://github.com/o/r.git/': \
The requested URL returned error: 403",
);
assert_eq!(
failure.toast(),
"Sync could not push: the remote refused access \u{2014} \
remote: Permission to o/r.git denied to someone."
);
assert!(
failure.toast().len() < failure.message().len(),
"the toast is the short form: {}",
failure.toast()
);
}
#[test]
fn short_keeps_the_cause_line() {
let failure = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::AccessRefused,
"remote: Permission to o/r.git denied to someone.\n\
fatal: unable to access 'https://github.com/o/r.git/': \
The requested URL returned error: 403",
);
assert_eq!(
failure.short(),
"the remote refused access \u{2014} remote: Permission to o/r.git denied to someone."
);
let ssh = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::AccessRefused,
"git@github.com: Permission denied (publickey).\n\
fatal: Could not read from remote repository.\n\n\
Please make sure you have the correct access rights\n\
and the repository exists.",
);
assert_eq!(
ssh.short(),
"the remote refused access \u{2014} git@github.com: Permission denied (publickey)."
);
let rejected = GitFailure::new(
GitStep::Push,
Some("origin"),
GitFailureKind::UpdateRejected,
"To /tmp/remote.git\n\
! [rejected] main -> main (non-fast-forward)\n\
error: failed to push some refs to '/tmp/remote.git'\n\
hint: Updates were rejected because the tip of your current branch is behind",
);
assert_eq!(
rejected.short(),
"the remote rejected the update \u{2014} \
! [rejected] main -> main (non-fast-forward)"
);
let long = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::Unreachable,
&format!(
"fatal: unable to access '{}': The requested URL returned error: 403",
"https://github.com/o/r/".repeat(12)
),
);
assert!(long.short().ends_with("error: 403"), "{}", long.short());
assert!(
long.short().len() < MAX_SHORT_REASON_BYTES + 80,
"{}",
long.short()
);
assert_eq!(
GitFailure::new(GitStep::Push, None, GitFailureKind::Local, "").short(),
"the failure was local"
);
}
#[test]
fn dedupe_key_folds_out_measurements() {
let first = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::Unreachable,
"fatal: unable to access 'https://x/': Failed to connect to x port 443 after 75002 ms: \
Couldn't connect to server",
);
let second = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::Unreachable,
"fatal: unable to access 'https://x/': Failed to connect to x port 443 after 75031 ms: \
Couldn't connect to server",
);
assert_eq!(first.dedupe_key(), second.dedupe_key());
let forbidden = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::AccessRefused,
"fatal: unable to access 'https://x/': The requested URL returned error: 403",
);
let unauthorized = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::AccessRefused,
"fatal: unable to access 'https://x/': The requested URL returned error: 401",
);
assert_ne!(forbidden.dedupe_key(), unauthorized.dedupe_key());
let report = "fatal: unable to access 'https://x/': Could not resolve host: x";
let probe = GitFailure::new(
GitStep::Probe,
Some("origin"),
GitFailureKind::Unreachable,
report,
);
let pull = GitFailure::new(
GitStep::Pull,
Some("origin"),
GitFailureKind::Unreachable,
report,
);
assert_ne!(probe.dedupe_key(), pull.dedupe_key());
}
#[test]
fn credentials_are_scrubbed_from_every_surface() {
let failure = GitFailure::new(
GitStep::Push,
Some("origin"),
GitFailureKind::AccessRefused,
"fatal: unable to access 'https://oauth2:ghp_secret@github.com/o/r.git/': \
The requested URL returned error: 403",
);
let message = failure.message();
assert!(!message.contains("ghp_secret"), "{message}");
assert!(!message.contains("oauth2"), "{message}");
assert!(
message.contains("https://***@github.com/o/r.git/"),
"{message}"
);
let slash = GitFailure::new(
GitStep::Push,
None,
GitFailureKind::AccessRefused,
"fatal: unable to access 'https://user:pa/ss@github.com/o/r.git/': error: 403",
)
.message();
assert!(!slash.contains("pa/ss"), "{slash}");
assert!(slash.contains("https://***@github.com/o/r.git/"), "{slash}");
let path = redact("fatal: bad ref 'https://github.com/o/r@v1.git'");
assert!(path.contains("o/r@v1.git"), "{path}");
}
#[test]
fn cap_keeps_the_tail_with_the_cause() {
let noise = "remote: counting objects\n".repeat(200);
let failure = GitFailure::new(
GitStep::Push,
None,
GitFailureKind::UpdateRejected,
&format!("{noise}fatal: the repository is protected"),
);
assert!(
failure.message().len() < MAX_REASON_BYTES + 200,
"the stored text is capped: {}",
failure.message().len()
);
assert!(
failure
.message()
.ends_with("fatal: the repository is protected"),
"{}",
failure.message()
);
assert!(
failure.message().contains("bytes omitted"),
"{}",
failure.message()
);
}
#[test]
fn network_failures_are_classified_by_origin() {
let spawn = GitNetworkFailure::Spawn {
command: "push".to_string(),
error: "No such file or directory (os error 2)".to_string(),
}
.into_failure(GitStep::Push, Some("origin"));
assert_eq!(spawn.kind(), GitFailureKind::Local);
assert!(spawn.message().contains("could not be started"));
let timed_out = GitNetworkFailure::TimedOut {
command: "push".to_string(),
secs: 300,
}
.into_failure(GitStep::Push, None);
assert_eq!(timed_out.kind(), GitFailureKind::Unreachable);
assert!(timed_out.message().contains("within 300s"));
let wait_failed = GitNetworkFailure::WaitFailed {
command: "push".to_string(),
error: "No child processes (os error 10)".to_string(),
}
.into_failure(GitStep::Push, Some("origin"));
assert_eq!(wait_failed.kind(), GitFailureKind::Local);
assert!(
wait_failed.message().contains("could not be waited for"),
"{}",
wait_failed.message()
);
let silent = GitNetworkFailure::Exited {
command: "push".to_string(),
status: Some(128),
stderr: String::new(),
stdout: String::new(),
}
.into_failure(GitStep::Push, None);
assert_eq!(silent.kind(), GitFailureKind::Unknown);
assert!(silent.message().contains("exited with status 128"));
}
}