#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
kind: Kind,
detail: String,
}
impl Error {
pub fn new(detail: impl Into<String>) -> Self {
let detail = detail.into();
Self {
kind: Kind::classify(&detail),
detail,
}
}
pub fn io(detail: impl Into<String>) -> Self {
Self {
kind: Kind::Other,
detail: detail.into(),
}
}
pub fn kind(&self) -> Kind {
self.kind
}
pub fn detail(&self) -> &str {
&self.detail
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.detail)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
NotFound,
Auth,
Network,
Other,
}
impl Kind {
pub fn classify(error: &str) -> Self {
let error = error.to_ascii_lowercase();
let has = |needle: &str| error.contains(needle);
if has("repository not found")
|| has("does not appear to be a git repository")
|| (has("repository") && has("not found"))
{
Self::NotFound
} else if has("authentication failed")
|| has("could not read username")
|| has("could not read password")
|| has("terminal prompts disabled")
|| has("permission denied")
|| has("403")
{
Self::Auth
} else if has("could not resolve host")
|| has("could not resolve")
|| has("unable to access")
|| has("failed to connect")
|| has("timed out")
|| has("network is unreachable")
{
Self::Network
} else {
Self::Other
}
}
pub fn reason(self) -> &'static str {
match self {
Self::NotFound => "repository not found",
Self::Auth => "authentication failed",
Self::Network => "can't reach the host",
Self::Other => "sync failed",
}
}
pub fn footer(self) -> &'static str {
match self {
Self::NotFound => "remote not found",
Self::Auth => "auth failed",
Self::Network => "offline",
Self::Other => "sync failed",
}
}
pub fn fix(self) -> &'static str {
match self {
Self::NotFound => {
"check the owner/repo, or create the repository (private is fine), then retry"
}
Self::Auth => {
"no stored credentials or no write access \u{2014} over HTTPS git needs a token, or use an SSH remote"
}
Self::Network => "check your network and the host name, then retry",
Self::Other => "the git error is above",
}
}
}
#[cfg(test)]
mod tests {
use super::Kind;
#[test]
fn classifies_common_git_failures() {
assert_eq!(
Kind::classify("remote: Repository not found."),
Kind::NotFound
);
assert_eq!(
Kind::classify(
"fatal: could not read Username for 'https://github.com': terminal prompts disabled"
),
Kind::Auth
);
assert_eq!(
Kind::classify("fatal: unable to access 'x': Could not resolve host: github.com"),
Kind::Network
);
assert_eq!(Kind::classify("something else"), Kind::Other);
}
#[test]
fn io_errors_are_not_mistaken_for_git_auth() {
let err = super::Error::io("could not create dir: Permission denied (os error 13)");
assert_eq!(err.kind(), Kind::Other);
}
}