cargo-rail 0.31.0

Cargo-native Rust workspace engine for affected CI, Rust source-surface analysis, compiler reuse, dependency coherence, exact-SHA releases, and split/sync
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
//! Error handling with contextual messages and CI-friendly exit codes.
//!
//! Exit code semantics: 0 = success, 1 = check mode found changes, 2 = error.
//! Errors carry optional help text that guides users toward resolution.

use std::fmt;
use std::io;
use std::path::PathBuf;

/// Exit codes for cargo-rail
///
/// Exit codes follow CI-friendly semantics:
/// - 0 = Success (or check passed with no changes needed)
/// - 1 = Check mode found changes would be made (not an error, but actionable)
/// - 2 = Error occurred (actual failure)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    /// Success - everything is good
    Success,
    /// Check failed - changes would be made (use in --check mode)
    CheckFailed,
    /// Error occurred (user or system error)
    Error,
    /// Custom exit code (e.g., propagated from subprocess)
    Custom(i32),
}

impl ExitCode {
    /// Convert to i32 for process exit
    pub fn as_i32(self) -> i32 {
        match self {
            ExitCode::Success => 0,
            ExitCode::CheckFailed => 1,
            ExitCode::Error => 2,
            ExitCode::Custom(code) => code,
        }
    }
}

/// Stable class of a failure that an external executor reported.
///
/// Machine output names the class in `failure_class`; each class has one recovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FailureClass {
    /// A Rust toolchain, target library, linker, Cargo, or configured wrapper is missing or unusable.
    Toolchain,
    /// A build script failed; its prerequisites belong to the package.
    BuildScript,
    /// Rust source failed to compile.
    Source,
    /// Cargo cannot load a manifest.
    Manifest,
    /// `Cargo.lock` does not match the manifests.
    Lockfile,
    /// Cargo-Rail's own compiler adapter failed inside Cargo.
    CargoRail,
    /// SIGINT or SIGTERM stopped the operation.
    Interrupted,
    /// Cargo failed for a cause Cargo-Rail does not classify.
    Cargo,
}

impl FailureClass {
    /// Stable machine name.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Toolchain => "toolchain",
            Self::BuildScript => "build_script",
            Self::Source => "source",
            Self::Manifest => "manifest",
            Self::Lockfile => "lockfile",
            Self::CargoRail => "cargo_rail",
            Self::Interrupted => "interrupted",
            Self::Cargo => "cargo",
        }
    }
}

/// One classified executor failure: a safe primary cause and one recovery section.
#[derive(Debug)]
pub struct ClassifiedFailure {
    class: FailureClass,
    message: String,
    help: String,
    detail: Option<String>,
}

impl ClassifiedFailure {
    /// Stable failure class.
    pub const fn class(&self) -> FailureClass {
        self.class
    }

    /// Bounded executor output that text output shows after the cause; machine output omits it.
    pub fn detail(&self) -> Option<&str> {
        self.detail.as_deref()
    }
}

fn joined_help(help: Option<String>, additional: String) -> String {
    match help {
        Some(help) => format!("{help}\n{additional}"),
        None => additional,
    }
}

/// Main error type for cargo-rail
#[derive(Debug)]
pub enum RailError {
    /// Configuration errors
    Config(ConfigError),

    /// Git operation errors
    Git(GitError),

    /// I/O errors
    Io(io::Error),

    /// A typed error from an external parser or subsystem.
    External {
        /// Stable operation-level description.
        message: &'static str,
        /// Native source error retained for inspection and diagnostics.
        source: Box<dyn std::error::Error + Send + Sync + 'static>,
    },

    /// Operation context around another typed Cargo-Rail error.
    Context {
        /// The operation that failed.
        context: String,
        /// The error produced by that operation.
        source: Box<RailError>,
    },

