Skip to main content

objects/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Shared error types across Heddle crates.
3
4use std::{error::Error, fmt, path::Path};
5
6use crate::object::{ContentHash, StateId, TreeError};
7
8/// Structured recovery details that can cross the embeddable facade boundary.
9#[derive(Debug, Clone, PartialEq)]
10pub struct RecoveryDetails {
11    pub kind: &'static str,
12    pub error: String,
13    pub hint: String,
14    pub unsafe_condition: String,
15    pub would_change: String,
16    pub preserved: String,
17    /// Explicit, path-specific recovery commands. When present these override
18    /// the `kind`-keyed fallback the CLI envelope would otherwise reconstruct
19    /// (the first entry is the primary command). `None` = use the generic
20    /// per-`kind` recovery mapping.
21    pub recovery_commands: Option<Vec<String>>,
22}
23
24impl RecoveryDetails {
25    pub fn safety_refusal(
26        kind: &'static str,
27        error: impl Into<String>,
28        hint: impl Into<String>,
29        unsafe_condition: impl Into<String>,
30        would_change: impl Into<String>,
31        already_preserved: impl Into<String>,
32    ) -> Self {
33        Self {
34            kind,
35            error: error.into(),
36            hint: hint.into(),
37            unsafe_condition: unsafe_condition.into(),
38            would_change: would_change.into(),
39            preserved: already_preserved.into(),
40            recovery_commands: None,
41        }
42    }
43
44    /// Attach explicit, path-specific recovery commands (the first entry is the
45    /// primary command). Used where the callsite has context — e.g. a source
46    /// checkout path — that the `kind`-keyed CLI fallback cannot reconstruct.
47    #[must_use]
48    pub fn with_recovery_commands(mut self, commands: Vec<String>) -> Self {
49        self.recovery_commands = Some(commands);
50        self
51    }
52
53    pub fn invalid_usage(
54        kind: &'static str,
55        error: impl Into<String>,
56        hint: impl Into<String>,
57    ) -> Self {
58        Self::safety_refusal(
59            kind,
60            error,
61            hint,
62            "the command arguments do not describe a valid operation",
63            "running with ambiguous or invalid arguments could target the wrong repository state or metadata",
64            "no repository objects, refs, metadata, or worktree files were changed",
65        )
66    }
67
68    pub fn feature_unavailable(command: &str, feature: &str) -> Self {
69        Self::safety_refusal(
70            "feature_unavailable",
71            format!("{command} requires building heddle with --features {feature}"),
72            format!(
73                "Use a binary built with the `{feature}` feature, or rerun without the feature-specific flag."
74            ),
75            format!("this heddle binary was built without the `{feature}` feature"),
76            format!("{command} cannot run because the requested analysis engine is unavailable"),
77            "repository state, refs, and worktree files were left unchanged",
78        )
79    }
80
81    pub fn serialization_error(detail: impl fmt::Display) -> Self {
82        Self::safety_refusal(
83            "state_corrupted",
84            "Repository state is corrupted or unreadable",
85            "Inspect repository integrity before attempting repair.",
86            format!("a stored repository object failed to decode: {detail}"),
87            "continuing would read or write through repository state Heddle cannot decode",
88            "the command stopped before mutating repository state; intact objects were left unchanged",
89        )
90    }
91
92    pub fn repository_integrity_error(error: impl Into<String>) -> Self {
93        Self::safety_refusal(
94            "repository_integrity_error",
95            error,
96            "Inspect repository integrity, then restore or repair the reported object/ref.",
97            "repository object or ref integrity did not pass validation",
98            "continuing could compound corruption or hide the missing object",
99            "the command stopped before applying the requested mutation",
100        )
101    }
102
103    pub fn repository_not_found(path: &Path) -> Self {
104        Self::safety_refusal(
105            "repository_not_found",
106            format!("repository not found at {}", path.display()),
107            "Initialize the requested repository before running repository commands.",
108            format!("no Heddle repository was found at '{}'", path.display()),
109            "the command cannot inspect or change repository state until initialization",
110            "no repository objects, refs, metadata, or worktree files were changed",
111        )
112    }
113
114    pub fn state_not_found(state_id: impl fmt::Display) -> Self {
115        Self::safety_refusal(
116            "state_not_found",
117            format!("State not found: {state_id}"),
118            "List recent states with `heddle log`, then choose an existing state id.",
119            "the requested state id does not exist in this repository",
120            "continuing with a guessed state could target the wrong history point",
121            "repository state, refs, metadata, and worktree files were left unchanged",
122        )
123    }
124}
125
126impl fmt::Display for RecoveryDetails {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(
129            f,
130            "{}. Unsafe: {}. Would change: {}. Preserved: {}.",
131            self.error, self.unsafe_condition, self.would_change, self.preserved
132        )?;
133        Ok(())
134    }
135}
136
137impl Error for RecoveryDetails {}
138
139/// Error type for repository/storage-adjacent operations.
140#[derive(Debug, thiserror::Error)]
141pub enum HeddleError {
142    #[error("{0}")]
143    Recovery(Box<RecoveryDetails>),
144    #[error("object not found: {0}")]
145    NotFound(String),
146    #[error("No merge in progress")]
147    NoMergeInProgress,
148    #[error("state not found: {0}")]
149    StateNotFound(StateId),
150    #[error("invalid object: {0}")]
151    InvalidObject(String),
152    #[error("repository not found at {0}")]
153    RepositoryNotFound(std::path::PathBuf),
154    #[error("repository already exists at {0}")]
155    RepositoryExists(std::path::PathBuf),
156    #[error(
157        "repository config at {path} uses repository format {found} but this binary supports {supported}; upgrade heddle or run `heddle migrate`"
158    )]
159    RepositoryFormatTooNew {
160        path: std::path::PathBuf,
161        found: u32,
162        supported: u32,
163    },
164    #[error(
165        "repository at {path} predates format v{required} (found v{found}); recreate it or re-adopt its Git history with this Heddle version"
166    )]
167    RepositoryFormatMigrationRequired {
168        path: std::path::PathBuf,
169        found: u32,
170        required: u32,
171    },
172    #[error(
173        "{storage} uses format {found}, but this binary supports {supported}; upgrade Heddle before opening it"
174    )]
175    StorageFormatTooNew {
176        storage: String,
177        found: u32,
178        supported: u32,
179    },
180    #[error(
181        "{storage} predates required format {required} (found {found}); recreate the repository or re-adopt its Git history with this Heddle version"
182    )]
183    StorageFormatMigrationRequired {
184        storage: String,
185        found: u32,
186        required: u32,
187    },
188    #[error("io error: {0}")]
189    Io(#[from] std::io::Error),
190    #[error("repository lock unavailable: {0}")]
191    Lock(#[from] crate::lock::LockError),
192    #[error("serialization error: {0}")]
193    Serialization(String),
194    #[error("configuration error: {0}")]
195    Config(String),
196    #[error("configuration parse error at {path}: {source}")]
197    ConfigParse {
198        path: std::path::PathBuf,
199        // Keep the original `toml::de::Error` as the error source — not a
200        // flattened string — so `HeddleExitCode::from_error` can still
201        // downcast through the chain and classify config-parse failures as
202        // EX_DATAERR (65) rather than falling through to EX_IOERR (74).
203        #[source]
204        source: toml::de::Error,
205    },
206    #[error(
207        "invalid {key}: '{value}' — valid values are {} (in {path})",
208        valid_values.join(" or ")
209    )]
210    ConfigInvalidValue {
211        path: std::path::PathBuf,
212        key: String,
213        value: String,
214        valid_values: Vec<String>,
215    },
216    #[error("conflict: {0}")]
217    Conflict(String),
218    #[error("compression error: {0}")]
219    Compression(String),
220    #[error("invalid ref name: {0}")]
221    InvalidRefName(String),
222    #[error("file too large: {0} bytes")]
223    InvalidFileSize(u64),
224    #[error("symlink target escapes repository: {0}")]
225    InvalidSymlinkTarget(std::path::PathBuf),
226    #[error("object corruption: expected {expected}, found {found}")]
227    Corruption {
228        expected: ContentHash,
229        found: ContentHash,
230    },
231    #[error(
232        "missing {object_type} object: {id} (run `heddle fsck --full` to inspect store integrity)"
233    )]
234    MissingObject { object_type: String, id: String },
235    #[error("invalid tree entry: {0}")]
236    InvalidTreeEntry(#[from] TreeError),
237}
238
239impl HeddleError {
240    pub fn recovery(details: RecoveryDetails) -> Self {
241        HeddleError::Recovery(Box::new(details))
242    }
243}
244
245impl From<rmp_serde::encode::Error> for HeddleError {
246    fn from(e: rmp_serde::encode::Error) -> Self {
247        HeddleError::Serialization(e.to_string())
248    }
249}
250
251impl From<rmp_serde::decode::Error> for HeddleError {
252    fn from(e: rmp_serde::decode::Error) -> Self {
253        HeddleError::Serialization(e.to_string())
254    }
255}
256
257impl From<toml::de::Error> for HeddleError {
258    fn from(e: toml::de::Error) -> Self {
259        HeddleError::Config(e.to_string())
260    }
261}
262
263impl From<toml::ser::Error> for HeddleError {
264    fn from(e: toml::ser::Error) -> Self {
265        HeddleError::Config(e.to_string())
266    }
267}
268
269impl From<serde_json::Error> for HeddleError {
270    fn from(e: serde_json::Error) -> Self {
271        HeddleError::Serialization(e.to_string())
272    }
273}
274
275/// Result type for repository/storage-adjacent operations.
276pub type Result<T> = std::result::Result<T, HeddleError>;
277
278#[cfg(test)]
279mod tests {
280    use super::{HeddleError, RecoveryDetails};
281
282    #[test]
283    fn safety_refusal_formats_domain_details() {
284        let details = RecoveryDetails::safety_refusal(
285            "example",
286            "error",
287            "hint",
288            "unsafe",
289            "would change",
290            "preserved",
291        );
292
293        assert_eq!(
294            details.to_string(),
295            "error. Unsafe: unsafe. Would change: would change. Preserved: preserved."
296        );
297    }
298
299    #[test]
300    fn recovery_error_displays_structured_error_copy() {
301        let err = HeddleError::recovery(RecoveryDetails::serialization_error("bad marker"));
302
303        assert!(err.to_string().contains("Repository state is corrupted"));
304        assert!(!err.to_string().contains("heddle fsck --full"));
305    }
306}