grit_lib/refs/store/error.rs
1//! Errors for [`super::RefStore`] operations.
2
3use std::fmt;
4use std::sync::Arc;
5
6use crate::git_dir::GitDirPathOperation;
7use crate::objects::{ObjectId, ObjectKind};
8use crate::refs::RefnameUnavailable;
9
10use super::{Expected, RawRef};
11
12/// Failure modes for reference store reads and transactions.
13#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
14#[non_exhaustive]
15pub enum RefStoreError {
16 /// Reflog contents changed between a snapshot and a locked [`super::RefStore::rewrite_reflog`]
17 /// re-read. Callers that compare against an earlier snapshot should retry.
18 #[error("reflog '{name}' changed during rewrite")]
19 ReflogRewriteStale {
20 /// Ref whose log no longer matched the expected prefix.
21 name: String,
22 },
23
24 /// Another writer holds a lock this transaction needs.
25 ///
26 /// For per-ref backends (files) that is the lock of `name` itself; for a backend with one
27 /// writer slot for the whole store ([`super::MemoryRefStore`], a database with a single
28 /// write transaction) it means that slot is busy, whichever refs the holder updates.
29 /// Transient: [`crate::refs::prepare_with_lock_wait`] retries it.
30 #[error("cannot lock ref '{name}': lock held")]
31 LockHeld {
32 /// A ref of the failed transaction: the locked ref, or the transaction's first ref
33 /// when the whole store is locked. Always one of the failed transaction's own refs.
34 name: String,
35 },
36
37 /// Compare-and-swap or existence check failed for an update.
38 #[error("ref '{name}' did not match expected state")]
39 ExpectedMismatch {
40 /// Ref that failed the check.
41 name: String,
42 /// What the caller required.
43 expected: Expected,
44 /// What was observed (`None` when the ref is absent).
45 actual: Option<RawRef>,
46 },
47
48 /// A ref name cannot be created because of a directory/file conflict.
49 #[error("cannot lock ref '{}': {}", reason.refname(), reason.lock_message_suffix())]
50 NameUnavailable {
51 /// Structured conflict reason (Git `refs_verify_refname_available` style).
52 reason: RefnameUnavailable,
53 },
54
55 /// A create was requested for a ref name that already exists under ASCII case folding
56 /// when `core.ignorecase` is enabled (or the git directory is on a case-insensitive
57 /// volume).
58 #[error("reference '{name}' already exists")]
59 CreateExists {
60 /// Ref the caller tried to create.
61 name: String,
62 },
63
64 /// Two creates in one transaction differ only by ASCII case while `core.ignorecase`
65 /// is enabled. The files ref backend cannot store both as loose refs; packed-refs
66 /// during an initial clone can hold both spellings.
67 #[error("cannot store refs '{name}' and '{other}' together when core.ignorecase is enabled")]
68 CaseConflict {
69 /// One ref in the conflicting pair.
70 name: String,
71 /// The other ref, equal under ASCII case folding.
72 other: String,
73 },
74
75 /// The same ref name appears more than once in one transaction.
76 #[error("multiple updates for ref '{name}' not allowed")]
77 DuplicateUpdate {
78 /// Duplicate ref name.
79 name: String,
80 },
81
82 /// Symbolic reference resolution exceeded [`crate::refs::SYMREF_MAXDEPTH`].
83 #[error("symbolic ref loop or chain too deep")]
84 SymrefLoop,
85
86 /// The ref (or the target at the end of its symbolic chain) does not exist.
87 #[error("ref not found: {name}")]
88 NotFound {
89 /// Name of the missing ref: the requested name, or the dangling symbolic target.
90 name: String,
91 },
92
93 /// Stored data for a ref or reflog is malformed.
94 #[error("corrupt ref store: {detail}")]
95 Corrupt {
96 /// What is wrong with the stored refs.
97 detail: String,
98 },
99
100 /// Filesystem I/O on a git-directory path during ref store work.
101 #[error("{}", crate::git_dir::io_error::format_git_dir_io_message(.path, *operation, &Self::git_dir_io_source(*.os_error)))]
102 GitDirPathIo {
103 /// Display path such as `.git/refs/heads/main` or `.git/worktrees/wt/HEAD.lock`.
104 path: String,
105 /// What the operation was trying to do when I/O failed.
106 operation: GitDirPathOperation,
107 /// Raw OS error code from the failing I/O call.
108 os_error: i32,
109 },
110
111 /// Ref name is not safe to store (traversal, illegal component, etc.).
112 ///
113 /// Every backend checks update names and both sides of reflog and case-only renames
114 /// in [`super::RefStore::prepare`], before taking locks.
115 #[error("refusing to update ref with bad name '{name}'")]
116 InvalidRefName {
117 /// The rejected ref name.
118 name: String,
119 },
120
121 /// A symbolic ref would point at a target Git refuses (outside `refs/` for `HEAD`, not
122 /// safe to store, or the same name as the ref being updated).
123 #[error("refusing to point '{name}' at symbolic target '{target}'")]
124 InvalidSymrefTarget {
125 /// The ref being updated.
126 name: String,
127 /// The symbolic target that was rejected.
128 target: String,
129 },
130
131 /// An update would store the all-zero (null) object id as a direct ref value.
132 ///
133 /// The null id names no object, so Git treats such a ref as broken. Delete a ref with
134 /// `new_value: None` instead. Reflog-only updates
135 /// ([`super::RefUpdateFlags::log_only`]) may still carry the null id.
136 #[error("refusing to point ref '{name}' at the null object id")]
137 NullOid {
138 /// The ref the update targeted.
139 name: String,
140 },
141
142 /// An update would point a ref at an object the repository does not store.
143 ///
144 /// Raised by the stores a [`crate::repo::Repository`] hands out (see
145 /// [`super::RefStore::prepare`]); the bare backends do not look at objects. Set
146 /// [`super::RefUpdateFlags::skip_oid_verification`] to write such a ref on purpose.
147 #[error("refusing to point ref '{name}' at {oid}: no such object in the repository")]
148 MissingObject {
149 /// The ref the update targeted.
150 name: String,
151 /// The object id the update would store.
152 oid: ObjectId,
153 },
154
155 /// An update would point a branch (`refs/heads/…`) or `HEAD` at something other than a
156 /// commit.
157 ///
158 /// Checked alongside [`Self::MissingObject`]. Tags, remote-tracking and other refs may
159 /// name any object.
160 #[error("refusing to point '{name}' at {kind} {oid}: branches and HEAD must name a commit")]
161 NotACommit {
162 /// The branch or `HEAD` the update targeted.
163 name: String,
164 /// The object id the update would store.
165 oid: ObjectId,
166 /// What `oid` actually is.
167 kind: ObjectKind,
168 },
169
170 /// Looking up the object an update would store failed (unreadable pack, I/O, a failing
171 /// custom object store), so the update could not be checked.
172 #[error("cannot check object {oid} for ref '{name}': {source}")]
173 ObjectLookup {
174 /// The ref the update targeted.
175 name: String,
176 /// The object id the update would store.
177 oid: ObjectId,
178 /// The object database error, downcastable to [`crate::error::Error`].
179 source: BackendError,
180 },
181
182 /// Reflog identity or message would forge or corrupt a log line.
183 #[error(transparent)]
184 InvalidReflog(#[from] crate::ident::SignatureError),
185
186 /// A custom backend's own storage failed (database, network, …).
187 ///
188 /// Built-in backends never return this; their I/O failures stay typed elsewhere.
189 #[error(transparent)]
190 Backend(BackendError),
191
192 /// A `reference-transaction` hook refused or could not run on the `prepared` phase.
193 #[error(transparent)]
194 Hook(ReferenceTransactionHookErr),
195}
196
197/// [`RefStoreError::Hook`] payload ( [`crate::hooks::HookError`] is not `Clone`).
198#[derive(Clone, Debug)]
199pub struct ReferenceTransactionHookErr(Arc<crate::hooks::HookError>);
200
201impl PartialEq for ReferenceTransactionHookErr {
202 fn eq(&self, other: &Self) -> bool {
203 self.0.to_string() == other.0.to_string()
204 }
205}
206
207impl Eq for ReferenceTransactionHookErr {}
208
209impl From<crate::hooks::HookError> for ReferenceTransactionHookErr {
210 fn from(value: crate::hooks::HookError) -> Self {
211 Self(Arc::new(value))
212 }
213}
214
215impl ReferenceTransactionHookErr {
216 pub(crate) fn into_hook_error(self) -> crate::hooks::HookError {
217 Arc::try_unwrap(self.0).unwrap_or_else(|arc| match arc.as_ref() {
218 crate::hooks::HookError::Failed {
219 hook_name,
220 status,
221 output,
222 } => crate::hooks::HookError::Failed {
223 hook_name: hook_name.clone(),
224 status: *status,
225 output: output.clone(),
226 },
227 crate::hooks::HookError::Spawn {
228 hook_name,
229 path,
230 source,
231 output,
232 } => crate::hooks::HookError::Spawn {
233 hook_name: hook_name.clone(),
234 path: path.clone(),
235 source: std::io::Error::new(source.kind(), source.to_string()),
236 output: output.clone(),
237 },
238 crate::hooks::HookError::MissingHookCommand { hook_name } => {
239 crate::hooks::HookError::MissingHookCommand {
240 hook_name: hook_name.clone(),
241 }
242 }
243 })
244 }
245}
246
247impl std::fmt::Display for ReferenceTransactionHookErr {
248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249 self.0.fmt(f)
250 }
251}
252
253impl std::error::Error for ReferenceTransactionHookErr {
254 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
255 Some(self.0.as_ref())
256 }
257}
258
259impl RefStoreError {
260 pub(crate) fn git_dir_path_io(
261 path: String,
262 operation: GitDirPathOperation,
263 source: std::io::Error,
264 ) -> Self {
265 Self::GitDirPathIo {
266 path,
267 operation,
268 os_error: source.raw_os_error().unwrap_or(0),
269 }
270 }
271
272 pub(crate) fn git_dir_io_source(os_error: i32) -> std::io::Error {
273 if os_error == 0 {
274 std::io::Error::from(std::io::ErrorKind::Other)
275 } else {
276 std::io::Error::from_raw_os_error(os_error)
277 }
278 }
279
280 pub(crate) fn not_found(name: &str) -> Self {
281 Self::NotFound {
282 name: name.to_owned(),
283 }
284 }
285
286 /// Wrap a custom backend's storage error as [`Self::Backend`].
287 pub fn backend(err: impl std::error::Error + Send + Sync + 'static) -> Self {
288 Self::Backend(BackendError::new(err))
289 }
290}
291
292/// A custom ref backend's storage error, carried by [`RefStoreError::Backend`].
293///
294/// Cheap to clone (the error is shared). Two values are equal only when they share the same
295/// underlying error. Use [`Self::downcast_ref`] to recover the backend's concrete type.
296#[derive(Clone)]
297pub struct BackendError(Arc<dyn std::error::Error + Send + Sync + 'static>);
298
299impl BackendError {
300 /// Wrap `err`.
301 pub fn new(err: impl std::error::Error + Send + Sync + 'static) -> Self {
302 Self(Arc::new(err))
303 }
304
305 /// Borrow the wrapped error.
306 #[must_use]
307 pub fn get_ref(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
308 self.0.as_ref()
309 }
310
311 /// The wrapped error as `E`, when it has that type.
312 #[must_use]
313 pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
314 self.0.downcast_ref::<E>()
315 }
316}
317
318impl fmt::Debug for BackendError {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 fmt::Debug::fmt(&self.0, f)
321 }
322}
323
324impl fmt::Display for BackendError {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 fmt::Display::fmt(&self.0, f)
327 }
328}
329
330impl std::error::Error for BackendError {
331 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
332 self.0.source()
333 }
334}
335
336impl PartialEq for BackendError {
337 fn eq(&self, other: &Self) -> bool {
338 Arc::ptr_eq(&self.0, &other.0)
339 }
340}
341
342impl Eq for BackendError {}
343
344impl From<BackendError> for RefStoreError {
345 fn from(err: BackendError) -> Self {
346 Self::Backend(err)
347 }
348}
349
350impl From<RefnameUnavailable> for RefStoreError {
351 fn from(reason: RefnameUnavailable) -> Self {
352 Self::NameUnavailable { reason }
353 }
354}