    /// Warnings already reported before an operation failed.
    WithWarnings {
        /// Warning messages retained for machine output.
        warnings: Vec<String>,
        /// The original failure, with its class, help, and exit behavior.
        source: Box<RailError>,
    },

    /// Generic error with an optional recovery hint.
    Message {
        /// Error message
        message: String,
        /// Help text to guide the user
        help: Option<String>,
    },

    /// An executor failure with a stable class and one recovery section.
    Failure(Box<ClassifiedFailure>),

    /// Check mode found pending changes (not an error, but exits with code 1)
    ///
    /// Used by --check commands to signal that changes would be made.
    /// This is not a failure, but CI should treat it as "action needed".
    CheckHasPendingChanges,

    /// Exit with specific code (no error message printed)
    ///
    /// Used for:
    /// - Propagating subprocess exit codes (e.g., cargo test failures)
    /// - Silent exits after JSON output has been written
    /// - Any case where we need a specific exit code without error output
    ExitWithCode {
        /// The exit code to use
        code: i32,
    },
}

impl RailError {
    /// Create a simple error message
    pub fn message(msg: impl Into<String>) -> Self {
        RailError::Message {
            message: msg.into(),
            help: None,
        }
    }

    /// Create an error with help text
    pub fn with_help(msg: impl Into<String>, help: impl Into<String>) -> Self {
        RailError::Message {
            message: msg.into(),
            help: Some(help.into()),
        }
    }

    /// Create a classified executor failure.
    ///
    /// `detail` is bounded executor output for text mode only; pass it only when it is safe to show.
    pub fn failure(
        class: FailureClass,
        message: impl Into<String>,
        help: impl Into<String>,
        detail: Option<String>,
    ) -> Self {
        RailError::Failure(Box::new(ClassifiedFailure {
            class,
            message: message.into(),
            help: help.into(),
            detail: detail.filter(|detail| !detail.trim().is_empty()),
        }))
    }

    /// The classified failure at the root of this error chain.
    pub fn classified(&self) -> Option<&ClassifiedFailure> {
        match self {
            RailError::Failure(failure) => Some(failure),
            RailError::Context { source, .. } | RailError::WithWarnings { source, .. } => source.classified(),
            _ => None,
        }
    }

    /// Append one more recovery line to the root error's help.
    pub(crate) fn with_additional_help(self, additional: impl Into<String>) -> Self {
        let additional = additional.into();
        match self {
            RailError::Failure(mut failure) => {
                failure.help.push('\n');
                failure.help.push_str(&additional);
                RailError::Failure(failure)
            }
            RailError::Context { context, source } => RailError::Context {
                context,
                source: Box::new(source.with_additional_help(additional)),
            },
            RailError::WithWarnings { warnings, source } => RailError::WithWarnings {
                warnings,
                source: Box::new(source.with_additional_help(additional)),
            },
            RailError::Message { message, help } => RailError::Message {
                message,
                help: Some(joined_help(help, additional)),
            },
            RailError::CheckHasPendingChanges | RailError::ExitWithCode { .. } => self,
            other => {
                let help = joined_help(other.help_message(), additional);
                RailError::with_help(other.to_string(), help)
            }
        }
    }

    /// Add context to an existing error
    pub fn context(self, ctx: impl Into<String>) -> Self {
        match self {
            RailError::CheckHasPendingChanges | RailError::ExitWithCode { .. } => self,
            source => RailError::Context {
                context: ctx.into(),
                source: Box::new(source),
            },
        }
    }

    pub(crate) fn with_warnings(self, warnings: Vec<String>) -> Self {
        if warnings.is_empty() || matches!(self, Self::CheckHasPendingChanges | Self::ExitWithCode { .. }) {
            self
        } else {
            Self::WithWarnings {
                warnings,
                source: Box::new(self),
            }
        }
    }

    fn warnings(&self) -> Vec<&str> {
        match self {
            Self::WithWarnings { warnings, source } => {
                warnings.iter().map(String::as_str).chain(source.warnings()).collect()
            }
            Self::Context { source, .. } => source.warnings(),
            _ => Vec::new(),
        }
    }

