1use std::fmt;
4use std::io;
5
6pub type DocumentResult<T> = Result<T, DocumentError>;
7
8#[derive(Debug, Clone)]
9pub enum DocumentError {
10 EmptyPath,
11 EmptyValues,
12 UnknownSegment {
13 path: String,
14 segment: String,
15 },
16 UnregisteredArray {
24 path: String,
25 },
26 SlugNotFound {
27 prefix: String,
28 slug: String,
29 },
30 AmbiguousMatch {
41 prefix: String,
42 segment: String,
43 indices: Vec<usize>,
44 },
45 SlugAlreadyExists {
46 prefix: String,
47 slug: String,
48 },
49 NotTraversable {
50 path: String,
51 got: String,
52 },
53 TypeMismatch {
54 path: String,
55 expected: String,
56 got: String,
57 hint: Option<String>,
58 },
59 PathNotFound {
60 path: String,
61 },
62 IndexOutOfBounds {
63 path: String,
64 index: usize,
65 len: usize,
66 },
67 ParseError {
70 format: String,
71 detail: String,
72 },
73 PathSyntax {
81 detail: String,
82 },
83 SourceRefused {
92 format: String,
93 detail: String,
94 },
95 InvalidArgument {
98 detail: String,
99 },
100 WriteWouldCorrupt {
106 format: String,
107 detail: String,
108 },
109 FormatUnknown {
115 path: String,
116 },
117 AlreadyExists {
121 path: String,
122 },
123 TooLarge {
128 path: String,
129 max_bytes: u64,
130 },
131 EmptyInput {
135 source: String,
136 },
137 IoError {
138 detail: String,
139 },
140 UnsupportedOperation {
141 format: String,
142 operation: String,
143 detail: String,
144 },
145}
146
147impl fmt::Display for DocumentError {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 match self {
150 DocumentError::EmptyPath => {
151 write!(f, "empty path provided")
152 }
153 DocumentError::EmptyValues => {
154 write!(f, "at least one value required")
155 }
156 DocumentError::UnknownSegment { path, segment } => {
157 write!(f, "path `{path}` segment `{segment}` not found")
158 }
159 DocumentError::UnregisteredArray { path } => {
160 write!(
161 f,
162 "array at `{path}` has no rule for naming an element by its content; \
163 address an element by index, or name the field that identifies one"
164 )
165 }
166 DocumentError::SlugNotFound { prefix, slug } => {
167 write!(f, "no element with slug `{slug}` found in `{prefix}`")
168 }
169 DocumentError::SlugAlreadyExists { prefix, slug } => {
170 write!(f, "slug `{slug}` already exists in `{prefix}`")
171 }
172 DocumentError::AmbiguousMatch {
173 prefix,
174 segment,
175 indices,
176 } => {
177 let candidates = indices
178 .iter()
179 .map(usize::to_string)
180 .collect::<Vec<_>>()
181 .join(", ");
182 write!(
183 f,
184 "segment `{}` matches {} elements of `{}` at indices {}",
185 segment,
186 indices.len(),
187 prefix,
188 candidates
189 )
190 }
191 DocumentError::NotTraversable { path, got } if path.is_empty() => {
194 if got == "null" {
195 write!(
196 f,
197 "the document is empty (its root is null), cannot traverse into it"
198 )
199 } else {
200 write!(f, "the document root is {got}, cannot traverse into it")
201 }
202 }
203 DocumentError::NotTraversable { path, got } => {
204 write!(f, "path `{path}` is {got}, cannot traverse further")
205 }
206 DocumentError::TypeMismatch {
207 path,
208 expected,
209 got,
210 hint,
211 } => {
212 write!(f, "field `{path}` expects {expected}, got `{got}`")?;
213 if let Some(h) = hint {
214 write!(f, "\n hint: {h}")?;
215 }
216 Ok(())
217 }
218 DocumentError::PathNotFound { path } => {
219 write!(f, "path `{path}` not found in document")
220 }
221 DocumentError::IndexOutOfBounds { path, index, len } => {
222 write!(f, "index {index} out of bounds at `{path}` (len {len})")
223 }
224 DocumentError::ParseError { format, detail } => {
225 write!(f, "failed to parse {format}: {detail}")
226 }
227 DocumentError::PathSyntax { detail } => {
228 write!(f, "invalid path: {detail}")
229 }
230 DocumentError::SourceRefused { format, detail } => {
231 write!(f, "refusing to read this {format}: {detail}")
232 }
233 DocumentError::InvalidArgument { detail } => {
234 write!(f, "invalid argument: {detail}")
235 }
236 DocumentError::WriteWouldCorrupt { format, detail } => {
237 write!(
238 f,
239 "refusing to write: the edit produced {format} this parser rejects ({detail}); the file is unchanged"
240 )
241 }
242 DocumentError::FormatUnknown { path } => {
243 write!(
244 f,
245 "cannot detect the format of `{path}` from its extension; pass an explicit format"
246 )
247 }
248 DocumentError::AlreadyExists { path } => {
249 write!(f, "document target `{path}` already exists")
250 }
251 DocumentError::TooLarge { path, max_bytes } => {
252 write!(f, "`{path}` exceeds the {max_bytes}-byte read limit")
253 }
254 DocumentError::EmptyInput { source } => {
255 write!(
256 f,
257 "{source} is empty (zero bytes); there is no document to read"
258 )
259 }
260 DocumentError::IoError { detail } => {
261 write!(f, "io error: {detail}")
262 }
263 DocumentError::UnsupportedOperation {
264 format,
265 operation,
266 detail,
267 } => write!(f, "{format} does not support {operation}: {detail}"),
268 }
269 }
270}
271
272impl std::error::Error for DocumentError {}
273
274impl DocumentError {
275 #[must_use]
281 pub const fn code(&self) -> &'static str {
282 match self {
283 Self::ParseError { .. } => "document_parse_failed",
284 Self::PathSyntax { .. } => "document_invalid_path",
285 Self::SourceRefused { .. } => "document_source_refused",
286 Self::FormatUnknown { .. } => "document_format_unknown",
287 Self::AlreadyExists { .. } => "document_target_exists",
288 Self::TooLarge { .. } => "document_too_large",
289 Self::WriteWouldCorrupt { .. } => "document_write_would_corrupt",
290 Self::PathNotFound { .. }
291 | Self::UnknownSegment { .. }
292 | Self::IndexOutOfBounds { .. }
293 | Self::UnregisteredArray { .. } => "document_path_not_found",
294 Self::NotTraversable { .. } | Self::TypeMismatch { .. } => "document_type_mismatch",
295 Self::SlugNotFound { .. } => "document_slug_not_found",
296 Self::AmbiguousMatch { .. } => "document_ambiguous_match",
297 Self::SlugAlreadyExists { .. } => "document_slug_exists",
298 Self::EmptyInput { .. } => "document_empty",
299 Self::IoError { .. } => "document_io_failed",
300 Self::UnsupportedOperation { .. } => "document_unsupported_operation",
301 Self::EmptyPath | Self::EmptyValues | Self::InvalidArgument { .. } => {
302 "document_invalid_argument"
303 }
304 }
305 }
306
307 #[must_use]
316 pub fn location(&self) -> Option<String> {
317 let Self::ParseError { detail, .. } = self else {
318 return None;
319 };
320 let head = detail.split('\n').next().unwrap_or(detail);
331 let rest = match head.split_once(" at line ") {
332 Some((_, rest)) => rest,
333 None => head.strip_prefix("line ")?,
334 };
335 let line = leading_ascii_digits(rest)?;
336 let column = rest
337 .split_once("column ")
338 .and_then(|(_, tail)| leading_ascii_digits(tail));
339 Some(match column {
340 Some(column) => format!("line {line} column {column}"),
341 None => format!("line {line}"),
342 })
343 }
344
345 #[must_use]
373 pub fn redacted_message(&self) -> String {
374 match self {
375 #[cfg(feature = "plist")]
378 Self::ParseError { detail, .. }
379 if detail == crate::document::format::plist::WRONG_FORMAT_DETAIL
380 || detail == crate::document::format::plist::WRONG_FORMAT_XML_DETAIL =>
381 {
382 self.to_string()
383 }
384 Self::ParseError { format, .. } => match self.location() {
385 Some(location) => format!("failed to parse {format} at {location}"),
386 None => format!("failed to parse {format}"),
387 },
388 Self::TypeMismatch { path, expected, .. } => {
389 if expected.is_empty() {
390 format!("field `{path}` has the wrong type")
391 } else {
392 format!("field `{path}` expects {expected}")
393 }
394 }
395 other => other.to_string(),
396 }
397 }
398
399 pub fn from_serde(path: impl Into<String>, err: impl std::fmt::Display) -> Self {
403 let msg = err.to_string();
404 let hint = msg
407 .split(" at line ")
408 .next()
409 .unwrap_or(&msg)
410 .trim()
411 .to_string();
412 DocumentError::TypeMismatch {
413 path: path.into(),
414 expected: String::new(),
415 got: hint,
416 hint: None,
417 }
418 }
419}
420
421impl From<io::Error> for DocumentError {
422 fn from(err: io::Error) -> Self {
423 DocumentError::IoError {
424 detail: err.to_string(),
425 }
426 }
427}
428
429fn leading_ascii_digits(text: &str) -> Option<&str> {
430 let end = text.bytes().take_while(u8::is_ascii_digit).count();
431 (end > 0).then_some(&text[..end])
432}
433
434#[cfg(test)]
435mod tests {
436 use super::DocumentError;
437
438 #[test]
439 fn document_error_codes_are_stable() {
440 let cases = [
441 (DocumentError::EmptyPath, "document_invalid_argument"),
442 (DocumentError::EmptyValues, "document_invalid_argument"),
443 (
444 DocumentError::UnknownSegment {
445 path: "root.key".to_string(),
446 segment: "key".to_string(),
447 },
448 "document_path_not_found",
449 ),
450 (
451 DocumentError::UnregisteredArray {
452 path: "items".to_string(),
453 },
454 "document_path_not_found",
455 ),
456 (
457 DocumentError::SlugNotFound {
458 prefix: "items".to_string(),
459 slug: "missing".to_string(),
460 },
461 "document_slug_not_found",
462 ),
463 (
464 DocumentError::SlugAlreadyExists {
465 prefix: "items".to_string(),
466 slug: "existing".to_string(),
467 },
468 "document_slug_exists",
469 ),
470 (
471 DocumentError::AmbiguousMatch {
472 prefix: "items".to_string(),
473 segment: "look".to_string(),
474 indices: vec![0, 2],
475 },
476 "document_ambiguous_match",
477 ),
478 (
479 DocumentError::NotTraversable {
480 path: "root".to_string(),
481 got: "string".to_string(),
482 },
483 "document_type_mismatch",
484 ),
485 (
486 DocumentError::TypeMismatch {
487 path: "root.key".to_string(),
488 expected: "integer".to_string(),
489 got: "string".to_string(),
490 hint: None,
491 },
492 "document_type_mismatch",
493 ),
494 (
495 DocumentError::PathNotFound {
496 path: "root.key".to_string(),
497 },
498 "document_path_not_found",
499 ),
500 (
501 DocumentError::EmptyInput {
502 source: "stdin".to_string(),
503 },
504 "document_empty",
505 ),
506 (
507 DocumentError::IndexOutOfBounds {
508 path: "items".to_string(),
509 index: 2,
510 len: 1,
511 },
512 "document_path_not_found",
513 ),
514 (
515 DocumentError::ParseError {
516 format: "JSON".to_string(),
517 detail: "invalid input".to_string(),
518 },
519 "document_parse_failed",
520 ),
521 (
522 DocumentError::IoError {
523 detail: "unreadable".to_string(),
524 },
525 "document_io_failed",
526 ),
527 (
528 DocumentError::AlreadyExists {
529 path: "config.toml".to_string(),
530 },
531 "document_target_exists",
532 ),
533 (
534 DocumentError::TooLarge {
535 path: "config.toml".to_string(),
536 max_bytes: 1024,
537 },
538 "document_too_large",
539 ),
540 (
541 DocumentError::UnsupportedOperation {
542 format: "INI".to_string(),
543 operation: "set".to_string(),
544 detail: "unsupported".to_string(),
545 },
546 "document_unsupported_operation",
547 ),
548 ];
549
550 for (error, expected) in cases {
551 assert_eq!(error.code(), expected);
552 }
553 }
554
555 #[test]
556 fn location_extracts_position_without_content() {
557 let err = DocumentError::ParseError {
563 format: "TOML".to_string(),
564 detail: "TOML parse error at line 5, column 12\n |\n\
565 5 | note = \"see at line 999 for TOPSECRET\" bad\n | ^"
566 .to_string(),
567 };
568 assert_eq!(err.location().as_deref(), Some("line 5 column 12"));
569 assert!(!err.redacted_message().contains("999"));
570 assert!(!err.redacted_message().contains("TOPSECRET"));
571
572 let no_column = DocumentError::ParseError {
573 format: "JSON".to_string(),
574 detail: "boom at line 3".to_string(),
575 };
576 assert_eq!(no_column.location().as_deref(), Some("line 3"));
577
578 assert!(
580 DocumentError::ParseError {
581 format: "INI".to_string(),
582 detail: "sensitive value".to_string(),
583 }
584 .location()
585 .is_none()
586 );
587 assert!(
588 DocumentError::PathNotFound {
589 path: "a.b".to_string(),
590 }
591 .location()
592 .is_none()
593 );
594 }
595
596 #[test]
597 fn redacted_message_drops_parser_detail() {
598 let err = DocumentError::ParseError {
599 format: "YAML".to_string(),
600 detail: "unexpected TOPSECRET at line 5 column 12".to_string(),
601 };
602 let redacted = err.redacted_message();
603 assert_eq!(redacted, "failed to parse YAML at line 5 column 12");
604 assert!(!redacted.contains("TOPSECRET"));
605
606 let path_err = DocumentError::PathNotFound {
608 path: "database.url".to_string(),
609 };
610 assert_eq!(path_err.redacted_message(), path_err.to_string());
611 }
612
613 #[test]
614 fn redacted_message_drops_the_offending_value() {
615 let err = DocumentError::from_serde(
618 "credentials.token",
619 "invalid type: string \"sk-live-TOPSECRET\", expected u16",
620 );
621 assert!(err.to_string().contains("sk-live-TOPSECRET"));
622 let redacted = err.redacted_message();
623 assert!(!redacted.contains("sk-live-TOPSECRET"), "{redacted}");
624 assert!(redacted.contains("credentials.token"), "{redacted}");
625 }
626
627 #[test]
628 fn ambiguous_match_reports_indices_without_document_content() {
629 let err = DocumentError::AmbiguousMatch {
630 prefix: "h1.0.h2".to_string(),
631 segment: "look".to_string(),
632 indices: vec![0, 2],
633 };
634 assert_eq!(
635 err.redacted_message(),
636 "segment `look` matches 2 elements of `h1.0.h2` at indices 0, 2"
637 );
638 assert!(!err.redacted_message().contains("Quick look"));
639 }
640
641 #[test]
642 fn not_traversable_names_the_type_not_the_value() {
643 let err = DocumentError::NotTraversable {
646 path: "token_secret.inner".to_string(),
647 got: crate::document::Value::String("sk-live-TOPSECRET".to_string())
648 .kind_name()
649 .to_string(),
650 };
651 assert_eq!(
652 err.to_string(),
653 "path `token_secret.inner` is string, cannot traverse further"
654 );
655 assert_eq!(err.redacted_message(), err.to_string());
656 }
657
658 #[test]
659 fn not_traversable_at_the_root_names_the_document() {
660 let empty = DocumentError::NotTraversable {
661 path: String::new(),
662 got: "null".to_string(),
663 };
664 assert_eq!(
665 empty.to_string(),
666 "the document is empty (its root is null), cannot traverse into it"
667 );
668 let scalar = DocumentError::NotTraversable {
669 path: String::new(),
670 got: "string".to_string(),
671 };
672 assert_eq!(
673 scalar.to_string(),
674 "the document root is string, cannot traverse into it"
675 );
676 }
677}