Repository navigation
Expand file tree
/
Copy patherror.rs
More file actions
1043 lines (906 loc) · 36.5 KB
/
Copy patherror.rs
File metadata and controls
1043 lines (906 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Error types for the FORGE Markdown-to-OSCAL pipeline.
//!
//! This module defines [`ForgeError`], a comprehensive error enum covering
//! all failure modes in the pipeline: input/IO errors, parse/structure errors,
//! validation/config errors, export errors, argument errors, batch errors,
//! external dependency errors, and diff errors.
//!
//! The [`exit_code`] function maps each variant to a CLI exit code:
//! - `1`: Input/IO errors
//! - `2`: Parse/Structure errors
//! - `3`: Validation/Config errors
//! - `4`: External dependency unavailable
use std::path::PathBuf;
use thiserror::Error;
#[allow(clippy::cast_precision_loss)] // Precision loss is acceptable for human-readable file sizes
#[allow(clippy::trivially_copy_pass_by_ref)] // thiserror passes struct fields by reference
fn format_size(bytes: &u64) -> String {
let bytes = *bytes;
if bytes < 1_048_576 {
format!("{:.1}KB", bytes as f64 / 1024.0)
} else if bytes < 1_073_741_824 {
format!("{:.1}MB", bytes as f64 / 1_048_576.0)
} else {
format!("{:.1}GB", bytes as f64 / 1_073_741_824.0)
}
}
/// Comprehensive error type for all FORGE pipeline failures.
///
/// Each variant is annotated with `#[error("...")]` (via [`thiserror`]) for
/// automatic [`Display`](std::fmt::Display) and [`Error`](std::error::Error) impls. Variants are organized into
/// logical groups matching CLI exit code categories.
#[derive(Debug, Error)]
pub enum ForgeError {
// --- Input/IO errors (exit code 1) ---
/// The specified input file does not exist.
#[error("File not found: '{}'", path.display())]
FileNotFound {
/// The path that could not be found.
path: PathBuf,
},
/// The current user lacks read permission for the specified file.
#[error("Permission denied: '{}'", path.display())]
PermissionDenied {
/// The path with insufficient permissions.
path: PathBuf,
},
/// The input file exists but contains no content.
#[error(
"File is empty: '{}' — provide a non-empty Markdown policy document",
path.display()
)]
EmptyInput {
/// The path to the empty file.
path: PathBuf,
},
/// The file appears to contain binary data rather than UTF-8 text.
#[error(
"File appears to be binary, not a text document: '{}'. \
FORGE accepts UTF-8 Markdown (.md) files.",
path.display()
)]
BinaryFile {
/// The path to the binary file.
path: PathBuf,
},
/// A PDF contained no extractable text; OCR is not supported by this release.
#[error(
"PDF has no extractable text: '{}'. OCR for scanned/image-only PDFs is not supported; provide a text-based PDF, DOCX, or Markdown source.",
path.display()
)]
OcrNotSupported {
/// The path to the scanned/image-only PDF.
path: PathBuf,
},
/// The file extension is not a supported Markdown format.
#[error(
"Unsupported file format '.{extension}'. Only Markdown files (.md, .markdown) are supported. \
Consider converting with pandoc or markitdown."
)]
UnsupportedFormat {
/// The unsupported file extension (without leading dot).
extension: String,
},
/// The input file exceeds the maximum allowed size.
#[error(
"File '{}' is {}, exceeding the {} limit.",
path.display(),
format_size(.size_bytes),
format_size(.limit_bytes)
)]
FileTooLarge {
/// The path to the oversized file.
path: PathBuf,
/// The actual file size in bytes.
size_bytes: u64,
/// The configured size limit in bytes.
limit_bytes: u64,
},
/// The input file exceeds the maximum allowed size for a command that accepts `--max-size`.
#[error(
"File '{}' is {}, exceeding the {} limit. Use --max-size to increase the limit.",
path.display(),
format_size(.size_bytes),
format_size(.limit_bytes)
)]
FileTooLargeWithMaxSize {
/// The path to the oversized file.
path: PathBuf,
/// The actual file size in bytes.
size_bytes: u64,
/// The configured size limit in bytes.
limit_bytes: u64,
},
/// The file is not valid UTF-8 text.
#[error(
"File '{}' is not valid UTF-8 text. FORGE requires UTF-8 encoded Markdown files.",
path.display()
)]
InvalidEncoding {
/// The path to the file with invalid encoding.
path: PathBuf,
},
/// The path does not refer to a regular file (e.g., it is a directory, broken symlink, or special file).
#[error("'{}' is not a regular file.", path.display())]
NotAFile {
/// The path that is not a regular file.
path: PathBuf,
},
/// A low-level I/O error (from [`std::io`]).
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
// --- Parse/Structure errors (exit code 2) ---
/// The input file contains no recognizable policy structure (headings or numbered clauses).
#[error(
"No policy structure detected in '{}' — expected Markdown headings (# Section) or numbered clauses",
path.display()
)]
NoStructureDetected {
/// The path to the file lacking structure.
path: PathBuf,
},
/// A generic Markdown parsing error.
#[error("Parse error: {0}")]
Parse(String),
/// An error occurred while building an OSCAL catalog.
#[error("Catalog build error: {0}")]
CatalogBuild(String),
/// An error occurred while processing back matter.
#[error("Back matter error: {0}")]
BackMatter(String),
/// An error occurred while building a component definition.
#[error("Component definition build error: {0}")]
ComponentDefinitionBuild(String),
/// An error occurred while building an assessment plan.
#[error("Assessment plan build error: {0}")]
AssessmentPlanBuild(String),
/// A trustworthy OSCAL Assessment Results artifact could not be produced.
#[error("Assessment Results build error: {0}")]
AssessmentResultsBuild(String),
/// POA&M foundation input or publication failed.
#[error("POA&M foundation error: {0}")]
PoamBuild(String),
/// A valid authored POA&M schedule contains explicit review or schedule actions.
#[error("POA&M schedule action required")]
PoamActionRequired,
/// A valid Assessment Results baseline comparison requires human review.
#[error("Assessment Results revision requires human review")]
AssessmentResultsReviewRequired,
/// An error occurred while building an SSP (System Security Plan).
#[error("SSP build error: {0}")]
SspBuild(String),
/// An SSP build failed while preserving its underlying source error.
#[error("SSP build error: {context}: {source}")]
SspBuildWithSource {
/// Build-stage context.
context: String,
/// Underlying failure.
#[source]
source: Box<ForgeError>,
},
/// A trustworthy OSCAL Control Mapping artifact could not be produced.
#[error("Control Mapping build error: {0}")]
MappingBuild(String),
/// Completed Mapping impact analysis requires human review under the selected policy.
#[error("Control Mapping changes require human review")]
MappingReviewRequired,
/// A trustworthy evidence/implementation linkage index could not be produced.
#[error("Evidence linkage error: {0}")]
Linkage(String),
/// A valid linkage analysis contains findings selected by the requested gate.
#[error("Evidence linkage action required")]
LinkageActionRequired,
/// A connector-neutral integration change set, plan, or state is invalid.
#[error("Integration error: {0}")]
Integration(String),
/// A lifecycle record, transition, portfolio, or artifact binding is invalid.
#[error("Policy lifecycle error: {0}")]
Lifecycle(String),
/// A valid lifecycle record requires human action under the selected gate.
#[error("Policy lifecycle action required")]
LifecycleActionRequired,
/// A trustworthy framework applicability report could not be produced.
#[error("Applicability analysis error: {0}")]
ApplicabilityAnalysis(String),
/// A completed applicability analysis contains categories selected by the gate policy.
#[error("Applicability analysis requires human review")]
ApplicabilityReviewRequired,
/// A trustworthy framework impact report could not be produced.
#[error("Framework impact analysis error: {0}")]
FrameworkImpact(String),
/// A reusable policy component or composition contract is invalid.
#[error("Policy composition error: {0}")]
PolicyComposition(String),
/// Invalid or unsafe local policy-authoring input or output.
#[error("Policy authoring error: {0}")]
Authoring(String),
/// A valid authoring plan contains unresolved gaps or required context.
#[error("Policy authoring action required")]
AuthoringActionRequired,
/// Framework impact construction failed while preserving its source error.
#[error("Framework impact analysis error: {context}: {source}")]
FrameworkImpactWithSource {
/// Operation context.
context: String,
/// Underlying failure.
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
/// Completed framework impact analysis requires action under the selected gate.
#[error("Framework changes require human review")]
FrameworkReviewRequired,
/// An error occurred during parameter extraction.
#[error("Parameter extraction error: {0}")]
ParameterExtraction(String),
/// The OSCAL artifact type is not supported for tracing.
#[error("Unsupported OSCAL artifact type for tracing: {detail}")]
TraceUnsupportedArtifact {
/// Human-readable detail about the unsupported type.
detail: String,
},
/// The input file contains multiple OSCAL model types instead of exactly one.
#[error(
"Ambiguous OSCAL artifact: file contains multiple model types ({detail}). Each file must contain exactly one OSCAL model."
)]
AmbiguousArtifact {
/// A description of the conflicting model types found.
detail: String,
},
// --- Validation/Config errors (exit code 3) ---
/// A document validation error (content rule violations).
#[error("Validation error: {0}")]
Validation(String),
/// A configuration error (invalid CLI options, environment, etc.).
#[error("Configuration error: {0}")]
Config(String),
// --- Export errors (exit code 1) ---
/// The input file extension does not match a supported OSCAL serialization format.
#[error(
"Unrecognized file extension '.{extension}' on input file. \
Expected .json, .xml, .yaml, or .yml for OSCAL artifacts."
)]
ExportUnsupportedExtension {
/// The unrecognized file extension.
extension: String,
},
/// The input file has no extension, so the OSCAL format cannot be determined.
#[error(
"No file extension on input file '{}'. \
Cannot determine OSCAL format. Expected .json, .xml, .yaml, or .yml.",
path.display()
)]
ExportNoExtension {
/// The path to the file with no extension.
path: PathBuf,
},
/// The input is not valid JSON, XML, or YAML representing an OSCAL artifact.
#[error("Input is not a valid OSCAL artifact: {detail}")]
ExportInvalidOscal {
/// Human-readable detail about why the artifact is invalid.
detail: String,
},
/// The export input file is empty.
#[error("Export input file is empty: '{}'", path.display())]
ExportEmptyInput {
/// The path to the empty export input file.
path: PathBuf,
},
// --- Argument errors (exit code 1) ---
/// An invalid command-line argument was provided.
#[error("Invalid argument: {0}")]
InvalidArgument(String),
// --- Batch errors (exit code 1) ---
/// An error occurred during batch conversion of multiple files.
#[error("Batch conversion error: {0}")]
BatchConversion(String),
// --- Usage errors (exit code 2) ---
/// A required command argument was not supplied by any layer (CLI or
/// project configuration). Mirrors clap's usage-error behavior so the
/// no-config exit code remains unchanged (PRD 051 M-14).
///
/// Displayed without its own `error:` prefix because `main` already wraps
/// every message in `Error: …`; carrying both prefixes produced
/// `Error: error: …`.
///
/// Warning: this no-prefix contract applies only when rendered through `main`;
/// other renderers receive the raw clap usage text.
#[error("{0}")]
MissingRequiredArgument(String),
// --- External dependency errors (exit code 4) ---
/// The `oscal-cli` tool was not found on the system PATH.
#[error(
"oscal-cli not found on system PATH. Install from: https://github.com/usnistgov/oscal-cli"
)]
OscalCliNotFound,
/// The `oscal-cli` binary was located but is not functional.
#[error("oscal-cli found at '{}' but is not functional: {detail}", path.display())]
OscalCliNotFunctional {
/// The path where `oscal-cli` was found.
path: PathBuf,
/// Human-readable detail about why the tool is not functional.
detail: String,
},
// --- oscal-cli execution errors (exit code 1) ---
/// The `oscal-cli` process finished with a non-zero exit code.
#[error("oscal-cli execution failed (exit code {exit_code:?}): {message}")]
OscalCliExecution {
/// The exit code returned by `oscal-cli`, or `None` if terminated by signal.
exit_code: Option<i32>,
/// The error message or combined stderr/stdout output.
message: String,
},
/// The `oscal-cli` process exceeded the configured timeout.
#[error("oscal-cli execution timed out after {timeout:?}")]
OscalCliTimeout {
/// The timeout duration that was exceeded.
timeout: std::time::Duration,
},
/// Profile resolution requires JSON input, but a different format was provided.
#[error(
"Expected JSON input file, got: '{}'. Only .json files are supported for profile resolution.",
path.display()
)]
ResolveInputNotJson {
/// The path to the non-JSON input file.
path: PathBuf,
},
// --- Diff/drift errors (exit code 2 for DiffError, exit code 1 when changes exist) ---
/// The diff operation detected changes between golden and current output.
///
/// This variant has an empty error message because the diff details are
/// printed separately by the CLI.
#[error("")]
DiffHasChanges,
/// The canonical CI comparison detected substantive artifact drift.
/// Status is printed separately without artifact content.
#[error("")]
DriftDetected,
/// A completed policy migration analysis found reviewable changes.
/// The report is printed separately by the CLI.
#[error("")]
MigrationHasChanges,
/// A trustworthy, complete policy migration report could not be produced.
#[error("Migration error: {0}")]
MigrationError(String),
/// A generic error during full pipeline preparation that identifies the
/// source line where an ordering invariant was violated.
#[error("Pipeline invariant violated at source line {source_line}: {context}")]
PipelineInvariant {
/// 1-based source line associated with the invariant failure.
source_line: usize,
/// Human-readable invariant context.
context: String,
},
/// A conversion leg in a round-trip chain failed.
#[error("Round-trip step {step} ({from} -> {to}) failed: {source}")]
RoundTripStep {
/// Zero-based chain step.
step: usize,
/// Input artifact path for this leg.
from: PathBuf,
/// Output artifact path for this leg.
to: PathBuf,
/// Underlying conversion failure.
#[source]
source: Box<ForgeError>,
},
/// Round-trip validation found unresolved divergences.
#[error("Round-trip validation failed: {0} unresolved divergence(s)")]
RoundTripFailed(usize),
/// A generic error during diff computation.
#[error("Diff error: {0}")]
DiffError(String),
// --- Other (exit code 1) ---
/// Serialization to JSON, XML, or YAML failed.
#[error("Serialization error: {0}")]
Serialization(String),
/// YAML serialization failed with its source error preserved.
#[error("YAML serialization error ({context}): {source}")]
YamlSerialization {
/// Serialization boundary.
context: String,
/// YAML crate source error.
#[source]
source: serde_yaml::Error,
},
/// Validation against the OSCAL JSON Schema failed.
#[error("Schema validation failed: {0}")]
SchemaValidation(String),
}
/// Map a [`ForgeError`] to a CLI exit code.
///
/// Exit code categories:
/// - `0`: Success (not handled here — only error cases)
/// - `1`: Input/IO errors (file not found, permission denied, empty, binary, encoding, size, I/O)
/// - `2`: Parse/Structure errors (no structure, parse failure, build errors)
/// - `3`: Validation/Config errors (schema violations, config issues)
/// - `4`: External dependency unavailable (oscal-cli not found or not functional)
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
/// use forge::error::{ForgeError, exit_code};
///
/// let err = ForgeError::FileNotFound { path: PathBuf::from("missing.md") };
/// assert_eq!(exit_code(&err), 1);
///
/// let err = ForgeError::Parse("bad syntax".into());
/// assert_eq!(exit_code(&err), 2);
///
/// let err = ForgeError::Validation("bad field".into());
/// assert_eq!(exit_code(&err), 3);
///
/// let err = ForgeError::OscalCliNotFound;
/// assert_eq!(exit_code(&err), 4);
/// ```
#[must_use]
pub fn exit_code(err: &ForgeError) -> u8 {
match err {
// Exit 1: Input/IO errors
ForgeError::FileNotFound { .. }
| ForgeError::PermissionDenied { .. }
| ForgeError::EmptyInput { .. }
| ForgeError::BinaryFile { .. }
| ForgeError::OcrNotSupported { .. }
| ForgeError::UnsupportedFormat { .. }
| ForgeError::FileTooLarge { .. }
| ForgeError::FileTooLargeWithMaxSize { .. }
| ForgeError::InvalidEncoding { .. }
| ForgeError::NotAFile { .. }
| ForgeError::Io(_)
| ForgeError::ExportUnsupportedExtension { .. }
| ForgeError::ExportNoExtension { .. }
| ForgeError::ExportInvalidOscal { .. }
| ForgeError::ExportEmptyInput { .. }
| ForgeError::InvalidArgument(_)
| ForgeError::BatchConversion(_)
| ForgeError::OscalCliExecution { .. }
| ForgeError::OscalCliTimeout { .. }
| ForgeError::ResolveInputNotJson { .. }
| ForgeError::Serialization(_)
| ForgeError::YamlSerialization { .. }
| ForgeError::DiffHasChanges
| ForgeError::DriftDetected
| ForgeError::MigrationHasChanges
| ForgeError::MappingReviewRequired
| ForgeError::LinkageActionRequired
| ForgeError::LifecycleActionRequired
| ForgeError::ApplicabilityReviewRequired
| ForgeError::FrameworkReviewRequired
| ForgeError::AuthoringActionRequired
| ForgeError::AssessmentResultsReviewRequired
| ForgeError::PoamActionRequired
| ForgeError::RoundTripFailed(_) => 1,
// Exit 2: Parse/Structure errors + usage/required-argument errors
ForgeError::MissingRequiredArgument(_)
| ForgeError::DiffError(_)
| ForgeError::MigrationError(_)
| ForgeError::SspBuild(_)
| ForgeError::SspBuildWithSource { .. }
| ForgeError::MappingBuild(_)
| ForgeError::Linkage(_)
| ForgeError::Integration(_)
| ForgeError::Lifecycle(_)
| ForgeError::ApplicabilityAnalysis(_)
| ForgeError::FrameworkImpact(_)
| ForgeError::FrameworkImpactWithSource { .. }
| ForgeError::PolicyComposition(_)
| ForgeError::Authoring(_)
| ForgeError::NoStructureDetected { .. }
| ForgeError::Parse(_)
| ForgeError::CatalogBuild(_)
| ForgeError::BackMatter(_)
| ForgeError::ComponentDefinitionBuild(_)
| ForgeError::AssessmentPlanBuild(_)
| ForgeError::AssessmentResultsBuild(_)
| ForgeError::PoamBuild(_)
| ForgeError::ParameterExtraction(_)
| ForgeError::TraceUnsupportedArtifact { .. }
| ForgeError::AmbiguousArtifact { .. }
| ForgeError::PipelineInvariant { .. }
| ForgeError::RoundTripStep { .. } => 2,
// Exit 3: Validation/Config errors
ForgeError::Validation(_) | ForgeError::Config(_) | ForgeError::SchemaValidation(_) => 3,
// Exit 4: External dependency unavailable
ForgeError::OscalCliNotFound | ForgeError::OscalCliNotFunctional { .. } => 4,
}
}
impl ForgeError {
/// Add actionable `--max-size` guidance without changing input-error semantics.
#[must_use]
pub(crate) fn with_max_size_guidance(self) -> Self {
match self {
Self::FileTooLarge { path, size_bytes, limit_bytes } => {
Self::FileTooLargeWithMaxSize { path, size_bytes, limit_bytes }
}
other => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// --- T004: New variant Display tests ---
#[test]
fn file_not_found_display() {
let err = ForgeError::FileNotFound { path: PathBuf::from("missing.md") };
assert_eq!(err.to_string(), "File not found: 'missing.md'");
}
#[test]
fn permission_denied_display() {
let err = ForgeError::PermissionDenied { path: PathBuf::from("restricted.md") };
assert_eq!(err.to_string(), "Permission denied: 'restricted.md'");
}
#[test]
fn empty_input_display() {
let err = ForgeError::EmptyInput { path: PathBuf::from("empty.md") };
assert_eq!(
err.to_string(),
"File is empty: 'empty.md' — provide a non-empty Markdown policy document"
);
}
#[test]
fn binary_file_display() {
let err = ForgeError::BinaryFile { path: PathBuf::from("image.png") };
assert_eq!(
err.to_string(),
"File appears to be binary, not a text document: 'image.png'. \
FORGE accepts UTF-8 Markdown (.md) files."
);
}
#[test]
fn no_structure_detected_display() {
let err = ForgeError::NoStructureDetected { path: PathBuf::from("flat.md") };
assert_eq!(
err.to_string(),
"No policy structure detected in 'flat.md' — expected Markdown headings (# Section) or numbered clauses"
);
}
// --- T005: exit_code tests ---
#[test]
fn missing_required_argument_display_has_no_extra_prefix() {
let err = ForgeError::MissingRequiredArgument(
"the following required arguments were not provided:\n --strategy <STRATEGY>"
.to_string(),
);
let rendered = err.to_string();
assert!(rendered.starts_with("the following required arguments"), "{rendered}");
assert!(!rendered.starts_with("error:"), "prefix duplication with main's `Error:` wrapper");
assert!(rendered.contains("--strategy"), "{rendered}");
}
#[test]
fn missing_required_argument_exit_code_is_2() {
assert_eq!(exit_code(&ForgeError::MissingRequiredArgument("test".into())), 2);
}
#[test]
fn drift_detected_has_no_message_and_exit_code_one() {
let err = ForgeError::DriftDetected;
assert_eq!(err.to_string(), "");
assert_eq!(exit_code(&err), 1);
}
#[test]
fn lifecycle_error_display_and_exit_code() {
let err = ForgeError::Lifecycle("invalid record".to_string());
assert_eq!(err.to_string(), "Policy lifecycle error: invalid record");
assert_eq!(exit_code(&err), 2);
}
#[test]
fn lifecycle_action_required_exit_code_is_one() {
assert_eq!(exit_code(&ForgeError::LifecycleActionRequired), 1);
}
#[test]
fn applicability_errors_have_stable_display_and_exit_codes() {
let analysis = ForgeError::ApplicabilityAnalysis("invalid manifest".to_string());
assert_eq!(analysis.to_string(), "Applicability analysis error: invalid manifest");
assert_eq!(exit_code(&analysis), 2);
let review = ForgeError::ApplicabilityReviewRequired;
assert_eq!(review.to_string(), "Applicability analysis requires human review");
assert_eq!(exit_code(&review), 1);
}
#[test]
fn batch_conversion_error_display() {
let err = ForgeError::BatchConversion("thread pool failed".to_string());
assert_eq!(err.to_string(), "Batch conversion error: thread pool failed");
}
#[test]
fn batch_conversion_exit_code_is_1() {
assert_eq!(exit_code(&ForgeError::BatchConversion("test".into())), 1);
}
#[test]
fn exit_code_input_io_errors_return_1() {
assert_eq!(exit_code(&ForgeError::FileNotFound { path: PathBuf::from("a") }), 1);
assert_eq!(exit_code(&ForgeError::PermissionDenied { path: PathBuf::from("a") }), 1);
assert_eq!(exit_code(&ForgeError::EmptyInput { path: PathBuf::from("a") }), 1);
assert_eq!(exit_code(&ForgeError::BinaryFile { path: PathBuf::from("a") }), 1);
assert_eq!(exit_code(&ForgeError::UnsupportedFormat { extension: "pdf".into() }), 1);
assert_eq!(
exit_code(&ForgeError::FileTooLarge {
path: PathBuf::from("a"),
size_bytes: 100,
limit_bytes: 50
}),
1
);
assert_eq!(exit_code(&ForgeError::InvalidEncoding { path: PathBuf::from("a") }), 1);
assert_eq!(exit_code(&ForgeError::NotAFile { path: PathBuf::from("a") }), 1);
let io_err = std::io::Error::other("test");
assert_eq!(exit_code(&ForgeError::Io(io_err)), 1);
assert_eq!(exit_code(&ForgeError::Serialization("s".into())), 1);
}
#[test]
fn exit_code_parse_structure_errors_return_2() {
assert_eq!(exit_code(&ForgeError::NoStructureDetected { path: PathBuf::from("a") }), 2);
assert_eq!(exit_code(&ForgeError::Parse("p".into())), 2);
assert_eq!(exit_code(&ForgeError::CatalogBuild("c".into())), 2);
assert_eq!(exit_code(&ForgeError::BackMatter("b".into())), 2);
assert_eq!(exit_code(&ForgeError::ComponentDefinitionBuild("d".into())), 2);
assert_eq!(exit_code(&ForgeError::ParameterExtraction("x".into())), 2);
}
#[test]
fn exit_code_validation_config_errors_return_3() {
assert_eq!(exit_code(&ForgeError::Validation("v".into())), 3);
assert_eq!(exit_code(&ForgeError::Config("c".into())), 3);
}
// --- Existing tests ---
#[test]
fn io_error_display() {
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
let err = ForgeError::Io(io_err);
assert_eq!(err.to_string(), "I/O error: file not found");
}
#[test]
fn parse_error_display() {
let err = ForgeError::Parse("unexpected token".to_string());
assert_eq!(err.to_string(), "Parse error: unexpected token");
}
#[test]
fn validation_error_display() {
let err = ForgeError::Validation("missing required field".to_string());
assert_eq!(err.to_string(), "Validation error: missing required field");
}
#[test]
fn config_error_display() {
let err = ForgeError::Config("invalid setting".to_string());
assert_eq!(err.to_string(), "Configuration error: invalid setting");
}
#[test]
fn unsupported_format_display() {
let err = ForgeError::UnsupportedFormat { extension: "pdf".to_string() };
assert_eq!(
err.to_string(),
"Unsupported file format '.pdf'. Only Markdown files (.md, .markdown) are supported. \
Consider converting with pandoc or markitdown."
);
}
#[test]
fn unsupported_format_empty_extension_display() {
let err = ForgeError::UnsupportedFormat { extension: String::new() };
assert_eq!(
err.to_string(),
"Unsupported file format '.'. Only Markdown files (.md, .markdown) are supported. \
Consider converting with pandoc or markitdown."
);
}
#[test]
fn file_too_large_display() {
let err = ForgeError::FileTooLarge {
path: PathBuf::from("/tmp/huge.md"),
size_bytes: 15 * 1_048_576,
limit_bytes: 10 * 1_048_576,
};
assert_eq!(err.to_string(), "File '/tmp/huge.md' is 15.0MB, exceeding the 10.0MB limit.");
}
#[test]
fn file_too_large_display_uses_gigabytes() {
let err = ForgeError::FileTooLarge {
path: PathBuf::from("/tmp/huge.md"),
size_bytes: 2 * 1_073_741_824,
limit_bytes: 1_073_741_824,
};
assert_eq!(err.to_string(), "File '/tmp/huge.md' is 2.0GB, exceeding the 1.0GB limit.");
}
#[test]
fn guided_file_too_large_preserves_input_error_exit_code() {
let err = ForgeError::FileTooLarge {
path: PathBuf::from("/tmp/huge.md"),
size_bytes: 15 * 1_048_576,
limit_bytes: 10 * 1_048_576,
}
.with_max_size_guidance();
assert_eq!(exit_code(&err), 1);
assert!(err.to_string().contains("Use --max-size"));
}
#[test]
fn invalid_encoding_display() {
let err = ForgeError::InvalidEncoding { path: PathBuf::from("/tmp/binary.md") };
assert_eq!(
err.to_string(),
"File '/tmp/binary.md' is not valid UTF-8 text. FORGE requires UTF-8 encoded Markdown files."
);
}
#[test]
fn not_a_file_display() {
let err = ForgeError::NotAFile { path: PathBuf::from("/tmp/somedir") };
assert_eq!(err.to_string(), "'/tmp/somedir' is not a regular file.");
}
#[test]
fn catalog_build_error_display() {
let err = ForgeError::CatalogBuild("missing stable_id".to_string());
assert_eq!(err.to_string(), "Catalog build error: missing stable_id");
}
#[test]
fn io_error_from_conversion() {
fn produce_io_error() -> Result<(), ForgeError> {
let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
Err(io_err)?
}
let result = produce_io_error();
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(err, ForgeError::Io(_)), "Expected ForgeError::Io, got: {err:?}");
assert_eq!(err.to_string(), "I/O error: access denied");
}
#[test]
fn back_matter_error_display() {
let err = ForgeError::BackMatter("invalid citation".to_string());
assert_eq!(err.to_string(), "Back matter error: invalid citation");
}
#[test]
fn serialization_error_display() {
let err = ForgeError::Serialization("failed to serialize".to_string());
assert_eq!(err.to_string(), "Serialization error: failed to serialize");
}
#[test]
fn assessment_plan_build_error_display() {
let err = ForgeError::AssessmentPlanBuild("metadata assembly failed".to_string());
assert_eq!(err.to_string(), "Assessment plan build error: metadata assembly failed");
}
#[test]
fn assessment_plan_build_exit_code_is_2() {
assert_eq!(exit_code(&ForgeError::AssessmentPlanBuild("test".into())), 2);
}
#[test]
fn component_definition_build_error_display() {
let err = ForgeError::ComponentDefinitionBuild("missing field".to_string());
assert_eq!(err.to_string(), "Component definition build error: missing field");
}
#[test]
fn trace_unsupported_artifact_display() {
let err = ForgeError::TraceUnsupportedArtifact {
detail: "Expected 'catalog' or 'component-definition'".to_string(),
};
assert_eq!(
err.to_string(),
"Unsupported OSCAL artifact type for tracing: Expected 'catalog' or 'component-definition'"
);
}
#[test]
fn trace_unsupported_artifact_exit_code() {
assert_eq!(
exit_code(&ForgeError::TraceUnsupportedArtifact { detail: "test".to_string() }),
2
);
}
#[test]
fn ambiguous_artifact_display() {
let err =
ForgeError::AmbiguousArtifact { detail: "catalog, component-definition".to_string() };
assert!(err.to_string().contains("Ambiguous OSCAL artifact"));
assert!(err.to_string().contains("catalog, component-definition"));
}
#[test]
fn ambiguous_artifact_exit_code_is_2() {
assert_eq!(exit_code(&ForgeError::AmbiguousArtifact { detail: "test".to_string() }), 2);
}
#[test]
fn schema_validation_error_display() {
let err = ForgeError::SchemaValidation("3 errors found".to_string());
assert_eq!(err.to_string(), "Schema validation failed: 3 errors found");
}
// --- T007: oscal-cli error variant Display tests ---
#[test]
fn oscal_cli_not_found_display() {
let err = ForgeError::OscalCliNotFound;
assert!(err.to_string().contains("oscal-cli not found"));
assert!(err.to_string().contains("https://github.com/usnistgov/oscal-cli"));
}
#[test]
fn oscal_cli_not_functional_display() {
let err = ForgeError::OscalCliNotFunctional {
path: PathBuf::from("/usr/bin/oscal-cli"),
detail: "Java runtime not found".to_string(),
};
assert!(err.to_string().contains("/usr/bin/oscal-cli"));
assert!(err.to_string().contains("not functional"));
assert!(err.to_string().contains("Java runtime not found"));
}
#[test]
fn oscal_cli_execution_display() {
let err = ForgeError::OscalCliExecution {
exit_code: Some(1),
message: "Invalid profile".to_string(),
};
let display = err.to_string();
assert!(display.contains("oscal-cli execution failed"));
assert!(display.contains("Invalid profile"));
assert!(!display.contains("stderr"), "stderr should not appear in display");
}
#[test]
#[allow(clippy::duration_suboptimal_units)]
fn oscal_cli_timeout_display() {
let err = ForgeError::OscalCliTimeout { timeout: std::time::Duration::from_secs(60) };
assert!(err.to_string().contains("timed out"));
assert!(err.to_string().contains("60"));
}
#[test]
fn resolve_input_not_json_display() {
let err = ForgeError::ResolveInputNotJson { path: PathBuf::from("profile.xml") };
assert!(err.to_string().contains("profile.xml"));
assert!(err.to_string().contains("Only .json files"));
}
// --- T008: oscal-cli exit code mapping tests ---
#[test]
fn exit_code_oscal_cli_not_found_returns_4() {
assert_eq!(exit_code(&ForgeError::OscalCliNotFound), 4);
}
#[test]
fn exit_code_oscal_cli_not_functional_returns_4() {
assert_eq!(
exit_code(&ForgeError::OscalCliNotFunctional {
path: PathBuf::from("/usr/bin/oscal-cli"),
detail: "broken".to_string(),
}),
4
);
}
#[test]
fn exit_code_oscal_cli_execution_returns_1() {
assert_eq!(
exit_code(&ForgeError::OscalCliExecution {
exit_code: Some(1),
message: "err".to_string(),
}),
1
);
}
#[test]
#[allow(clippy::duration_suboptimal_units)]
fn exit_code_oscal_cli_timeout_returns_1() {
assert_eq!(