    fn external(message: &'static str, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self::External {
            message,
            source: Box::new(source),
        }
    }

    /// Get the appropriate exit code for this error
    pub fn exit_code(&self) -> ExitCode {
        match self {
            RailError::CheckHasPendingChanges => ExitCode::CheckFailed,
            RailError::ExitWithCode { code } => ExitCode::Custom(*code),
            RailError::Context { source, .. } | RailError::WithWarnings { source, .. } => source.exit_code(),
            _ => ExitCode::Error,
        }
    }

    /// Get contextual help message for this error
    pub fn help_message(&self) -> Option<String> {
        match self {
            RailError::Config(e) => e.help_message(),
            RailError::Git(e) => e.help_message(),
            RailError::Message { help, .. } => help.clone(),
            RailError::Failure(failure) => Some(failure.help.clone()),
            RailError::Context { source, .. } | RailError::WithWarnings { source, .. } => source.help_message(),
            _ => None,
        }
    }

    /// Whether this error chain ends in a broken stdout or stderr pipe.
    pub fn is_broken_pipe(&self) -> bool {
        match self {
            RailError::Io(error) => error.kind() == io::ErrorKind::BrokenPipe,
            RailError::Context { source, .. } | RailError::WithWarnings { source, .. } => source.is_broken_pipe(),
            _ => false,
        }
    }

    fn machine_parts(&self) -> (String, Option<String>) {
        let mut contexts = Vec::new();
        let mut current = self;
        loop {
            match current {
                RailError::Context { context, source } => {
                    contexts.push(context.as_str());
                    current = source;
                }
                RailError::WithWarnings { source, .. } => current = source,
                _ => break,
            }
        }

        let message = match current {
            RailError::Message { message, .. } => message.clone(),
            RailError::Failure(failure) => failure.message.clone(),
            _ => current.to_string(),
        };

        let context = (!contexts.is_empty()).then(|| contexts.join("\n"));
        (message, context)
    }
}

impl fmt::Display for RailError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RailError::Config(e) => write!(f, "{}", e),
            RailError::Git(e) => write!(f, "{}", e),
            RailError::Io(e) => write!(f, "{}", e),
            RailError::External { message, source } => write!(f, "{}: {}", message, source),
            RailError::Context { context, source } => write!(f, "{}\n{}", source, context),
            RailError::WithWarnings { source, .. } => write!(f, "{source}"),
            RailError::Message { message, .. } => write!(f, "{}", message),
            RailError::Failure(failure) => write!(f, "{}", failure.message),
            RailError::CheckHasPendingChanges => Ok(()), // Silent - CI signal
            RailError::ExitWithCode { .. } => Ok(()),    // Silent - exit code only
        }
    }
}

impl std::error::Error for RailError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            RailError::Config(e) => Some(e),
            RailError::Git(e) => Some(e),
            RailError::Io(e) => Some(e),
            RailError::External { source, .. } => Some(source.as_ref()),
            RailError::Context { source, .. } | RailError::WithWarnings { source, .. } => Some(source.as_ref()),
            _ => None,
        }
    }
}

impl From<io::Error> for RailError {
    fn from(err: io::Error) -> Self {
        RailError::Io(err)
    }
}

impl From<String> for RailError {
    fn from(msg: String) -> Self {
        RailError::message(msg)
    }
}

impl From<&str> for RailError {
    fn from(msg: &str) -> Self {
        RailError::message(msg)
    }
}

impl From<toml_edit::TomlError> for RailError {
    fn from(err: toml_edit::TomlError) -> Self {
        RailError::external("invalid TOML", err)
    }
}

impl From<cargo_metadata::Error> for RailError {
    fn from(err: cargo_metadata::Error) -> Self {
        RailError::external("cargo metadata failed", err)
    }
}

