Skip to main content

nb_api/
error.rs

1//! Structured error types for `nb-api`.
2//!
3//! This module hosts [`NbError`] and its associated types
4//! ([`ParseErrorKind`], [`IoError`], [`IoErrorKind`]) as defined by
5//! the `add-note-document-model` (P1) specification. All variants
6//! derive `Serialize`/`Deserialize` so errors round-trip cleanly
7//! through JSON-encoded wire protocols (MCP tool responses, etc.).
8//!
9//! [`NbError`] also derives `Display` and implements
10//! [`std::error::Error`], so existing textual error reporting paths
11//! continue to work unchanged.
12//!
13//! # Migration (from `nb-api` 0.2.x to 0.3.0)
14//!
15//! | Old variant | New variant | Migration |
16//! |---|---|---|
17//! | `CommandFailed(String)` | `CommandFailed { command, stderr, exit_code }` | capture fields at call sites; map validation/policy failures to `ValidationError` |
18//! | `NotFound` (unit) | `ExecutableNotFound { path }` | the unit means `nb` binary missing; track path |
19//! | `Io(std::io::Error)` | `Io { path, source: IoError }` | track path in callers; convert via `From`; reverse is lossy |
20//! | `UnsupportedShowTarget { selector, actual_type }` | Same | Unchanged |
21//! | `DuplicateTitleHeading { title, heading }` | Same | Unchanged |
22//!
23//! New variants introduced in 0.3.0: `ParseError`, `InvalidFingerprint`,
24//! `JsonParseError`, `ValidationError`, `ExecutableNotFound`,
25//! `UnsupportedDocumentFormat`.
26//!
27//! ## New `UnsupportedDocumentFormat` variant (R3 revision)
28//!
29//! This is a NEW variant. There is no `nb-api 0.2.x` predecessor.
30//! Consumers upgrading to `nb-api 0.3.0` SHALL add the variant to
31//! their match arms. **Adding a variant to an exhaustive enum
32//! match produces a compile error, not a warning; wildcard
33//! matches continue compiling.** The constant
34//! [`SUPPORTED_DOCUMENT_EXTENSIONS`] (crate-root re-export of the
35//! source-of-truth declared in `parser`) is the basis for the
36//! `supported` payload at construction time.
37
38use std::error::Error as _; // `.source()` on `std::io::Error`
39use std::path::PathBuf;
40
41use serde::{Deserialize, Serialize};
42
43/// Errors raised by `nb-api` operations.
44///
45/// All variants are serializable so they can traverse MCP tool
46/// response envelopes without lossy string flattening. The
47/// [`std::error::Error`] implementation remains for ergonomic
48/// interop with code that uses `?` and standard error reporting.
49///
50/// `std::error::Error` is implemented MANUALLY below rather than
51/// via `thiserror::Error` derive. The derive's autodetect
52/// treats any field named `source` as a `#[source]` chain link
53/// and tries to convert it to `dyn Error`, which fails for
54/// fields of type `String` (e.g., `JsonParseError { source:
55/// String }` per the P1 specification). The manual impl
56/// preserves the field name and only sets a source-chain link
57/// for variants whose source field is itself an `Error`.
58#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
59#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[serde(tag = "type", rename_all = "snake_case")]
61pub enum NbError {
62    /// An `nb` subprocess invocation failed (non-zero exit, or
63    /// spawning failed for a non-NotFound reason).
64    CommandFailed {
65        /// The argument vector (joined) that was executed.
66        command: String,
67        /// Captured stderr (or stdout when stderr was empty).
68        stderr: String,
69        /// Process exit code, if the process started.
70        exit_code: Option<i32>,
71    },
72
73    /// The `nb` executable could not be located on `PATH` (or in
74    /// the resolved location) when a subprocess was spawned.
75    ExecutableNotFound {
76        /// The resolved path the spawn attempt targeted.
77        path: String,
78    },
79
80    /// `nb` reported that the requested selector was not found.
81    NotFound {
82        /// The selector that was not resolved.
83        selector: String,
84    },
85
86    /// An I/O error occurred while accessing a notebook file or
87    /// the on-disk notebook directory. The `source` field captures
88    /// the original `std::io::Error` chain as a serializable
89    /// snapshot (recursive [`IoError`]).
90    Io {
91        /// Path that triggered the I/O error.
92        path: PathBuf,
93        /// Snapshot of the `std::io::Error` chain.
94        source: IoError,
95    },
96
97    /// `nb show` was invoked on a selector whose type is not
98    /// classified as text by `nb` itself (per the
99    /// `add-0-2-0-foundation` public-API spec). Folders, archives,
100    /// audio, video, image, and any other non-textual type reach
101    /// this path. The classification delegates to
102    /// `nb show <selector> --type text` so forward compatibility
103    /// is automatic when `nb` adds new textual types. Probe
104    /// failure (e.g., selector not found) does NOT route here;
105    /// it falls through to the original `CommandFailed` error
106    /// from the content-read path.
107    UnsupportedShowTarget {
108        selector: String,
109        actual_type: String,
110    },
111
112    /// `nb add` was called with a `title` and `content` where the
113    /// first nonblank line of `content` is an exact Markdown ATX H1
114    /// duplicating the title. The validation runs in the caller
115    /// process before any subprocess invocation or notebook side
116    /// effect (including `resolve_notebook`); the rejection
117    /// happens entirely in-process. `heading` carries the exact
118    /// detected source line (including the leading `#` and any
119    /// surrounding whitespace) for actionable diagnostics. See
120    /// `add-0-2-0-foundation` public-API specification.
121    DuplicateTitleHeading { title: String, heading: String },
122
123    /// A structural parse failure.
124    ParseError {
125        kind: ParseErrorKind,
126        location: std::ops::Range<usize>,
127    },
128
129    /// A fingerprint string failed structural validation (wrong
130    /// prefix, wrong length, mixed case, etc.). `reason` carries a
131    /// machine-readable category (e.g., `"empty"`,
132    /// `"unknown_algorithm_prefix"`, `"uppercase_hex"`).
133    InvalidFingerprint { reason: String },
134
135    /// JSON deserialization failed when constructing a typed
136    /// wrapper (e.g., [`crate::fingerprint::Fingerprint::from_json`]).
137    JsonParseError {
138        // Field is named `source` per the P1 specification.
139        source: String,
140    },
141
142    /// A semantic validation error raised by an operation boundary
143    /// (e.g., rejecting input that is structurally valid but
144    /// semantically illegal). `location` is `None` when the
145    /// failure is not byte-anchored.
146    ValidationError {
147        reason: String,
148        location: Option<std::ops::Range<usize>>,
149    },
150
151    /// Format-dispatch refusal (R3 revision).
152    ///
153    /// `parse(bytes, FromPath(path))` returned this error because
154    /// the final filename matched one of the recognized-but-
155    /// unsupported dotted suffixes (e.g., `.org`, `.latex`,
156    /// `.tex`, `.adoc`, `.asciidoc`). Format dispatch precedes
157    /// byte parsing, so no bytes were consumed and no
158    /// parse-error location is meaningful — this is a
159    /// contextual configuration error, not a parse failure.
160    ///
161    /// `extension` carries the lowercase dotted suffix WITHOUT
162    /// the leading dot (e.g., `"org"`, `"latex"`).
163    /// `supported` is the owned canonical list of supported
164    /// extensions, populated at construction time from
165    /// `crate::SUPPORTED_DOCUMENT_EXTENSIONS`. The owned
166    /// `Vec<String>` shape is required for the derived
167    /// `Serialize` / `Deserialize` round-trip contract on
168    /// `NbError`.
169    UnsupportedDocumentFormat {
170        extension: String,
171        supported: Vec<String>,
172    },
173
174    /// Process-shared gate queue wait exceeded. Notebook was not mutated.
175    GateTimeout { gate: String, timeout_ms: u64 },
176
177    /// `Transaction::commit` refused because the notebook worktree/index is dirty.
178    DirtyBaseline { guidance: String },
179
180    /// Plan-op path collision against snapshot or earlier plan ops.
181    PathCollision {
182        path: String,
183        plan_index: Option<u32>,
184    },
185
186    /// Plan targets or would leave durable state on a Git-ignored path in a
187    /// way that cannot be represented in the single checkpoint (existing
188    /// ignored entry mutation), or requires force-staging (reported only when
189    /// force-stage is unavailable). Prefer rejecting existing-ignored mutators.
190    PathIgnored {
191        path: String,
192        guidance: String,
193        plan_index: Option<u32>,
194    },
195
196    /// Validation/apply failure tied to a plan entry.
197    PlanValidation {
198        kind: String,
199        message: String,
200        plan_index: Option<u32>,
201    },
202
203    /// Commit completion is unknown (e.g. transport timeout after checkpoint may have started).
204    IndeterminateCommit {
205        pre_revision: String,
206        post_revision_observed: Option<String>,
207        guidance: String,
208    },
209
210    /// Cleanup after a known failed apply could not verify clean `pre_revision`.
211    RecoveryRequired {
212        pre_revision: String,
213        post_revision_observed: Option<String>,
214        status_observed: Option<String>,
215        preserved_paths: Option<Vec<String>>,
216        guidance: String,
217    },
218
219    /// Body fingerprint precondition failed.
220    FingerprintMismatch {
221        target: crate::types::NoteTarget,
222        guidance: String,
223    },
224
225    /// Line number/anchor precondition failed.
226    AnchorMismatch {
227        target: String,
228        number: u32,
229        guidance: String,
230    },
231
232    /// Substring `expected_count` did not match actual matches.
233    OccurrenceMismatch { expected: u32, actual: u32 },
234
235    /// Overlapping line edits in one batch.
236    OverlappingEdits { indices: Vec<u32> },
237
238    /// Invalid `show_note_lines` window.
239    InvalidLineWindow {
240        offset: u32,
241        limit: u32,
242        total_lines: u32,
243    },
244
245    /// Empty substring pattern refused at enqueue/apply.
246    EmptySubstringPattern,
247
248    /// Contiguous-body-only op invoked on a multi-fragment document.
249    FragmentedBody {
250        fragment_count: u32,
251        guidance: String,
252    },
253
254    /// Structured text surface hit non-UTF-8 bytes in a text-classified file.
255    ///
256    /// Non-textual notes keep using `UnsupportedShowTarget`; this variant
257    /// covers the narrow non-UTF-8-but-text case. Use
258    /// `NbClient::read_note_source_bytes` for raw access.
259    NonUtf8 {
260        selector: String,
261        path: String,
262        kind: String,
263        #[serde(default, skip_serializing_if = "Option::is_none")]
264        mime_hint: Option<String>,
265    },
266
267    /// `.nb-api-index.lock` wait exceeded before any mutation.
268    IndexLockTimeout { path: String, timeout_ms: u64 },
269
270    /// Document structure is not supported for the requested op.
271    UnsupportedStructure { reason: String },
272}
273
274impl std::fmt::Display for NbError {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        match self {
277            Self::CommandFailed {
278                command,
279                stderr,
280                exit_code,
281            } => write!(
282                f,
283                "command {command:?} failed (exit {exit_code:?}): {stderr}"
284            ),
285            Self::ExecutableNotFound { path } => {
286                write!(f, "`nb` executable not found at path {path:?}")
287            }
288            Self::NotFound { selector } => write!(f, "not found: {selector:?}"),
289            Self::Io { path, source } => write!(f, "I/O error at {path:?}: {source}"),
290            Self::UnsupportedShowTarget {
291                selector,
292                actual_type,
293            } => write!(
294                f,
295                "selector `{selector}` resolved to non-textual type `{actual_type}`; \
296                 `nb show` does not display non-textual content"
297            ),
298            Self::DuplicateTitleHeading { title, heading } => write!(
299                f,
300                "title `{title}` duplicates the first H1 in content (`{heading}`); \
301                 remove the duplicate heading to avoid double-rendering"
302            ),
303            Self::ParseError { kind, location } => {
304                write!(f, "parse error: {kind:?} at {location:?}")
305            }
306            Self::InvalidFingerprint { reason } => {
307                write!(f, "invalid fingerprint: {reason:?}")
308            }
309            Self::JsonParseError { source } => {
310                write!(f, "JSON parse error: {source:?}")
311            }
312            Self::ValidationError {
313                reason,
314                location: _,
315            } => {
316                write!(f, "validation error: {reason:?}")
317            }
318            Self::UnsupportedDocumentFormat {
319                extension,
320                supported,
321            } => {
322                write!(
323                    f,
324                    "unsupported document format: {extension:?} (supported: {supported:?})"
325                )
326            }
327            Self::GateTimeout { gate, timeout_ms } => {
328                write!(f, "gate timeout waiting on {gate} after {timeout_ms}ms")
329            }
330            Self::DirtyBaseline { guidance } => {
331                write!(f, "dirty baseline: {guidance}")
332            }
333            Self::PathCollision { path, plan_index } => {
334                write!(f, "path collision at {path:?} (plan_index={plan_index:?})")
335            }
336            Self::PathIgnored {
337                path,
338                guidance,
339                plan_index,
340            } => write!(
341                f,
342                "ignored path {path:?} (plan_index={plan_index:?}): {guidance}"
343            ),
344            Self::PlanValidation {
345                kind,
346                message,
347                plan_index,
348            } => write!(
349                f,
350                "plan validation ({kind}) at index {plan_index:?}: {message}"
351            ),
352            Self::IndeterminateCommit {
353                pre_revision,
354                post_revision_observed,
355                guidance,
356            } => write!(
357                f,
358                "indeterminate commit (pre={pre_revision}, post={post_revision_observed:?}): {guidance}"
359            ),
360            Self::RecoveryRequired {
361                pre_revision,
362                guidance,
363                ..
364            } => write!(
365                f,
366                "recovery required (pre_revision={pre_revision}): {guidance}"
367            ),
368            Self::FingerprintMismatch { target, guidance } => {
369                write!(f, "fingerprint mismatch for {target:?}: {guidance}")
370            }
371            Self::AnchorMismatch {
372                target,
373                number,
374                guidance,
375            } => write!(f, "anchor mismatch for {target} line {number}: {guidance}"),
376            Self::OccurrenceMismatch { expected, actual } => {
377                write!(
378                    f,
379                    "occurrence mismatch: expected={expected} actual={actual}"
380                )
381            }
382            Self::OverlappingEdits { indices } => {
383                write!(f, "overlapping edits at indices {indices:?}")
384            }
385            Self::InvalidLineWindow {
386                offset,
387                limit,
388                total_lines,
389            } => write!(
390                f,
391                "invalid line window offset={offset} limit={limit} total_lines={total_lines}"
392            ),
393            Self::EmptySubstringPattern => write!(f, "empty substring pattern"),
394            Self::FragmentedBody {
395                fragment_count,
396                guidance,
397            } => write!(
398                f,
399                "fragmented body ({fragment_count} fragments): {guidance}"
400            ),
401            Self::NonUtf8 {
402                selector,
403                path,
404                kind,
405                mime_hint,
406            } => write!(
407                f,
408                "non-UTF-8 text at {selector:?} ({path:?}, kind={kind}, mime={mime_hint:?}); use read_note_source_bytes for raw access"
409            ),
410            Self::IndexLockTimeout { path, timeout_ms } => {
411                write!(f, "index lock timeout on {path} after {timeout_ms}ms")
412            }
413            Self::UnsupportedStructure { reason } => {
414                write!(f, "unsupported structure: {reason}")
415            }
416        }
417    }
418}
419
420impl std::error::Error for NbError {
421    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
422        // Only `Io { source: IoError }` carries a true source-chain
423        // link. Every other variant's `source` field (where
424        // present) is a diagnostic String or a non-Error type, so
425        // we explicitly return `None` for them.
426        match self {
427            Self::Io { source, .. } => Some(source),
428            _ => None,
429        }
430    }
431}
432
433/// Narrow refusal contract for the structural parser.
434///
435/// `parse` accepts every input that can be losslessly partitioned
436/// into a [`crate::parser::NoteDocument`], including the frozen
437/// W1 and E1-E11 noncanonical forms. The ONLY refusal cases at
438/// the parse layer are:
439///
440/// - Todo with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
441/// - Bookmark with no non-blank line at all: [`ParseErrorKind::MissingTitle`].
442///
443/// Notes are permissive on empty source. Title-shape errors belong
444/// to a later strict validator (P5+), not to the parser.
445#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
446#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
447pub enum ParseErrorKind {
448    /// The first non-blank line was missing entirely (Todo/Bookmark
449    /// only; Notes are permissive).
450    MissingTitle,
451}
452
453/// Serializable snapshot of a [`std::io::Error`] chain.
454///
455/// `IoError` captures the **chain structure** (as a tree of
456/// snapshots) but does NOT preserve the original `std::io::Error`
457/// identity. The forward conversion [`From<std::io::Error>`] walks
458/// [`std::error::Error::source`] and recurses for each
459/// `std::io::Error` link; nested non-`io::Error` sources are
460/// stringified into [`IoErrorKind::Other`].
461///
462/// The reverse conversion [`From<IoError>`] for `std::io::Error`
463/// is **explicitly lossy** — see [`IoError`]'s `From` impl.
464#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, thiserror::Error)]
465#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
466#[error("{kind:?}: {message}")]
467pub struct IoError {
468    pub kind: IoErrorKind,
469    pub message: String,
470    pub os_error: Option<i32>,
471    pub source: Option<Box<IoError>>,
472}
473
474/// Discriminator for the `std::io::ErrorKind` taxonomy, lifted into
475/// a serializable form. Marked `#[non_exhaustive]` so future
476/// versions can add new kinds without breaking downstream
477/// `match` arms that include a default branch.
478#[non_exhaustive]
479#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
480#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
481pub enum IoErrorKind {
482    NotFound,
483    PermissionDenied,
484    ConnectionRefused,
485    ConnectionReset,
486    ConnectionAborted,
487    NotConnected,
488    AddrInUse,
489    AddrNotAvailable,
490    BrokenPipe,
491    AlreadyExists,
492    WouldBlock,
493    InvalidInput,
494    InvalidData,
495    TimedOut,
496    WriteZero,
497    Interrupted,
498    UnexpectedEof,
499    OutOfMemory,
500    /// Catch-all for nested sources that are not themselves
501    /// `std::io::Error` (e.g., a third-party crate's error type
502    /// captured as `source`).
503    Other,
504}
505
506impl IoErrorKind {
507    /// Map a `std::io::ErrorKind` into the serializable variant.
508    pub fn from_std(kind: std::io::ErrorKind) -> Self {
509        match kind {
510            std::io::ErrorKind::NotFound => Self::NotFound,
511            std::io::ErrorKind::PermissionDenied => Self::PermissionDenied,
512            std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,
513            std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,
514            std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,
515            std::io::ErrorKind::NotConnected => Self::NotConnected,
516            std::io::ErrorKind::AddrInUse => Self::AddrInUse,
517            std::io::ErrorKind::AddrNotAvailable => Self::AddrNotAvailable,
518            std::io::ErrorKind::BrokenPipe => Self::BrokenPipe,
519            std::io::ErrorKind::AlreadyExists => Self::AlreadyExists,
520            std::io::ErrorKind::WouldBlock => Self::WouldBlock,
521            std::io::ErrorKind::InvalidInput => Self::InvalidInput,
522            std::io::ErrorKind::InvalidData => Self::InvalidData,
523            std::io::ErrorKind::TimedOut => Self::TimedOut,
524            std::io::ErrorKind::WriteZero => Self::WriteZero,
525            std::io::ErrorKind::Interrupted => Self::Interrupted,
526            std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEof,
527            std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,
528            _ => Self::Other,
529        }
530    }
531}
532
533impl From<std::io::ErrorKind> for IoErrorKind {
534    fn from(kind: std::io::ErrorKind) -> Self {
535        Self::from_std(kind)
536    }
537}
538
539impl From<std::io::Error> for IoError {
540    /// Capture an `io::Error` chain as a tree of serializable
541    /// snapshots.
542    ///
543    /// The implementation recursively walks the
544    /// [`std::error::Error::source`] chain on BORROWED
545    /// `&dyn Error` references. This is critical: `std::io::Error`
546    /// is not `Clone`, so we cannot reconstruct an inner error
547    /// from a borrow without losing its `raw_os_error()` and its
548    /// own source chain. Walking the borrow preserves the chain
549    /// STRUCTURE exactly.
550    ///
551    /// At each level: if the source is itself an `io::Error`,
552    /// recurse on its borrow; otherwise, capture the source as
553    /// an [`IoErrorKind::Other`] snapshot (preserving the
554    /// `Display` text and walking its own source chain for
555    /// nested non-io links).
556    fn from(err: std::io::Error) -> Self {
557        snapshot_io_error(err)
558    }
559}
560
561/// Build an `IoError` snapshot from an `io::Error` value, then
562/// walk its source chain via the borrowed `dyn Error` to
563/// preserve chain structure exactly.
564fn snapshot_io_error(err: std::io::Error) -> IoError {
565    let kind = IoErrorKind::from_std(err.kind());
566    let os_error = err.raw_os_error();
567    let message = err.to_string();
568    let source = walk_source_chain(err.source());
569    IoError {
570        kind,
571        message,
572        os_error,
573        source,
574    }
575}
576
577/// Walk a `&(dyn Error + 'static)` chain, building a list of
578/// `IoError` snapshots. Each link appears EXACTLY ONCE in the
579/// chain (no duplication). Each `std::io::Error` link has its
580/// `raw_os_error()` preserved verbatim via the recursive walk
581/// on the borrowed `dyn Error`.
582///
583/// The chain is built by snapshotting the CURRENT node with its
584/// `source` field set to the recursive walk of the NEXT node.
585/// This avoids the A→B→B duplication that would arise from both
586/// recursing into the source AND iterating/appending the same
587/// source.
588fn walk_source_chain(source: Option<&(dyn std::error::Error + 'static)>) -> Option<Box<IoError>> {
589    let head = source?;
590    Some(Box::new(snapshot_link(head)))
591}
592
593/// Snapshot a single link in the source chain. The link's `source`
594/// field is set to the recursive snapshot of the next link.
595fn snapshot_link(current: &(dyn std::error::Error + 'static)) -> IoError {
596    if let Some(io_err) = current.downcast_ref::<std::io::Error>() {
597        IoError {
598            kind: IoErrorKind::from_std(io_err.kind()),
599            message: io_err.to_string(),
600            os_error: io_err.raw_os_error(),
601            // The recursive walk captures the io_err's own
602            // chain. Each io_err-level appears exactly once.
603            source: walk_source_chain(io_err.source()),
604        }
605    } else {
606        IoError {
607            kind: IoErrorKind::Other,
608            message: current.to_string(),
609            os_error: None,
610            // Recurse on the next link. Because `walk_source_chain`
611            // snapshots its OWN first link and recurses, the
612            // outer iteration does NOT see the next link — no
613            // duplication.
614            source: walk_source_chain(current.source()),
615        }
616    }
617}
618
619impl From<IoError> for std::io::Error {
620    /// Reverse conversion is **explicitly lossy**.
621    ///
622    /// The implementation prefers [`std::io::Error::from_raw_os_error`]
623    /// when [`IoError::os_error`] is `Some`, which LOSES the
624    /// snapshot message and any source chain. Otherwise, it
625    /// constructs a new `io::Error::new(kind, message)`, which
626    /// loses `raw_os_error()`.
627    ///
628    /// The forward conversion ([`From<std::io::Error>`] for
629    /// `IoError`) preserves chain STRUCTURE; this reverse
630    /// conversion does not — the snapshot tree is collapsed to a
631    /// single `std::io::Error`.
632    fn from(snapshot: IoError) -> Self {
633        if let Some(code) = snapshot.os_error {
634            std::io::Error::from_raw_os_error(code)
635        } else {
636            let kind = match snapshot.kind {
637                IoErrorKind::NotFound => std::io::ErrorKind::NotFound,
638                IoErrorKind::PermissionDenied => std::io::ErrorKind::PermissionDenied,
639                IoErrorKind::ConnectionRefused => std::io::ErrorKind::ConnectionRefused,
640                IoErrorKind::ConnectionReset => std::io::ErrorKind::ConnectionReset,
641                IoErrorKind::ConnectionAborted => std::io::ErrorKind::ConnectionAborted,
642                IoErrorKind::NotConnected => std::io::ErrorKind::NotConnected,
643                IoErrorKind::AddrInUse => std::io::ErrorKind::AddrInUse,
644                IoErrorKind::AddrNotAvailable => std::io::ErrorKind::AddrNotAvailable,
645                IoErrorKind::BrokenPipe => std::io::ErrorKind::BrokenPipe,
646                IoErrorKind::AlreadyExists => std::io::ErrorKind::AlreadyExists,
647                IoErrorKind::WouldBlock => std::io::ErrorKind::WouldBlock,
648                IoErrorKind::InvalidInput => std::io::ErrorKind::InvalidInput,
649                IoErrorKind::InvalidData => std::io::ErrorKind::InvalidData,
650                IoErrorKind::TimedOut => std::io::ErrorKind::TimedOut,
651                IoErrorKind::WriteZero => std::io::ErrorKind::WriteZero,
652                IoErrorKind::Interrupted => std::io::ErrorKind::Interrupted,
653                IoErrorKind::UnexpectedEof => std::io::ErrorKind::UnexpectedEof,
654                IoErrorKind::OutOfMemory => std::io::ErrorKind::OutOfMemory,
655                IoErrorKind::Other => std::io::ErrorKind::Other,
656            };
657            std::io::Error::new(kind, snapshot.message)
658        }
659    }
660}