use std::error::Error as _; use std::path::PathBuf;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NbError {
CommandFailed {
command: String,
stderr: String,
exit_code: Option<i32>,
},
ExecutableNotFound {
path: String,
},
NotFound {
selector: String,
},
Io {
path: PathBuf,
source: IoError,
},
UnsupportedShowTarget {
selector: String,
actual_type: String,
},
DuplicateTitleHeading { title: String, heading: String },
ParseError {
kind: ParseErrorKind,
location: std::ops::Range<usize>,
},
InvalidFingerprint { reason: String },
JsonParseError {
source: String,
},
ValidationError {
reason: String,
location: Option<std::ops::Range<usize>>,
},
UnsupportedDocumentFormat {
extension: String,
supported: Vec<String>,
},
GateTimeout { gate: String, timeout_ms: u64 },
DirtyBaseline { guidance: String },
PathCollision {
path: String,
plan_index: Option<u32>,
},
PathIgnored {
path: String,
guidance: String,
plan_index: Option<u32>,
},
PlanValidation {
kind: String,
message: String,
plan_index: Option<u32>,
},
IndeterminateCommit {
pre_revision: String,
post_revision_observed: Option<String>,
guidance: String,
},
RecoveryRequired {
pre_revision: String,
post_revision_observed: Option<String>,
status_observed: Option<String>,
preserved_paths: Option<Vec<String>>,
guidance: String,
},
FingerprintMismatch {
target: crate::types::NoteTarget,
guidance: String,
},
AnchorMismatch {
target: String,
number: u32,
guidance: String,
},
OccurrenceMismatch { expected: u32, actual: u32 },
OverlappingEdits { indices: Vec<u32> },
InvalidLineWindow {
offset: u32,
limit: u32,
total_lines: u32,
},
EmptySubstringPattern,
FragmentedBody {
fragment_count: u32,
guidance: String,
},
NonUtf8 {
selector: String,
path: String,
kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
mime_hint: Option<String>,
},
IndexLockTimeout { path: String, timeout_ms: u64 },
UnsupportedStructure { reason: String },
}
impl std::fmt::Display for NbError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::CommandFailed {
command,
stderr,
exit_code,
} => write!(
f,
"command {command:?} failed (exit {exit_code:?}): {stderr}"
),
Self::ExecutableNotFound { path } => {
write!(f, "`nb` executable not found at path {path:?}")
}
Self::NotFound { selector } => write!(f, "not found: {selector:?}"),
Self::Io { path, source } => write!(f, "I/O error at {path:?}: {source}"),
Self::UnsupportedShowTarget {
selector,
actual_type,
} => write!(
f,
"selector `{selector}` resolved to non-textual type `{actual_type}`; \
`nb show` does not display non-textual content"
),
Self::DuplicateTitleHeading { title, heading } => write!(
f,
"title `{title}` duplicates the first H1 in content (`{heading}`); \
remove the duplicate heading to avoid double-rendering"
),
Self::ParseError { kind, location } => {
write!(f, "parse error: {kind:?} at {location:?}")
}
Self::InvalidFingerprint { reason } => {
write!(f, "invalid fingerprint: {reason:?}")
}
Self::JsonParseError { source } => {
write!(f, "JSON parse error: {source:?}")
}
Self::ValidationError {
reason,
location: _,
} => {
write!(f, "validation error: {reason:?}")
}
Self::UnsupportedDocumentFormat {
extension,
supported,
} => {
write!(
f,
"unsupported document format: {extension:?} (supported: {supported:?})"
)
}
Self::GateTimeout { gate, timeout_ms } => {
write!(f, "gate timeout waiting on {gate} after {timeout_ms}ms")
}
Self::DirtyBaseline { guidance } => {
write!(f, "dirty baseline: {guidance}")
}
Self::PathCollision { path, plan_index } => {
write!(f, "path collision at {path:?} (plan_index={plan_index:?})")
}
Self::PathIgnored {
path,
guidance,
plan_index,
} => write!(
f,
"ignored path {path:?} (plan_index={plan_index:?}): {guidance}"
),
Self::PlanValidation {
kind,
message,
plan_index,
} => write!(
f,
"plan validation ({kind}) at index {plan_index:?}: {message}"
),
Self::IndeterminateCommit {
pre_revision,
post_revision_observed,
guidance,
} => write!(
f,
"indeterminate commit (pre={pre_revision}, post={post_revision_observed:?}): {guidance}"
),
Self::RecoveryRequired {
pre_revision,
guidance,
..
} => write!(
f,
"recovery required (pre_revision={pre_revision}): {guidance}"
),
Self::FingerprintMismatch { target, guidance } => {
write!(f, "fingerprint mismatch for {target:?}: {guidance}")
}
Self::AnchorMismatch {
target,
number,
guidance,
} => write!(f, "anchor mismatch for {target} line {number}: {guidance}"),
Self::OccurrenceMismatch { expected, actual } => {
write!(
f,
"occurrence mismatch: expected={expected} actual={actual}"
)
}
Self::OverlappingEdits { indices } => {
write!(f, "overlapping edits at indices {indices:?}")
}
Self::InvalidLineWindow {
offset,
limit,
total_lines,
} => write!(
f,
"invalid line window offset={offset} limit={limit} total_lines={total_lines}"
),
Self::EmptySubstringPattern => write!(f, "empty substring pattern"),
Self::FragmentedBody {
fragment_count,
guidance,
} => write!(
f,
"fragmented body ({fragment_count} fragments): {guidance}"
),
Self::NonUtf8 {
selector,
path,
kind,
mime_hint,
} => write!(
f,
"non-UTF-8 text at {selector:?} ({path:?}, kind={kind}, mime={mime_hint:?}); use read_note_source_bytes for raw access"
),
Self::IndexLockTimeout { path, timeout_ms } => {
write!(f, "index lock timeout on {path} after {timeout_ms}ms")
}
Self::UnsupportedStructure { reason } => {
write!(f, "unsupported structure: {reason}")
}
}
}
}
impl std::error::Error for NbError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ParseErrorKind {
MissingTitle,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[error("{kind:?}: {message}")]
pub struct IoError {
pub kind: IoErrorKind,
pub message: String,
pub os_error: Option<i32>,
pub source: Option<Box<IoError>>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum IoErrorKind {
NotFound,
PermissionDenied,
ConnectionRefused,
ConnectionReset,
ConnectionAborted,
NotConnected,
AddrInUse,
AddrNotAvailable,
BrokenPipe,
AlreadyExists,
WouldBlock,
InvalidInput,
InvalidData,
TimedOut,
WriteZero,
Interrupted,
UnexpectedEof,
OutOfMemory,
Other,
}
impl IoErrorKind {
pub fn from_std(kind: std::io::ErrorKind) -> Self {
match kind {
std::io::ErrorKind::NotFound => Self::NotFound,
std::io::ErrorKind::PermissionDenied => Self::PermissionDenied,
std::io::ErrorKind::ConnectionRefused => Self::ConnectionRefused,
std::io::ErrorKind::ConnectionReset => Self::ConnectionReset,
std::io::ErrorKind::ConnectionAborted => Self::ConnectionAborted,
std::io::ErrorKind::NotConnected => Self::NotConnected,
std::io::ErrorKind::AddrInUse => Self::AddrInUse,
std::io::ErrorKind::AddrNotAvailable => Self::AddrNotAvailable,
std::io::ErrorKind::BrokenPipe => Self::BrokenPipe,
std::io::ErrorKind::AlreadyExists => Self::AlreadyExists,
std::io::ErrorKind::WouldBlock => Self::WouldBlock,
std::io::ErrorKind::InvalidInput => Self::InvalidInput,
std::io::ErrorKind::InvalidData => Self::InvalidData,
std::io::ErrorKind::TimedOut => Self::TimedOut,
std::io::ErrorKind::WriteZero => Self::WriteZero,
std::io::ErrorKind::Interrupted => Self::Interrupted,
std::io::ErrorKind::UnexpectedEof => Self::UnexpectedEof,
std::io::ErrorKind::OutOfMemory => Self::OutOfMemory,
_ => Self::Other,
}
}
}
impl From<std::io::ErrorKind> for IoErrorKind {
fn from(kind: std::io::ErrorKind) -> Self {
Self::from_std(kind)
}
}
impl From<std::io::Error> for IoError {
fn from(err: std::io::Error) -> Self {
snapshot_io_error(err)
}
}
fn snapshot_io_error(err: std::io::Error) -> IoError {
let kind = IoErrorKind::from_std(err.kind());
let os_error = err.raw_os_error();
let message = err.to_string();
let source = walk_source_chain(err.source());
IoError {
kind,
message,
os_error,
source,
}
}
fn walk_source_chain(source: Option<&(dyn std::error::Error + 'static)>) -> Option<Box<IoError>> {
let head = source?;
Some(Box::new(snapshot_link(head)))
}
fn snapshot_link(current: &(dyn std::error::Error + 'static)) -> IoError {
if let Some(io_err) = current.downcast_ref::<std::io::Error>() {
IoError {
kind: IoErrorKind::from_std(io_err.kind()),
message: io_err.to_string(),
os_error: io_err.raw_os_error(),
source: walk_source_chain(io_err.source()),
}
} else {
IoError {
kind: IoErrorKind::Other,
message: current.to_string(),
os_error: None,
source: walk_source_chain(current.source()),
}
}
}
impl From<IoError> for std::io::Error {
fn from(snapshot: IoError) -> Self {
if let Some(code) = snapshot.os_error {
std::io::Error::from_raw_os_error(code)
} else {
let kind = match snapshot.kind {
IoErrorKind::NotFound => std::io::ErrorKind::NotFound,
IoErrorKind::PermissionDenied => std::io::ErrorKind::PermissionDenied,
IoErrorKind::ConnectionRefused => std::io::ErrorKind::ConnectionRefused,
IoErrorKind::ConnectionReset => std::io::ErrorKind::ConnectionReset,
IoErrorKind::ConnectionAborted => std::io::ErrorKind::ConnectionAborted,
IoErrorKind::NotConnected => std::io::ErrorKind::NotConnected,
IoErrorKind::AddrInUse => std::io::ErrorKind::AddrInUse,
IoErrorKind::AddrNotAvailable => std::io::ErrorKind::AddrNotAvailable,
IoErrorKind::BrokenPipe => std::io::ErrorKind::BrokenPipe,
IoErrorKind::AlreadyExists => std::io::ErrorKind::AlreadyExists,
IoErrorKind::WouldBlock => std::io::ErrorKind::WouldBlock,
IoErrorKind::InvalidInput => std::io::ErrorKind::InvalidInput,
IoErrorKind::InvalidData => std::io::ErrorKind::InvalidData,
IoErrorKind::TimedOut => std::io::ErrorKind::TimedOut,
IoErrorKind::WriteZero => std::io::ErrorKind::WriteZero,
IoErrorKind::Interrupted => std::io::ErrorKind::Interrupted,
IoErrorKind::UnexpectedEof => std::io::ErrorKind::UnexpectedEof,
IoErrorKind::OutOfMemory => std::io::ErrorKind::OutOfMemory,
IoErrorKind::Other => std::io::ErrorKind::Other,
};
std::io::Error::new(kind, snapshot.message)
}
}
}