impl From<std::num::ParseIntError> for RailError {
    fn from(err: std::num::ParseIntError) -> Self {
        RailError::external("invalid number", err)
    }
}

impl From<toml_edit::de::Error> for RailError {
    fn from(err: toml_edit::de::Error) -> Self {
        RailError::external("invalid TOML", err)
    }
}

impl From<toml_edit::ser::Error> for RailError {
    fn from(err: toml_edit::ser::Error) -> Self {
        RailError::external("TOML serialization failed", err)
    }
}

impl From<serde_json::Error> for RailError {
    fn from(err: serde_json::Error) -> Self {
        RailError::external("invalid JSON", err)
    }
}

impl From<std::str::Utf8Error> for RailError {
    fn from(err: std::str::Utf8Error) -> Self {
        RailError::external("invalid UTF-8", err)
    }
}

impl From<std::string::FromUtf8Error> for RailError {
    fn from(err: std::string::FromUtf8Error) -> Self {
        RailError::external("invalid UTF-8", err)
    }
}

impl From<std::path::StripPrefixError> for RailError {
    fn from(err: std::path::StripPrefixError) -> Self {
        RailError::external("path error", err)
    }
}

impl From<std::env::VarError> for RailError {
    fn from(err: std::env::VarError) -> Self {
        RailError::external("environment variable error", err)
    }
}

/// Configuration-related errors
#[derive(Debug)]
pub enum ConfigError {
    /// rail.toml not found
    NotFound {
        /// Workspace root where config was searched
        workspace_root: PathBuf,
    },

    /// Config file exists but failed to parse
    ParseError {
        /// Path to the config file
        path: PathBuf,
        /// Parse error message
        message: String,
    },

    /// Missing required field
    MissingField {
        /// Name of the missing field
        field: String,
    },

    /// Crate not found in configuration
    CrateNotFound {
        /// Name of the crate that wasn't found
        name: String,
    },

    /// Invalid configuration value
    InvalidValue {
        /// Field name
        field: String,
        /// Error message
        message: String,
    },

    /// Invalid field configuration
    InvalidField {
        /// Field name
        field: String,
        /// Reason why it's invalid
        reason: String,
    },

    /// Invalid glob pattern
    InvalidGlobPattern {
        /// The invalid pattern
        pattern: String,
        /// Error message
        message: String,
    },
}

impl ConfigError {
    fn help_message(&self) -> Option<String> {
        match self {
            ConfigError::NotFound { .. } => Some("run 'cargo rail init' to create configuration".to_string()),
            ConfigError::ParseError { .. } => Some("check the config file syntax and fix the error".to_string()),
            ConfigError::CrateNotFound { name } => Some(format!(
                "check the '[crates.{name}]' table in rail.toml or run 'cargo rail config validate'"
            )),
            ConfigError::InvalidValue { field, .. } => Some(format!("check the '{}' field in your config file", field)),
            ConfigError::InvalidField { field, .. } => Some(format!("check the '{}' field in your config file", field)),
            ConfigError::InvalidGlobPattern { pattern, .. } => {
                Some(format!("fix or remove the invalid glob pattern: '{}'", pattern))
            }
            ConfigError::MissingField { field } => {
                Some(format!("add the required '{}' field to your config file", field))
            }
        }
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigError::NotFound { workspace_root } => {
                write!(
                    f,
                    "no configuration found in {}\n       searched: rail.toml, .rail.toml, .cargo/rail.toml, .config/rail.toml",
                    workspace_root.display()
                )
            }
            ConfigError::ParseError { path, message } => {
                write!(f, "failed to parse config file {}: {}", path.display(), message)
            }
            ConfigError::MissingField { field } => {
                write!(f, "missing required field: {}", field)
            }
            ConfigError::CrateNotFound { name } => {
                write!(f, "crate '{}' not found in configuration", name)
            }
            ConfigError::InvalidValue { field, message } => {
                write!(f, "invalid value for '{}': {}", field, message)
            }
            ConfigError::InvalidField { field, reason } => {
                write!(f, "invalid configuration for '{}': {}", field, reason)
            }
            ConfigError::InvalidGlobPattern { pattern, message } => {
                write!(f, "invalid glob pattern '{}': {}", pattern, message)
            }
        }
    }
}

