Skip to main content

grit_lib/repo/
repository_error.rs

1//! Repository layout, discovery, init, and embedding failures.
2
3use thiserror::Error;
4
5use std::fmt;
6
7use crate::error::{NotARepositoryReason, PathIoError};
8
9/// One or more unknown `extensions.*` keys (repository format version ≥ 1).
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct UnknownRepositoryExtensions {
12    /// Extension names from the config file, in sorted order.
13    pub extensions: Vec<String>,
14}
15
16impl fmt::Display for UnknownRepositoryExtensions {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        let lead = if self.extensions.len() == 1 {
19            "unknown repository extension found:"
20        } else {
21            "unknown repository extensions found:"
22        };
23        write!(f, "{lead}")?;
24        for ext in &self.extensions {
25            write!(f, "\n\t{ext}")?;
26        }
27        Ok(())
28    }
29}
30
31/// Format version 0 with `extensions.*` keys that require format version 1.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct V1OnlyExtensionsInFormatZero {
34    /// Extension names from the config file, in sorted order.
35    pub extensions: Vec<String>,
36}
37
38impl fmt::Display for V1OnlyExtensionsInFormatZero {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        let lead = if self.extensions.len() == 1 {
41            "repo version is 0, but v1-only extension found:"
42        } else {
43            "repo version is 0, but v1-only extensions found:"
44        };
45        write!(f, "{lead}")?;
46        for ext in &self.extensions {
47            write!(f, "\n\t{ext}")?;
48        }
49        Ok(())
50    }
51}
52use crate::git_dir::GitDirPathOperation;
53use crate::objects::HashAlgo;
54
55/// An operation that only the files-backed object store supports.
56///
57/// Carried by [`RepositoryError::UnsupportedObjectStore`] when a repository whose primary
58/// store is custom (for example a [`MemoryStore`](crate::objects::odb::store::MemoryStore))
59/// is asked to do something that reads or writes the on-disk `objects/` layout: loose
60/// files, packs, `.idx`, multi-pack-index or commit-graph files. Each variant names the
61/// APIs that refuse with it.
62///
63/// [`Self::as_str`] gives a stable snake_case name for scripts (the `operation` field of
64/// `grit --json` errors); [`Display`](fmt::Display) gives a short human phrase.
65///
66/// # Examples
67///
68/// ```
69/// use grit_lib::repo::error::FilesOnlyOperation;
70///
71/// assert_eq!(FilesOnlyOperation::CommitGraphWrite.as_str(), "commit_graph_write");
72/// assert_eq!(FilesOnlyOperation::Gc.to_string(), "garbage collection");
73/// ```
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75#[non_exhaustive]
76pub enum FilesOnlyOperation {
77    /// Garbage collection without a repository: [`Odb::gc`](crate::odb::Odb::gc) on an `Odb`
78    /// built standalone, with no git directory to find reachability roots in.
79    Gc,
80    /// Deleting unreachable objects from a custom primary that cannot delete
81    /// ([`WritableObjectStore::as_prunable`](crate::odb::store::WritableObjectStore::as_prunable)
82    /// is `None`): [`Maintenance::prune_loose_objects`](crate::maintenance::Maintenance::prune_loose_objects),
83    /// [`refs::gc::prune_loose_unreachable`](crate::gc::prune_loose_unreachable),
84    /// [`Odb::gc`](crate::odb::Odb::gc), [`Maintenance::gc`](crate::maintenance::Maintenance::gc). Implement
85    /// [`PrunableObjectStore`](crate::odb::store::PrunableObjectStore) to support them.
86    Prune,
87    /// Repacking into `objects/pack/`: [`Maintenance::repack`](crate::maintenance::Maintenance::repack)
88    /// and [`Maintenance::repack_all`](crate::maintenance::Maintenance::repack_all).
89    Repack,
90    /// Writing `objects/info/commit-graph`: [`Odb::write_commit_graph`](crate::odb::Odb::write_commit_graph) and
91    /// [`Maintenance::write_commit_graph`](crate::maintenance::Maintenance::write_commit_graph). A custom store builds its graph in memory with
92    /// [`Maintenance::build_commit_graph`](crate::maintenance::Maintenance::build_commit_graph) instead.
93    CommitGraphWrite,
94    /// Writing `objects/pack/multi-pack-index`: [`Maintenance::write_midx`](crate::maintenance::Maintenance::write_midx).
95    MidxWrite,
96    /// The files backend's pack and MIDX read cache: [`Odb::pack_store`](crate::odb::Odb::pack_store).
97    PackStore,
98    /// Installing a pack file and its `.idx` under `objects/pack/`:
99    /// [`index_pack::install_pack_bytes`](crate::index_pack::install_pack_bytes) and [`index_pack::install_pack_path`](crate::index_pack::install_pack_path). Use
100    /// [`index_pack::ingest_received_pack`](crate::index_pack::ingest_received_pack) to write a pack into any primary.
101    PackInstall,
102    /// Finding the largest pack index in `objects/pack/`: [`Odb::largest_pack_index_path`](crate::odb::Odb::largest_pack_index_path).
103    LargestPackIndex,
104    /// Writing loose object files into `objects/`: [`Odb::write_local`](crate::odb::Odb::write_local),
105    /// [`Odb::write_raw_local`](crate::odb::Odb::write_raw_local) and [`Odb::write_loose_materialize`](crate::odb::Odb::write_loose_materialize). [`Odb::write`](crate::odb::Odb::write) works with
106    /// any primary.
107    LooseWrite,
108    /// The files-backed primary source itself: [`Odb::primary`](crate::odb::Odb::primary). Use [`Odb::primary_writable`](crate::odb::Odb::primary_writable)
109    /// for the primary of any kind.
110    FilesSource,
111    /// Moving blobs to a large-object promisor: [`Maintenance::offload_blobs`](crate::maintenance::Maintenance::offload_blobs), for the main
112    /// repository and for the promisor repository.
113    Offload,
114    /// Rewriting packs to leave out promised objects, as offload and dropping promised
115    /// blobs do.
116    PromisorRewrite,
117    /// Fetching or cloning with an object filter (a partial clone) into a custom primary.
118    PartialFetch,
119    /// The receive-pack quarantine directory under `objects/`. A custom primary receives
120    /// pushes through an in-memory overlay instead.
121    ReceiveQuarantine,
122    /// Dropping promised blobs from promisor packs: [`Maintenance::drop_promised_blobs`](crate::maintenance::Maintenance::drop_promised_blobs).
123    DropLargeBlobs,
124}
125
126impl FilesOnlyOperation {
127    /// Stable snake_case name (`"gc"`, `"commit_graph_write"`, …) for scripts and JSON.
128    ///
129    /// Names never change once released; new variants add new names.
130    #[must_use]
131    pub const fn as_str(self) -> &'static str {
132        match self {
133            Self::Gc => "gc",
134            Self::Prune => "prune",
135            Self::Repack => "repack",
136            Self::CommitGraphWrite => "commit_graph_write",
137            Self::MidxWrite => "midx_write",
138            Self::PackStore => "pack_store",
139            Self::PackInstall => "pack_install",
140            Self::LargestPackIndex => "largest_pack_index",
141            Self::LooseWrite => "loose_write",
142            Self::FilesSource => "files_source",
143            Self::Offload => "offload",
144            Self::PromisorRewrite => "promisor_rewrite",
145            Self::PartialFetch => "partial_fetch",
146            Self::ReceiveQuarantine => "receive_quarantine",
147            Self::DropLargeBlobs => "drop_large_blobs",
148        }
149    }
150}
151
152impl fmt::Display for FilesOnlyOperation {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.write_str(match self {
155            Self::Gc => "garbage collection",
156            Self::Prune => "pruning unreachable objects",
157            Self::Repack => "repacking",
158            Self::CommitGraphWrite => "writing a commit-graph file",
159            Self::MidxWrite => "writing a multi-pack-index",
160            Self::PackStore => "the pack read cache",
161            Self::PackInstall => "installing a pack file",
162            Self::LargestPackIndex => "finding the largest pack index",
163            Self::LooseWrite => "writing loose object files",
164            Self::FilesSource => "opening the files-backed primary",
165            Self::Offload => "offloading blobs",
166            Self::PromisorRewrite => "rewriting promisor packs",
167            Self::PartialFetch => "a partial fetch",
168            Self::ReceiveQuarantine => "the receive quarantine directory",
169            Self::DropLargeBlobs => "dropping promised blobs",
170        })
171    }
172}
173
174/// Failures opening, discovering, initializing, or validating a repository layout.
175#[derive(Debug, Error)]
176#[non_exhaustive]
177pub enum RepositoryError {
178    /// A repository could not be found or is structurally invalid.
179    #[error("not a git repository (or any of the parent directories): {0}")]
180    NotARepository(NotARepositoryReason),
181
182    /// A bare repository was found but access is forbidden by `safe.bareRepository`.
183    #[error("cannot use bare repository '{path}' (safe.bareRepository is 'explicit')")]
184    ForbiddenBareRepository {
185        /// Display path of the bare repository that was rejected.
186        path: String,
187    },
188
189    /// The repository is owned by a different user (`safe.directory`).
190    #[error("detected dubious ownership in repository at '{path}'")]
191    DubiousOwnership {
192        /// Display path that failed the ownership check.
193        path: String,
194        /// Owner uid of the path when known.
195        owner_uid: Option<u32>,
196        /// Effective uid of the current process when known.
197        effective_uid: Option<u32>,
198    },
199
200    /// Repository format version is not supported by this implementation.
201    #[error("unsupported repository format version '{version}'")]
202    UnsupportedRepositoryFormatVersion {
203        /// Parsed `core.repositoryformatversion`.
204        version: u32,
205    },
206
207    /// `extensions.refStorage` names an unsupported backend.
208    #[error("invalid value for 'extensions.refstorage': '{value}'")]
209    InvalidRefStorageFormat {
210        /// Raw `extensions.refStorage` value from the repository config.
211        value: String,
212    },
213
214    /// [`super::Repository::init`] refused to change object format on reinit.
215    #[error("cannot change object format in an existing repository")]
216    InitObjectFormatChange,
217
218    /// [`super::Repository::init`] with incompatible `--bare` and separate git dir.
219    #[error("cannot combine bare repository with separate git directory")]
220    InitBareWithSeparateGitDir,
221
222    /// [`super::Repository::init`] was asked for an on-disk ref storage format while
223    /// [`RepositoryOptions::with_ref_store`](crate::config::environment::RepositoryOptions::with_ref_store)
224    /// injects the ref backend.
225    #[error("cannot create {requested} ref storage: the ref store is injected")]
226    InitRefStorageWithInjectedRefStore {
227        /// The ref storage format [`InitOptions::ref_storage`](super::InitOptions::ref_storage) requested.
228        requested: crate::ref_storage::RefStorageFormat,
229    },
230
231    /// Command requires a working tree but the repository is bare.
232    #[error("this operation needs a working tree")]
233    RequiresWorkTree,
234
235    /// [`super::Repository::prefetch_promised`] was called without a promisor fetcher on the handle.
236    #[error("promisor prefetch requires a PromisorFetcher on RepositoryOptions")]
237    PromisorFetcherMissing,
238
239    /// Repository format version 1+ declares an extension this implementation does not recognize.
240    #[error("{0}")]
241    UnknownRepositoryExtensions(UnknownRepositoryExtensions),
242
243    /// Format version 0 declares an extension that requires format version 1 or newer.
244    #[error("{0}")]
245    V1OnlyExtensionsInFormatZero(V1OnlyExtensionsInFormatZero),
246
247    /// Filesystem I/O failed on a path under the repository git directory.
248    #[error("{0}")]
249    GitDirPathIo(PathIoError),
250
251    /// The operation needs the files-backed `objects/` directory, but the repository uses a custom primary store.
252    #[error(
253        "{operation} needs the files-backed object store, but this repository's primary store is custom"
254    )]
255    UnsupportedObjectStore {
256        /// The operation that was refused.
257        operation: FilesOnlyOperation,
258    },
259
260    /// The operation would delete objects, and `extensions.preciousObjects` forbids it.
261    #[error("{operation} deletes objects, which extensions.preciousObjects forbids here")]
262    PreciousObjectsRepository {
263        /// Operation that was refused (for example `"drop-large-blobs"`).
264        operation: &'static str,
265    },
266
267    /// Injected object store hash algorithm differs from the repository's `extensions.objectformat`.
268    #[error(
269        "object store hashes with {} but the repository's object format is {}",
270        store.name(),
271        repository.name()
272    )]
273    ObjectFormatMismatch {
274        /// The repository's object format from its config.
275        repository: HashAlgo,
276        /// The first injected store's algorithm that differs from `repository`.
277        store: HashAlgo,
278    },
279
280    /// Another maintenance run holds the repository's `gc.pid` lock
281    /// ([`crate::maintenance::GcLock`]); nothing was changed.
282    #[error("{}", crate::error::maintenance_running_message(holder))]
283    MaintenanceRunning {
284        /// Process recorded in `gc.pid`.
285        holder: crate::maintenance::GcLockHolder,
286    },
287}
288
289impl RepositoryError {
290    /// Stable snake_case name (same slugs as the legacy umbrella variants for these failures).
291    #[must_use]
292    pub fn kind_name(&self) -> &'static str {
293        match self {
294            Self::NotARepository(..) => "not_a_repository",
295            Self::ForbiddenBareRepository { .. } => "forbidden_bare_repository",
296            Self::DubiousOwnership { .. } => "dubious_ownership",
297            Self::UnsupportedRepositoryFormatVersion { .. } => {
298                "unsupported_repository_format_version"
299            }
300            Self::InvalidRefStorageFormat { .. } => "invalid_ref_storage_format",
301            Self::InitObjectFormatChange => "init_object_format_change",
302            Self::InitBareWithSeparateGitDir => "init_bare_with_separate_git_dir",
303            Self::InitRefStorageWithInjectedRefStore { .. } => {
304                "init_ref_storage_with_injected_ref_store"
305            }
306            Self::RequiresWorkTree => "requires_work_tree",
307            Self::PromisorFetcherMissing => "message",
308            Self::UnknownRepositoryExtensions(_) | Self::V1OnlyExtensionsInFormatZero(_) => {
309                "message"
310            }
311            Self::GitDirPathIo(io) => match io.operation {
312                crate::error::PathIoOperation::GitDir(_) => "git_dir_path_io",
313                crate::error::PathIoOperation::Worktree(_) => "worktree_path_io",
314            },
315            Self::UnsupportedObjectStore { .. } => "unsupported_object_store",
316            Self::PreciousObjectsRepository { .. } => "precious_objects_repository",
317            Self::ObjectFormatMismatch { .. } => "object_format_mismatch",
318            Self::MaintenanceRunning { .. } => "maintenance_running",
319        }
320    }
321
322    /// Functional area for analytics and JSON (`area`), matching [`crate::error::Error::area`] when wrapped.
323    #[must_use]
324    pub fn area(&self) -> &'static str {
325        match self {
326            Self::GitDirPathIo(io) => match io.operation {
327                crate::error::PathIoOperation::GitDir(_) => "repository",
328                crate::error::PathIoOperation::Worktree(_) => "worktree",
329            },
330            Self::RequiresWorkTree
331            | Self::PromisorFetcherMissing
332            | Self::UnknownRepositoryExtensions(_)
333            | Self::V1OnlyExtensionsInFormatZero(_) => "repository",
334            _ => "repository",
335        }
336    }
337
338    /// Build [`Self::GitDirPathIo`] from git-dir path context (legacy call sites).
339    #[must_use]
340    pub fn git_dir_path_io(
341        path: impl Into<String>,
342        operation: GitDirPathOperation,
343        source: std::io::Error,
344    ) -> Self {
345        Self::GitDirPathIo(PathIoError::git_dir(path, operation, source))
346    }
347}
348
349impl From<PathIoError> for RepositoryError {
350    fn from(value: PathIoError) -> Self {
351        Self::GitDirPathIo(value)
352    }
353}
354
355/// Convenience alias for repository open/discover/init APIs.
356pub type RepositoryResult<T> = std::result::Result<T, RepositoryError>;
357
358#[cfg(test)]
359#[path = "files_only_operation_tests.rs"]
360mod files_only_operation_tests;