Skip to main content

grit_lib/
diagnostics.rs

1//! Git-style diagnostic prefixes and typed warning sinks for embedders and the CLI.
2//!
3//! Prefix helpers keep `fatal:` / `warning:` literals out of call sites. Structured
4//! [`Warning`] values flow through [`DiagnosticSink`] implementations; human-readable
5//! text is formatted by embedders (for example `grit-cli`), not by `grit-lib`.
6//!
7//! Library guide: [diagnostics](https://grit-scm.com/docs/library/embedding)
8//!
9//! ```rust
10//! use grit_lib::repo::{InitOptions, Repository};
11//! # fn main() -> grit_lib::error::Result<()> {
12//! let dir = tempfile::tempdir()?;
13//! let _repo = Repository::init(dir.path(), &InitOptions::default())?;
14//! # Ok(())
15//! # }
16//! ```
17
18use std::collections::HashSet;
19use std::path::PathBuf;
20use std::sync::{Arc, Mutex};
21
22/// Prefix a body with Git's `warning: ` diagnostic marker.
23#[must_use]
24pub fn warning_line(body: &str) -> String {
25    ["warning", ": ", body].concat()
26}
27
28/// Prefix a body with Git's `error: ` diagnostic marker.
29#[must_use]
30pub fn error_line(body: &str) -> String {
31    ["error", ": ", body].concat()
32}
33
34/// Prefix a body with Git's `fatal: ` diagnostic marker.
35#[must_use]
36pub fn fatal_line(body: &str) -> String {
37    ["fatal", ": ", body].concat()
38}
39
40/// A non-fatal condition worth surfacing to the user or an embedder.
41#[non_exhaustive]
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
43pub enum Warning {
44    /// A ref name could mean both a branch/tag ref and an object id prefix.
45    AmbiguousRefname {
46        /// User-supplied revision or pathspec fragment.
47        spec: String,
48    },
49    /// A symbolic ref pointed at a missing or invalid target (except bare `HEAD`).
50    DanglingSymref {
51        /// Pack file name or config identifier.
52        name: String,
53    },
54    /// A commit-graph chunk was smaller than required.
55    CommitGraphChunkTooSmall {
56        /// Commit-graph layer identifier in the warning.
57        layer: String,
58        /// Commit-graph chunk name that failed validation.
59        chunk: String,
60    },
61    /// Bloom filters were disabled for a commit-graph layer due to incompatible settings.
62    CommitGraphBloomDisabled {
63        /// Commit-graph layer identifier in the warning.
64        layer: String,
65    },
66    /// Changed-path Bloom index chunk does not cover all commits in the layer.
67    CommitGraphChangedPathIndexTooSmall,
68    /// Changed-path Bloom data chunk header is too small.
69    CommitGraphChangedPathChunkTooSmall {
70        /// Observed size or offset in bytes.
71        actual: usize,
72        /// Minimum required size in bytes.
73        minimum: usize,
74    },
75    /// Changed-path Bloom index entry points past the chunk.
76    CommitGraphChangedPathOffsetOutOfRange {
77        /// Byte offset into a commit-graph chunk.
78        offset: usize,
79        /// Index of the commit-graph entry being validated.
80        position: usize,
81        /// Path or label of the commit-graph file.
82        graph: String,
83        /// Total size of the commit-graph chunk in bytes.
84        chunk_size: usize,
85    },
86    /// Changed-path Bloom index offsets decrease between adjacent entries.
87    CommitGraphChangedPathOffsetsDecreasing {
88        /// Starting offset for an adjacent pair of entries.
89        start: usize,
90        /// Ending offset for an adjacent pair of entries.
91        end: usize,
92        /// Commit index for the start offset.
93        position_start: usize,
94        /// Commit index for the end offset.
95        position_end: usize,
96        /// Path or label of the commit-graph file.
97        graph: String,
98    },
99    /// Repository config was skipped because the git directory uses an unsupported format.
100    IgnoredGitDir {
101        /// Repository-relative or filesystem path related to the failure.
102        path: PathBuf,
103        /// Why the value or operation was rejected.
104        reason: String,
105    },
106    /// `core.bare=true` while `core.worktree` is also set.
107    CoreBareWithWorktree,
108    /// A config value looked boolean but could not be parsed.
109    BadBooleanConfig {
110        /// Config key name that failed validation.
111        key: String,
112        /// Raw config value that could not be parsed.
113        value: String,
114    },
115    /// Submodule name failed validation.
116    SuspiciousSubmoduleName {
117        /// Pack file name or config identifier.
118        name: String,
119    },
120    /// Submodule config value looked like a command-line flag.
121    SubmoduleConfigLooksLikeOption {
122        /// Config key name that failed validation.
123        key: String,
124        /// Raw config value that could not be parsed.
125        value: String,
126    },
127    /// Duplicate submodule keys in `.gitmodules` for one commit tree.
128    SubmoduleMultipleConfigs {
129        /// Commit object id or label tied to the warning.
130        commit: String,
131        /// Pack file name or config identifier.
132        name: String,
133        /// Config option or submodule key name.
134        option: String,
135    },
136    /// `.gitmodules` could not be parsed at a given line.
137    GitmodulesBadConfig {
138        /// Free-form diagnostic message body.
139        message: String,
140    },
141    /// Split index was requested while `core.splitIndex` disables it.
142    SplitIndexDisabledWhileConfigEnabled,
143    /// Split index was disabled on the command line while config enables it.
144    SplitIndexEnabledWhileConfigDisabled,
145    /// `GIT_INDEX_VERSION` was set but invalid.
146    IndexVersionEnvInvalid {
147        /// Index version used after the invalid setting was ignored.
148        fallback: u32,
149    },
150    /// `index.version` in config was invalid.
151    IndexVersionConfigInvalid {
152        /// Index version used after the invalid setting was ignored.
153        fallback: u32,
154    },
155    /// `mailmap.blob` (or the bare-repository `HEAD:.mailmap` default) names an object that
156    /// is not a blob; it was skipped.
157    MailmapUnreadable {
158        /// The configured blob revision, as written.
159        spec: String,
160        /// Kind of the object the revision resolved to.
161        kind: crate::objects::ObjectKind,
162    },
163    /// A ref was updated but its reflog line could not be appended; the update stands.
164    ReflogNotWritten {
165        /// Ref whose reflog was not updated (for example `refs/heads/main` or `HEAD`).
166        refname: String,
167        /// Why the append failed.
168        detail: String,
169    },
170    /// A traditional hook script exists but is not executable.
171    NonExecutableHookIgnored {
172        /// Hook script basename that was skipped.
173        hook_name: String,
174        /// Resolved path to the hook script, when known.
175        hook_path: Option<PathBuf>,
176    },
177    /// A hook whose outcome does not affect the operation (such as `post-commit`) could not be
178    /// run; the operation already completed.
179    HookNotRun {
180        /// Hook event name (`post-commit`, …).
181        hook_name: String,
182        /// Why it did not run, including the underlying OS error.
183        detail: String,
184    },
185    /// Returned when midx checksum mismatch.
186    MidxChecksumMismatch,
187    /// Returned when midx ignoring existing checksum mismatch.
188    MidxIgnoringExistingChecksumMismatch,
189    /// Returned when midx chunk table error.
190    MidxChunkTableError {
191        /// Additional human-readable detail for the failure.
192        detail: String,
193    },
194    /// Returned when midx rev index wrong size.
195    MidxRevIndexWrongSize,
196    /// Returned when midx bitmap missing reverse index.
197    MidxBitmapMissingReverseIndex,
198    /// Returned when midx pack index unavailable.
199    MidxPackIndexUnavailable {
200        /// Pack file basename (`.pack` suffix).
201        pack: String,
202    },
203    /// Returned when midx unknown preferred pack.
204    MidxUnknownPreferredPack {
205        /// Pack file name or config identifier.
206        name: String,
207    },
208    /// A `.bitmap` sidecar was present but could not be loaded; reachability falls back without it.
209    PackBitmapIgnored {
210        /// Repository-relative or filesystem path related to the failure.
211        path: PathBuf,
212        /// Why the value or operation was rejected.
213        reason: String,
214    },
215}
216
217/// Optional trace events (network debugging, etc.), separate from [`Warning`].
218#[non_exhaustive]
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub enum Trace {
221    /// Returned when network.
222    Network {
223        /// Human-readable message body.
224        message: String,
225    },
226}
227
228/// Receives warnings and optional trace lines from `grit-lib`.
229pub trait DiagnosticSink: Send + Sync {
230    /// Record a non-fatal warning.
231    fn warn(&self, warning: Warning);
232    /// Record a trace event (no-op by default).
233    fn trace(&self, event: Trace) {
234        let _ = event;
235    }
236}
237
238/// Discards all diagnostics (default for [`crate::repo::Repository`]).
239#[derive(Debug, Default, Clone, Copy)]
240pub struct NullDiagnostics;
241
242impl DiagnosticSink for NullDiagnostics {
243    fn warn(&self, _warning: Warning) {}
244}
245
246/// Collects warnings (and traces) for tests and the CLI.
247#[derive(Debug)]
248pub struct CollectingDiagnostics {
249    warnings: Mutex<Vec<Warning>>,
250    traces: Mutex<Vec<Trace>>,
251    dedupe: bool,
252    seen: Mutex<HashSet<Warning>>,
253}
254
255impl Default for CollectingDiagnostics {
256    fn default() -> Self {
257        Self::new()
258    }
259}
260
261impl CollectingDiagnostics {
262    /// Create a collector that records every warning.
263    #[must_use]
264    pub fn new() -> Self {
265        Self {
266            warnings: Mutex::new(Vec::new()),
267            traces: Mutex::new(Vec::new()),
268            dedupe: false,
269            seen: Mutex::new(HashSet::new()),
270        }
271    }
272
273    /// When `dedupe` is true, identical [`Warning`] values are stored at most once.
274    #[must_use]
275    pub fn with_dedupe(dedupe: bool) -> Self {
276        Self {
277            dedupe,
278            ..Self::new()
279        }
280    }
281
282    /// Snapshot collected warnings (clone of each entry).
283    #[must_use]
284    pub fn warnings(&self) -> Vec<Warning> {
285        self.warnings
286            .lock()
287            .unwrap_or_else(|e| e.into_inner())
288            .clone()
289    }
290
291    /// Snapshot collected trace events.
292    #[must_use]
293    pub fn traces(&self) -> Vec<Trace> {
294        self.traces
295            .lock()
296            .unwrap_or_else(|e| e.into_inner())
297            .clone()
298    }
299
300    /// Drop all collected warnings and traces.
301    pub fn clear(&self) {
302        self.warnings
303            .lock()
304            .unwrap_or_else(|e| e.into_inner())
305            .clear();
306        self.traces
307            .lock()
308            .unwrap_or_else(|e| e.into_inner())
309            .clear();
310        self.seen.lock().unwrap_or_else(|e| e.into_inner()).clear();
311    }
312}
313
314impl DiagnosticSink for CollectingDiagnostics {
315    fn warn(&self, warning: Warning) {
316        if self.dedupe {
317            let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());
318            if !seen.insert(warning.clone()) {
319                return;
320            }
321        }
322        self.warnings
323            .lock()
324            .unwrap_or_else(|e| e.into_inner())
325            .push(warning);
326    }
327
328    fn trace(&self, event: Trace) {
329        self.traces
330            .lock()
331            .unwrap_or_else(|e| e.into_inner())
332            .push(event);
333    }
334}
335
336/// Shared handle used when threading diagnostics through load paths.
337pub type DiagnosticsHandle = Arc<dyn DiagnosticSink + Send + Sync>;
338
339/// Emit `warning` through `handle`.
340pub fn warn(handle: &DiagnosticsHandle, warning: Warning) {
341    handle.warn(warning);
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347
348    #[test]
349    fn collecting_diagnostics_records_warnings() {
350        let sink = CollectingDiagnostics::new();
351        sink.warn(Warning::AmbiguousRefname { spec: "abc".into() });
352        assert_eq!(sink.warnings().len(), 1);
353    }
354
355    #[test]
356    fn collecting_diagnostics_dedupes_identical_warnings() {
357        let sink = CollectingDiagnostics::with_dedupe(true);
358        let w = Warning::CommitGraphChunkTooSmall {
359            layer: "layer-a".into(),
360            chunk: "base graphs".into(),
361        };
362        sink.warn(w.clone());
363        sink.warn(w);
364        assert_eq!(sink.warnings().len(), 1);
365    }
366}