impl std::error::Error for ConfigError {}

/// Git operation errors
#[derive(Debug)]
pub enum GitError {
    /// Git command failed
    CommandFailed {
        /// Command that was executed
        command: String,
        /// Standard error output
        stderr: String,
    },

    /// Repository not found
    RepoNotFound {
        /// Path where repository was expected
        path: PathBuf,
    },

    /// Commit not found
    CommitNotFound {
        /// SHA of the missing commit
        sha: String,
    },

    /// Push failed
    PushFailed {
        /// Remote name
        remote: String,
        /// Branch name
        branch: String,
        /// Failure reason
        reason: String,
    },

    /// Worktree has uncommitted changes
    DirtyWorktree {
        /// List of dirty files
        files: Vec<String>,
    },
}

impl GitError {
    fn help_message(&self) -> Option<String> {
        match self {
            GitError::PushFailed { reason, .. } => {
                if reason.contains("non-fast-forward") {
                    Some("fetch and reconcile the remote branch, then retry".to_string())
                } else if reason.contains("permission denied") || reason.contains("403") {
                    Some("check SSH key and repository permissions".to_string())
                } else {
                    None
                }
            }
            GitError::RepoNotFound { path } => Some(format!("run 'git init {}' or verify the path", path.display())),
            GitError::DirtyWorktree { .. } => Some("commit or stash changes, or use --allow-dirty".to_string()),
            _ => None,
        }
    }
}

impl fmt::Display for GitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GitError::CommandFailed { command, stderr } => {
                let stderr = stderr.trim();
                if stderr.is_empty() {
                    write!(f, "{} failed", command)
                } else {
                    write!(f, "{} failed: {}", command, stderr)
                }
            }
            GitError::RepoNotFound { path } => {
                write!(f, "not a git repository: {}", path.display())
            }
            GitError::CommitNotFound { sha } => {
                write!(f, "commit not found: {}", sha)
            }
            GitError::PushFailed { remote, branch, reason } => {
                write!(f, "push to {}/{} failed: {}", remote, branch, reason.trim())
            }
            GitError::DirtyWorktree { files } => {
                let count = files.len();
                if count <= 5 {
                    write!(f, "working tree has uncommitted changes:\n{}", files.join("\n"))
                } else {
                    write!(
                        f,
                        "working tree has uncommitted changes:\n{}\n  ... and {} more",
                        files[..5].join("\n"),
                        count - 5
                    )
                }
            }
        }
    }
}

impl std::error::Error for GitError {}

/// Result type alias for cargo-rail
pub type RailResult<T> = Result<T, RailError>;

/// Preserve both subprocess streams in an existing Git error diagnostic.
pub(crate) fn git_command_diagnostics(stdout: &[u8], stderr: &[u8]) -> String {
    let stdout = String::from_utf8_lossy(stdout);
    let stderr = String::from_utf8_lossy(stderr);
    let stdout = stdout.trim_end();
    let stderr = stderr.trim_end();
    match (stdout.is_empty(), stderr.is_empty()) {
        (true, true) => String::new(),
        (false, true) => stdout.to_string(),
        (true, false) => stderr.to_string(),
        (false, false) => format!("stdout:\n{}\nstderr:\n{}", stdout, stderr),
    }
}

/// Helper trait to add context to Results
pub trait ResultExt<T> {
    /// Add context to an error result
    fn context(self, ctx: impl Into<String>) -> RailResult<T>;

    /// Add context using a closure (lazy evaluation)
    fn with_context<F>(self, f: F) -> RailResult<T>
    where
        F: FnOnce() -> String;
}

