Skip to main content

vtcode_commons/
errors.rs

1#![expect(
2    clippy::indexing_slicing,
3    reason = "Error rendering indexes only validated structured diagnostic entries."
4)]
5
6use std::borrow::Cow;
7use std::fmt;
8
9use anyhow::{Error, Result};
10
11// File operation errors
12pub const ERR_READ_FILE: &str = "failed to read file";
13pub const ERR_WRITE_FILE: &str = "failed to write file";
14pub const ERR_READ_DIR: &str = "failed to read directory";
15pub const ERR_CREATE_DIR: &str = "failed to create directory";
16pub const ERR_REMOVE_FILE: &str = "failed to remove file";
17pub const ERR_REMOVE_DIR: &str = "failed to remove directory";
18pub const ERR_READ_DIR_ENTRY: &str = "failed to read directory entry";
19pub const ERR_GET_FILE_TYPE: &str = "failed to read file type";
20pub const ERR_GET_METADATA: &str = "failed to read file metadata";
21pub const ERR_CANONICALIZE_PATH: &str = "failed to canonicalize path";
22pub const ERR_READ_SYMLINK: &str = "failed to read symlink";
23
24// Skill/Tool errors
25pub const ERR_CREATE_SKILLS_DIR: &str = "failed to create skills directory";
26pub const ERR_CREATE_SKILL_DIR: &str = "failed to create skill directory";
27pub const ERR_READ_SKILL_CODE: &str = "failed to read skill code";
28pub const ERR_WRITE_SKILL_CODE: &str = "failed to write skill code";
29pub const ERR_READ_SKILL_METADATA: &str = "failed to read skill metadata";
30pub const ERR_WRITE_SKILL_METADATA: &str = "failed to write skill metadata";
31pub const ERR_PARSE_SKILL_METADATA: &str = "failed to parse skill metadata";
32pub const ERR_WRITE_SKILL_DOCS: &str = "failed to write skill documentation";
33pub const ERR_DELETE_SKILL: &str = "failed to delete skill";
34pub const ERR_READ_SKILLS_DIR: &str = "failed to read skills directory";
35pub const ERR_TOOL_DENIED: &str = "tool denied or unavailable by policy";
36
37// Audit/Logging errors
38pub const ERR_CREATE_AUDIT_DIR: &str = "Failed to create audit directory";
39pub const ERR_WRITE_AUDIT_LOG: &str = "failed to write audit log";
40
41// Checkpoint/Snapshot errors
42pub const ERR_CREATE_CHECKPOINT_DIR: &str = "failed to create checkpoint directory";
43pub const ERR_WRITE_CHECKPOINT: &str = "failed to write checkpoint";
44pub const ERR_READ_CHECKPOINT: &str = "failed to read checkpoint";
45
46// Policy errors
47pub const ERR_CREATE_POLICY_DIR: &str = "Failed to create directory for tool policy config";
48pub const ERR_CREATE_WORKSPACE_POLICY_DIR: &str = "Failed to create workspace policy directory";
49
50// Serialization errors
51pub const ERR_SERIALIZE_METADATA: &str = "failed to serialize skill metadata";
52pub const ERR_SERIALIZE_STATE: &str = "failed to serialize state";
53pub const ERR_DESERIALIZE: &str = "failed to deserialize data";
54
55// IPC/SDK errors
56pub const ERR_CREATE_IPC_DIR: &str = "failed to create IPC directory";
57pub const ERR_READ_REQUEST_FILE: &str = "failed to read request file";
58pub const ERR_READ_REQUEST_JSON: &str = "failed to read request JSON";
59pub const ERR_PARSE_REQUEST_JSON: &str = "failed to parse request JSON";
60pub const ERR_PARSE_ARGS: &str = "failed to parse tokenized args";
61pub const ERR_PARSE_RESULT: &str = "failed to parse de-tokenized result";
62
63/// Helper macro for file operation errors with context.
64///
65/// Usage: `file_err!(path, read)` where `path` is an expression and the
66/// operation is matched as a bare identifier (not a string literal).
67/// Expands to `"failed to read <path>"`.
68#[macro_export]
69macro_rules! file_err {
70    ($path:expr, read) => {
71        format!("failed to read {}", $path)
72    };
73    ($path:expr, write) => {
74        format!("failed to write {}", $path)
75    };
76    ($path:expr, delete) => {
77        format!("failed to delete {}", $path)
78    };
79    ($path:expr, create) => {
80        format!("failed to create {}", $path)
81    };
82}
83
84/// Helper macro for context errors
85/// Usage: ctx_err!(operation, context) -> "operation context"
86#[macro_export]
87macro_rules! ctx_err {
88    ($op:expr, $ctx:expr) => {
89        format!("{}: {}", $op, $ctx)
90    };
91}
92
93/// Formats an error into a user-facing description. This allows extracted
94/// components to present consistent error messaging without depending on the
95/// CLI presentation layer.
96pub trait ErrorFormatter: Send + Sync {
97    /// Render the error into a user-facing string.
98    fn format_error(&self, error: &Error) -> Cow<'_, str>;
99}
100
101/// Reports non-fatal errors to an observability backend.
102pub trait ErrorReporter: Send + Sync {
103    /// Capture the provided error for later inspection.
104    fn capture(&self, error: &Error) -> Result<()>;
105
106    /// Convenience helper to capture a simple message.
107    ///
108    /// `where Self: Sized` keeps the trait object-safe so consumers can erase
109    /// a concrete reporter into `&dyn ErrorReporter` at their API boundary;
110    /// the helper stays available on every concrete implementation.
111    fn capture_message(&self, message: impl Into<Cow<'static, str>>) -> Result<()>
112    where
113        Self: Sized,
114    {
115        let message: Cow<'static, str> = message.into();
116        self.capture(&Error::msg(message))
117    }
118}
119
120/// Error reporting implementation that drops every event. Useful for tests or
121/// when a consumer does not yet integrate with error monitoring.
122#[derive(Debug, Default, Clone, Copy)]
123pub struct NoopErrorReporter;
124
125impl ErrorReporter for NoopErrorReporter {
126    fn capture(&self, _error: &Error) -> Result<()> {
127        Ok(())
128    }
129}
130
131/// Default formatter that surfaces the error's display output.
132#[derive(Debug, Default, Clone, Copy)]
133pub struct DisplayErrorFormatter;
134
135impl ErrorFormatter for DisplayErrorFormatter {
136    fn format_error(&self, error: &Error) -> Cow<'_, str> {
137        Cow::Owned(format!("{error}"))
138    }
139}
140
141/// A collection of errors that enables continuing work while collecting failures.
142///
143/// This type implements the "error parameter" pattern: instead of short-circuiting
144/// on the first error, processing continues and errors are accumulated. The caller
145/// can inspect the collection afterward to determine whether all operations
146/// succeeded.
147///
148/// # Ergonomic Result handling
149///
150/// [`collect_result`](MultiErrors::collect_result) lets you process a `Result<T, E>`
151/// while keeping the happy path dominant:
152///
153/// ```rust
154/// use vtcode_commons::MultiErrors;
155/// let mut errors: MultiErrors<String> = MultiErrors::new();
156/// let value: Option<i32> = errors.collect_result("42".parse::<i32>().map_err(|e| e.to_string()));
157/// assert_eq!(value, Some(42));
158/// ```
159///
160/// # Composing with traditional error handling
161///
162/// Use [`ok`](MultiErrors::ok) or [`to_anyhow`](MultiErrors::to_anyhow) to convert
163/// back into a traditional `Result`.
164#[derive(Debug, Clone)]
165pub struct MultiErrors<E = Error> {
166    errors: Vec<E>,
167}
168
169impl<E> MultiErrors<E> {
170    /// Create an empty error collection.
171    pub fn new() -> Self {
172        Self { errors: Vec::new() }
173    }
174
175    /// Add a single error to the collection.
176    pub fn push(&mut self, error: E) {
177        self.errors.push(error);
178    }
179
180    /// Extend the collection with multiple errors.
181    fn extend(&mut self, iter: impl IntoIterator<Item = E>) {
182        self.errors.extend(iter);
183    }
184
185    /// Returns `true` if no errors have been collected.
186    #[must_use]
187    pub fn is_empty(&self) -> bool {
188        self.errors.is_empty()
189    }
190
191    /// Returns the number of collected errors.
192    #[must_use]
193    pub fn len(&self) -> usize {
194        self.errors.len()
195    }
196
197    /// Consume the collector and return the underlying error vector.
198    #[must_use]
199    fn into_inner(self) -> Vec<E> {
200        self.errors
201    }
202
203    /// Returns a slice of all collected errors.
204    #[must_use]
205    pub fn as_slice(&self) -> &[E] {
206        &self.errors
207    }
208
209    /// Returns an iterator over the collected errors.
210    pub fn iter(&self) -> std::slice::Iter<'_, E> {
211        self.errors.iter()
212    }
213
214    /// Convert into `Result<()>` — succeeds if no errors were collected.
215    pub fn ok(self) -> std::result::Result<(), Self> {
216        if self.errors.is_empty() { Ok(()) } else { Err(self) }
217    }
218
219    /// Remove all errors from the collection.
220    pub fn clear(&mut self) {
221        self.errors.clear();
222    }
223
224    /// Process a `Result`, returning the success value or collecting the error.
225    ///
226    /// This is the key ergonomic method — it keeps the happy path as the primary
227    /// flow while silently collecting errors for later inspection.
228    pub fn collect_result<T, F>(&mut self, result: std::result::Result<T, F>) -> Option<T>
229    where
230        F: Into<E>,
231    {
232        match result {
233            Ok(val) => Some(val),
234            Err(e) => {
235                self.errors.push(e.into());
236                None
237            }
238        }
239    }
240
241    /// Convert into an [`anyhow::Error`] for use with traditional error handling.
242    #[must_use]
243    pub fn to_anyhow(&self) -> Error
244    where
245        E: fmt::Display,
246    {
247        Error::msg(self.to_string())
248    }
249}
250
251impl<E> Default for MultiErrors<E> {
252    fn default() -> Self {
253        Self::new()
254    }
255}
256
257impl<E> From<Vec<E>> for MultiErrors<E> {
258    fn from(errors: Vec<E>) -> Self {
259        Self { errors }
260    }
261}
262
263impl<E> IntoIterator for MultiErrors<E> {
264    type Item = E;
265    type IntoIter = std::vec::IntoIter<E>;
266
267    fn into_iter(self) -> Self::IntoIter {
268        self.errors.into_iter()
269    }
270}
271
272impl<E: serde::Serialize> serde::Serialize for MultiErrors<E> {
273    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
274        self.errors.serialize(serializer)
275    }
276}
277
278impl<'de, E: serde::Deserialize<'de>> serde::Deserialize<'de> for MultiErrors<E> {
279    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
280        Vec::<E>::deserialize(deserializer).map(|errors| Self { errors })
281    }
282}
283
284impl<E: fmt::Display> fmt::Display for MultiErrors<E> {
285    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286        match self.errors.len() {
287            0 => write!(f, "no errors"),
288            1 => write!(f, "{}", self.errors[0]),
289            _ => {
290                for (i, error) in self.errors.iter().enumerate() {
291                    if i > 0 {
292                        writeln!(f)?;
293                    }
294                    write!(f, "  {}. {error}", i + 1)?;
295                }
296                Ok(())
297            }
298        }
299    }
300}
301
302impl<E: std::error::Error + 'static> std::error::Error for MultiErrors<E> {
303    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
304        self.errors.first().map(|e| e as &(dyn std::error::Error + 'static))
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn file_err_operations_format_path() {
314        // `file_err!` has no shape test; other relative paths in macros were
315        // also left invariant. Keep the message contract pinned.
316        let path = "config/vtcode.toml";
317        assert_eq!(file_err!(path, read), "failed to read config/vtcode.toml");
318        assert_eq!(file_err!(path, write), "failed to write config/vtcode.toml");
319        assert_eq!(file_err!(path, delete), "failed to delete config/vtcode.toml");
320        assert_eq!(file_err!(path, create), "failed to create config/vtcode.toml");
321    }
322
323    #[test]
324    fn ctx_err_joins_operation_and_context() {
325        assert_eq!(ctx_err!("llm factory", "lock poisoned"), "llm factory: lock poisoned");
326    }
327
328    #[test]
329    fn formatter_uses_display() {
330        let formatter = DisplayErrorFormatter;
331        let error = Error::msg("test error");
332        assert_eq!(formatter.format_error(&error), "test error");
333    }
334
335    #[test]
336    fn noop_reporter_drops_errors() {
337        let reporter = NoopErrorReporter;
338        let error = Error::msg("test");
339        assert!(reporter.capture(&error).is_ok());
340        assert!(reporter.capture_message("message").is_ok());
341    }
342
343    #[test]
344    fn multi_errors_new_is_empty() {
345        let errors: MultiErrors<String> = MultiErrors::new();
346        assert!(errors.is_empty());
347        assert_eq!(errors.len(), 0);
348    }
349
350    #[test]
351    fn multi_errors_push_and_len() {
352        let mut errors = MultiErrors::new();
353        errors.push("error 1".to_string());
354        errors.push("error 2".to_string());
355        assert!(!errors.is_empty());
356        assert_eq!(errors.len(), 2);
357    }
358
359    #[test]
360    fn multi_errors_collect_result_ok() {
361        let mut errors: MultiErrors<String> = MultiErrors::new();
362        let value: i32 = errors.collect_result(Ok::<_, String>(42)).unwrap_or(0);
363        assert_eq!(value, 42);
364        assert!(errors.is_empty());
365    }
366
367    #[test]
368    fn multi_errors_collect_result_err() {
369        let mut errors: MultiErrors<String> = MultiErrors::new();
370        let value: i32 = errors.collect_result(Err::<i32, String>("bad".to_string())).unwrap_or(0);
371        assert_eq!(value, 0);
372        assert_eq!(errors.len(), 1);
373    }
374
375    #[test]
376    fn multi_errors_ok_succeeds_when_empty() {
377        let errors: MultiErrors<String> = MultiErrors::new();
378        assert!(errors.ok().is_ok());
379    }
380
381    #[test]
382    fn multi_errors_ok_fails_when_not_empty() {
383        let mut errors = MultiErrors::new();
384        errors.push("error".to_string());
385        assert!(errors.ok().is_err());
386    }
387
388    #[test]
389    fn multi_errors_display_empty() {
390        let errors: MultiErrors<String> = MultiErrors::new();
391        assert_eq!(errors.to_string(), "no errors");
392    }
393
394    #[test]
395    fn multi_errors_display_single() {
396        let mut errors = MultiErrors::new();
397        errors.push("something failed".to_string());
398        assert_eq!(errors.to_string(), "something failed");
399    }
400
401    #[test]
402    fn multi_errors_display_multiple() {
403        let mut errors = MultiErrors::new();
404        errors.push("first issue".to_string());
405        errors.push("second issue".to_string());
406        let display = errors.to_string();
407        assert!(display.contains("1. first issue"));
408        assert!(display.contains("2. second issue"));
409    }
410
411    #[test]
412    fn multi_errors_extend() {
413        let mut errors = MultiErrors::new();
414        errors.extend(vec!["a".to_string(), "b".to_string()]);
415        assert_eq!(errors.len(), 2);
416    }
417
418    #[test]
419    fn multi_errors_into_inner() {
420        let mut errors = MultiErrors::new();
421        errors.push("test".to_string());
422        let inner: Vec<String> = errors.into_inner();
423        assert_eq!(inner.len(), 1);
424    }
425
426    #[test]
427    fn multi_errors_from_vec() {
428        let errors: MultiErrors<String> = MultiErrors::from(vec!["a".to_string()]);
429        assert_eq!(errors.len(), 1);
430    }
431
432    #[test]
433    fn multi_errors_into_iterator() {
434        let mut errors = MultiErrors::new();
435        errors.push("a".to_string());
436        errors.push("b".to_string());
437        let collected: Vec<String> = errors.into_iter().collect();
438        assert_eq!(collected, vec!["a", "b"]);
439    }
440
441    #[test]
442    fn multi_errors_slice_access() {
443        let mut errors = MultiErrors::new();
444        errors.push("err".to_string());
445        assert_eq!(errors.as_slice(), &["err".to_string()]);
446    }
447
448    #[test]
449    fn multi_errors_to_anyhow() {
450        let mut errors = MultiErrors::new();
451        errors.push("something broke".to_string());
452        let err = errors.to_anyhow();
453        assert!(err.to_string().contains("something broke"));
454    }
455}