Skip to main content

grit_lib/remote/
error.rs

1//! [`RemoteError`] and conversions for transport, fetch, push, and clone.
2
3use std::path::PathBuf;
4
5use thiserror::Error;
6
7use super::push_plan::PushPlanError;
8use crate::error::{AuthFailure, RemoteUnreadableReason};
9use crate::fetch_request::FetchRefspecError;
10use crate::partial_clone::PartialCloneError;
11use crate::protocol::ProtocolError;
12use crate::resumable::ResumableError;
13use crate::serve::ServeError;
14
15/// Errors for remote URL resolution, transport, fetch, push, and clone.
16#[non_exhaustive]
17#[derive(Debug, Error)]
18pub enum RemoteError {
19    /// A remote has no URL: `remote.<name>.url` is unset or blank, or a literal URL was empty.
20    #[error("{}", match remote {
21        Some(name) => format!("remote '{name}' has no URL configured"),
22        None => "remote URL is empty".to_owned(),
23    })]
24    NoUrl {
25        /// The configured remote's name; `None` when an empty literal URL was given.
26        remote: Option<String>,
27    },
28    /// The URL uses a scheme grit does not support for remotes.
29    #[error("unsupported remote URL scheme")]
30    UnsupportedScheme,
31    /// A URL or path failed to parse.
32    #[error("{detail}")]
33    InvalidUrl {
34        /// Why the URL or path could not be used.
35        detail: String,
36    },
37    /// Smart HTTP requires the `http-ureq` feature or an injected HTTP client factory.
38    #[error("HTTP remotes require the http-ureq feature or an HttpClientFactory")]
39    HttpUnavailable,
40    /// The argument is neither a configured remote name nor a URL or path.
41    #[error("unknown remote '{name}'")]
42    UnknownRemote {
43        /// The argument as given.
44        name: String,
45    },
46    /// [`RepositoryRemotes::add`](crate::repo_handles::RepositoryRemotes::add) found an
47    /// existing `remote.<name>.*` section.
48    #[error("remote '{name}' already exists")]
49    RemoteExists {
50        /// The remote name.
51        name: String,
52    },
53    /// The name cannot be used for a remote (`refs/remotes/<name>/…` would not be a valid ref).
54    #[error("'{name}' is not a valid remote name")]
55    InvalidRemoteName {
56        /// The name as given.
57        name: String,
58    },
59
60    /// HTTP authentication failed.
61    #[error("authentication failed for {url}: {reason}")]
62    Auth {
63        /// Repository URL with credentials redacted.
64        url: String,
65        /// What went wrong.
66        reason: AuthFailure,
67    },
68    /// A credential provider could not supply a complete username and password.
69    #[error("{}", crate::credentials::NON_INTERACTIVE_MESSAGE)]
70    CredentialsUnavailable {
71        /// The `credential.helper` programs that were asked, in order.
72        helpers: Vec<String>,
73    },
74    /// An atomic wire push was requested, but the remote did not advertise `atomic`.
75    #[error("the remote does not support atomic pushes")]
76    PushAtomicUnsupported,
77    /// Push options were sent but the remote did not advertise `push-options`.
78    #[error("the receiving end does not support push options")]
79    PushOptionsUnsupported,
80    /// `git fetch --unshallow` on a repository that is not shallow.
81    #[error("repository is not shallow")]
82    FetchUnshallowNotShallow,
83    /// A deepen/shallow fetch was requested but the remote did not advertise `shallow`.
84    #[error("the remote does not support shallow fetches")]
85    FetchShallowUnsupported,
86    /// A `--deepen` fetch was requested but the remote did not advertise `deepen-relative`.
87    #[error("the remote does not support deepen-relative")]
88    FetchDeepenRelativeUnsupported,
89    /// Streaming fetch/clone temp pack disappeared before index-pack.
90    #[error(
91        "received pack file missing: {}. If this persists, check real-time antivirus or disk cleanup for quarantined pack temp files.",
92        crate::git_path::user_display_path(.path)
93    )]
94    ReceivedPackTempMissing {
95        /// Path to the temp pack that was expected on disk.
96        path: PathBuf,
97    },
98    /// The remote could not be read or written at all.
99    #[error("{}", crate::error::remote_unreadable_message(url.as_deref(), reason))]
100    Unreadable {
101        /// Remote URL or resolved local path, with credentials redacted.
102        url: Option<String>,
103        /// What went wrong.
104        reason: RemoteUnreadableReason,
105    },
106    /// The remote was reached but aborted with its own error text.
107    #[error("remote error: {message}")]
108    Fatal {
109        /// The server's message.
110        message: String,
111    },
112    /// The upload-pack serving a local path or `file://` URL in this process failed.
113    #[error("local upload-pack: {0}")]
114    LocalUploadPack(Box<ServeError>),
115    /// Serving a fetch or push to a client failed at the protocol level.
116    #[error(transparent)]
117    Serve(ServeError),
118    /// The thread serving a local path or `file://` URL panicked.
119    #[error("local upload-pack stopped unexpectedly")]
120    LocalUploadPackPanicked,
121    /// A resumable bundle download or upload failed.
122    #[error(transparent)]
123    Resumable(#[from] Box<ResumableError>),
124    /// Explicit fetch refspec resolution failed.
125    #[error("{0}")]
126    FetchRefspec(#[from] FetchRefspecError),
127    /// Fetch refused to update the branch checked out in this or a linked worktree.
128    #[error("cannot fetch into checked-out branch '{branch}'")]
129    FetchIntoCheckedOutBranch {
130        /// Short branch name under `refs/heads/`.
131        branch: String,
132    },
133    /// Protocol allow/deny policy blocked the transport.
134    #[error(transparent)]
135    Protocol(#[from] ProtocolError),
136    /// Push planning failed before the wire protocol ran.
137    #[error(transparent)]
138    PushPlan(#[from] PushPlanError),
139    /// Partial-clone filter configuration failed.
140    #[error(transparent)]
141    PartialClone(#[from] PartialCloneError),
142    /// Malformed remote URL for a specific transport scheme.
143    #[error("{detail}")]
144    MalformedTransportUrl {
145        /// `git`, `ssh`, `http`, or `file`.
146        scheme: &'static str,
147        /// Parse or validation detail.
148        detail: String,
149    },
150    /// SSH subprocess or URL setup failed.
151    #[error("{detail}")]
152    Ssh {
153        /// What failed while starting or talking to `ssh`.
154        detail: String,
155    },
156    /// Low-level transport failure (connection, DNS, TLS, or I/O outside HTTP status handling).
157    #[error("{}", crate::error::remote_transport_message(.url.as_deref(), .detail))]
158    Transport {
159        /// Redacted repository URL when known.
160        url: Option<String>,
161        /// What failed (for example `connection refused`).
162        detail: String,
163    },
164    /// HTTP status from an embedder [`HttpClient`](crate::transport::http::HttpClient) outside auth/unreadable mapping.
165    #[error("{}", crate::error::remote_http_status_message(.url.as_deref(), *status))]
166    HttpStatus {
167        /// Redacted repository URL when known.
168        url: Option<String>,
169        /// Response status code.
170        status: u16,
171    },
172    /// HTTP client or worker failure outside unreadable/auth classification.
173    #[error("{detail}")]
174    Http {
175        /// What the HTTP client reported.
176        detail: String,
177    },
178    /// HTTP worker thread panicked.
179    #[error("HTTP worker thread panicked")]
180    HttpWorkerPanicked,
181    /// HTTP transfer stalled below the configured low-speed limit.
182    #[error("{detail}")]
183    HttpLowSpeedStall {
184        /// The transfer rate and limit that were crossed.
185        detail: String,
186    },
187    /// Credential helper or askpass failure.
188    #[error("{detail}")]
189    Credential {
190        /// What the credential helper or askpass reported.
191        detail: String,
192    },
193    /// A snapshot checkout from a grit server failed for a server-specific reason.
194    #[error(transparent)]
195    Snapshot(crate::snapshot_checkout::CheckoutError),
196    /// Clone-specific failure (destination not empty, missing `--branch` ref, failed checkout).
197    #[error(transparent)]
198    Clone(Box<crate::clone::CloneError>),
199    /// A bundle used as a remote (or written for one) could not be read, written, or applied.
200    #[error(transparent)]
201    Bundle(crate::bundle::BundleError),
202}
203
204impl RemoteError {
205    /// Map a low-level I/O error to [`RemoteError::Transport`].
206    pub fn from_io(err: std::io::Error) -> Self {
207        Self::Transport {
208            url: None,
209            detail: err.to_string(),
210        }
211    }
212
213    /// Whether the remote could not be read or written at all.
214    #[must_use]
215    pub fn is_remote_unreadable(&self) -> bool {
216        matches!(self, Self::Unreadable { .. })
217    }
218
219    /// Stable slug aligned with former [`Error::kind_name`](crate::error::Error::kind_name) values for absorbed variants.
220    #[must_use]
221    pub fn kind_name(&self) -> &'static str {
222        match self {
223            Self::NoUrl { .. } => "remote_no_url",
224            Self::UnsupportedScheme => "unsupported_scheme",
225            Self::InvalidUrl { .. } => "invalid_url",
226            Self::HttpUnavailable => "http_unavailable",
227            Self::UnknownRemote { .. } => "unknown_remote",
228            Self::RemoteExists { .. } => "remote_exists",
229            Self::InvalidRemoteName { .. } => "invalid_remote_name",
230            Self::Auth { .. } => "auth",
231            Self::CredentialsUnavailable { .. } => "credentials_unavailable",
232            Self::PushAtomicUnsupported => "push_atomic_unsupported",
233            Self::PushOptionsUnsupported => "push_options_unsupported",
234            Self::FetchUnshallowNotShallow => "fetch_unshallow_not_shallow",
235            Self::FetchShallowUnsupported => "fetch_shallow_unsupported",
236            Self::FetchDeepenRelativeUnsupported => "fetch_deepen_relative_unsupported",
237            Self::ReceivedPackTempMissing { .. } => "received_pack_temp_missing",
238            Self::Unreadable { .. } => "remote_unreadable",
239            Self::Fatal { .. } => "remote_fatal",
240            Self::LocalUploadPack(_) => "local_upload_pack",
241            Self::Serve(_) => "serve",
242            Self::LocalUploadPackPanicked => "local_upload_pack_panicked",
243            Self::Resumable(_) => "resumable",
244            Self::FetchRefspec(_) => "fetch_refspec",
245            Self::FetchIntoCheckedOutBranch { .. } => "fetch_into_checked_out_branch",
246            Self::Protocol(_) => "protocol",
247            Self::PushPlan(_) => "push_plan",
248            Self::PartialClone(_) => "partial_clone",
249            Self::MalformedTransportUrl { .. } => "malformed_transport_url",
250            Self::Transport { .. } => "transport",
251            Self::HttpStatus { .. } => "http_status",
252            Self::Ssh { .. } => "ssh",
253            Self::Http { .. } => "http",
254            Self::HttpWorkerPanicked => "http_worker_panicked",
255            Self::HttpLowSpeedStall { .. } => "http_low_speed_stall",
256            Self::Credential { .. } => "credential",
257            Self::Bundle(_) => "bundle",
258            Self::Clone(_) => "clone",
259            Self::Snapshot(_) => "snapshot",
260        }
261    }
262
263    /// Functional area for analytics and JSON (`area`), matching [`Error::area`](crate::error::Error::area) when wrapped.
264    #[must_use]
265    pub fn area(&self) -> &'static str {
266        "remote"
267    }
268
269    /// Build [`RemoteError::Unreadable`] for `url`.
270    #[must_use]
271    pub fn unreadable(url: impl Into<String>, reason: RemoteUnreadableReason) -> Self {
272        Self::Unreadable {
273            url: Some(url.into()),
274            reason,
275        }
276    }
277}