impl<T, E> ResultExt<T> for Result<T, E>
where
    E: Into<RailError>,
{
    fn context(self, ctx: impl Into<String>) -> RailResult<T> {
        self.map_err(|e| e.into().context(ctx))
    }

    fn with_context<F>(self, f: F) -> RailResult<T>
    where
        F: FnOnce() -> String,
    {
        self.map_err(|e| e.into().context(f()))
    }
}

/// Structured JSON error for machine-readable output
#[derive(serde::Serialize)]
struct JsonError<'a> {
    error: bool,
    code: i32,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    context: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    help: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    failure_class: Option<&'static str>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    warnings: Vec<&'a str>,
}

/// Print an error to stderr with optional help text
///
/// In JSON mode, outputs a structured JSON error object instead of text.
pub fn print_error(error: &RailError) {
    // These are not errors to display - they're exit code signals
    // CheckHasPendingChanges: CI signal for "changes would be made"
    // ExitWithCode: subprocess errors or silent exits after JSON output
    if matches!(
        error,
        RailError::CheckHasPendingChanges | RailError::ExitWithCode { .. }
    ) {
        return;
    }

    if crate::output::is_json_mode() {
        print_error_json(error);
    } else {
        crate::error!("{}", error);
        if let Some(detail) = error.classified().and_then(ClassifiedFailure::detail) {
            eprintln!("{}", detail.trim_end());
        }

        if let Some(help) = error.help_message() {
            crate::help!("{}", help);
        }
    }
}

/// Print error as structured JSON to stdout
fn print_error_json(error: &RailError) {
    let (message, context) = error.machine_parts();

    let json_error = JsonError {
        error: true,
        code: error.exit_code().as_i32(),
        message,
        context,
        help: error.help_message(),
        failure_class: error.classified().map(|failure| failure.class().as_str()),
        warnings: error.warnings(),
    };

    // JSON errors go to stdout for consistent machine parsing
    // (stderr may have other output mixed in)
    if let Ok(json) = serde_json::to_string_pretty(&json_error) {
        println!("{}", json);
    } else {
        crate::error!("{}", error);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error as _;

    #[test]
    fn warning_context_preserves_failure_authority_and_silent_exits() {
        let failure = RailError::failure(FailureClass::Source, "compile failed", "fix source", None)
            .with_warnings(vec!["tag collision".into()])
            .context("release check")
            .with_additional_help("retry");
        assert_eq!(failure.warnings(), ["tag collision"]);
        assert_eq!(
            failure.machine_parts(),
            ("compile failed".into(), Some("release check".into()))
        );
        assert_eq!(failure.classified().unwrap().class(), FailureClass::Source);
        assert_eq!(failure.help_message().as_deref(), Some("fix source\nretry"));
        assert_eq!(failure.exit_code().as_i32(), 2);
        assert!(matches!(
            RailError::CheckHasPendingChanges.with_warnings(vec!["tag collision".into()]),
            RailError::CheckHasPendingChanges
        ));
        assert!(matches!(
            RailError::ExitWithCode { code: 2 }.with_warnings(vec!["tag collision".into()]),
            RailError::ExitWithCode { code: 2 }
        ));
    }

    fn rail_source(error: &RailError) -> &RailError {
        error
            .source()
            .and_then(|source| source.downcast_ref::<RailError>())
            .expect("context must retain its RailError source")
    }

    #[test]
    fn additional_help_keeps_the_failure_class_through_context() {
        let failure = RailError::failure(FailureClass::BuildScript, "cause", "recover", None)
            .context("affected views: a, b")
            .with_additional_help("resume with 'cargo rail surface --resume'");
        assert_eq!(
            failure.classified().map(ClassifiedFailure::class),
            Some(FailureClass::BuildScript)
        );
        assert_eq!(
            failure.help_message().as_deref(),
            Some("recover\nresume with 'cargo rail surface --resume'")
        );
        assert_eq!(
            failure.machine_parts(),
            ("cause".to_string(), Some("affected views: a, b".to_string()))
        );

        let message = RailError::message("cause").with_additional_help("resume");
        assert_eq!(message.help_message().as_deref(), Some("resume"));
        let typed = RailError::Io(io::Error::other("disk")).with_additional_help("resume");
        assert_eq!(
            (typed.to_string(), typed.help_message()),
            ("disk".to_string(), Some("resume".to_string()))
        );
    }

    #[test]
    fn context_retains_configuration_git_and_filesystem_sources() {
        let config = RailError::Config(ConfigError::MissingField {
            field: "release.change_dir".to_string(),
        })
        .context("validating release policy");
        let config = rail_source(&config);
        assert!(matches!(config, RailError::Config(ConfigError::MissingField { .. })));
        assert!(
            config
                .source()
                .is_some_and(|source| source.downcast_ref::<ConfigError>().is_some())
        );

        let git = RailError::Git(GitError::CommitNotFound {
            sha: "deadbeef".to_string(),
        })
        .context("resolving release base");
        let git = rail_source(&git);
        assert!(matches!(git, RailError::Git(GitError::CommitNotFound { .. })));
        assert!(
            git.source()
                .is_some_and(|source| source.downcast_ref::<GitError>().is_some())
        );

        let io = RailError::from(io::Error::new(io::ErrorKind::PermissionDenied, "denied"))
            .context("opening recovery journal");
        let io = rail_source(&io);
        assert!(matches!(io, RailError::Io(_)));
        assert!(
            io.source()
                .is_some_and(|source| source.downcast_ref::<io::Error>().is_some())
        );
    }

    #[test]
    fn external_conversions_retain_cargo_and_serialization_sources() {
        let cargo = RailError::from(cargo_metadata::Error::NoJson).context("capturing Cargo metadata");
        let cargo = rail_source(&cargo);
        assert!(matches!(cargo, RailError::External { .. }));
        assert!(
            cargo
                .source()
                .is_some_and(|source| source.downcast_ref::<cargo_metadata::Error>().is_some())
        );

        let serde = serde_json::from_str::<serde_json::Value>("{").expect_err("JSON must be invalid");
        let serde = RailError::from(serde).context("reading recovery receipt");
        let serde = rail_source(&serde);
        assert!(matches!(serde, RailError::External { .. }));
        assert!(
            serde
                .source()
                .is_some_and(|source| source.downcast_ref::<serde_json::Error>().is_some())
        );
    }

    #[test]
    fn nested_context_survives_text_machine_help_and_exit_boundaries() {
        let error = RailError::with_help("recovery failed", "resume with the recorded transaction ID")
            .context("restoring manifests")
            .context("aborting release transaction");

        assert_eq!(
            error.to_string(),
            "recovery failed\nrestoring manifests\naborting release transaction"
        );
        assert_eq!(error.exit_code(), ExitCode::Error);
        assert_eq!(
            error.help_message().as_deref(),
            Some("resume with the recorded transaction ID")
        );

        let (message, context) = error.machine_parts();
        assert_eq!(message, "recovery failed");
        assert_eq!(
            context.as_deref(),
            Some("aborting release transaction\nrestoring manifests")
        );
    }

    #[test]
    fn context_preserves_control_outcomes_and_broken_pipe_detection() {
        assert!(matches!(
            RailError::CheckHasPendingChanges.context("ignored"),
            RailError::CheckHasPendingChanges
        ));
        assert!(matches!(
            RailError::ExitWithCode { code: 42 }.context("ignored"),
            RailError::ExitWithCode { code: 42 }
        ));

        let broken_pipe =
            RailError::from(io::Error::new(io::ErrorKind::BrokenPipe, "closed")).context("writing report");
        assert!(broken_pipe.is_broken_pipe());
    }
}