-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy patherror.rs
More file actions
1534 lines (1403 loc) · 54.3 KB
/
error.rs
File metadata and controls
1534 lines (1403 loc) · 54.3 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
//! User-facing CLI error rendering utilities.
//!
//! The CLI uses [`CliError`] as the single user-visible error type at the
//! process boundary. Domain errors inside commands should be mapped into
//! [`CliError`] with an explicit stable code, exit code, and hint set instead
//! of printing raw internal causes to stderr.
//!
//! Contract references for maintainers and AI agents:
//! - Stable rendering and JSON envelope: `docs/development/cli-error-contract-design.md`
//! - Public stable-code catalogue: `docs/error-codes.md`
//!
//! ## Anatomy of a CliError
//!
//! Each error carries five pieces of metadata that drive rendering:
//! - **kind** ([`CliErrorKind`]) — chooses the prefix (`fatal:`, `error:`, none).
//! - **stable_code** ([`StableErrorCode`]) — machine-readable identifier (`LBR-...`)
//! that maps to a [`CliErrorCategory`] and a default exit code.
//! - **message** — the primary human-readable line.
//! - **hints** — at most two trailing `Hint:`-prefixed lines.
//! - **usage** / **details** — optional usage block and structured key/value details.
//!
//! ## Rendering modes
//!
//! - `render` — single-line prefixed output for human consumption.
//! - `render_json` — structured envelope used in `--json` mode and when
//! `LIBRA_ERROR_JSON=1` forces structured stderr.
//! - `render_report` — combines both, emitting the human line and a trailing JSON
//! payload so log scrapers can parse the same line a developer is reading.
//!
//! ## Exit-code resolution
//!
//! By default the exit code follows the Git convention: 128 for fatal runtime
//! errors and 129 for usage errors. Setting `LIBRA_FINE_EXIT_CODES=1` switches to
//! the legacy 2..=9 category codes for backward compatibility with old scripts.
//! `with_exit_code` overrides everything else, used when matching Git's quirky
//! per-command codes (e.g. `git config --get` returning 1).
use std::{
collections::BTreeMap,
env, fmt,
io::{self, IsTerminal, Write},
};
use serde::{Serialize, Serializer};
use serde_json::Value;
use crate::utils::output::{JsonFormat, OutputConfig, record_warning};
/// Shared CLI result type used by every command handler and dispatcher.
pub type CliResult<T = ()> = Result<T, CliError>;
/// Env var that forces structured (JSON) error output on stderr regardless of
/// whether stderr is a TTY. Recognised values: `1`, `true`, `yes`, `on`, `always`.
pub const LIBRA_ERROR_JSON_ENV: &str = "LIBRA_ERROR_JSON";
/// Env var that switches exit codes from the Git-style 128/129 to the legacy
/// fine-grained 2..=9 category codes. Recognised values: `1`, `true`, `yes`, `on`.
pub const LIBRA_FINE_EXIT_CODES_ENV: &str = "LIBRA_FINE_EXIT_CODES";
/// Returns `true` when `LIBRA_FINE_EXIT_CODES=1` is set, enabling backward-
/// compatible category-specific exit codes (2–9) instead of the default
/// Git-standard 128/129.
///
/// Boundary conditions:
/// - Only recognises a small allowlist of truthy strings; an unknown value (e.g.
/// `LIBRA_FINE_EXIT_CODES=yesplease`) leaves the flag off rather than guessing.
fn fine_exit_codes_enabled() -> bool {
matches!(
env::var(LIBRA_FINE_EXIT_CODES_ENV).as_deref(),
Ok("1" | "true" | "yes" | "on")
)
}
/// High-level CLI error classes used to decide prefixes and parse semantics.
///
/// Variants do not encode severity directly — see [`ErrorLevel`] for that — but
/// they do drive how `render` chooses the leading prefix string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CliErrorKind {
/// `libra foo` where `foo` is not a known subcommand. Renders without prefix.
UnknownCommand,
/// Top-level argv parse failure (clap-detected). Renders with `error:` prefix.
ParseUsage,
/// Subcommand-specific usage failure (e.g. mutually exclusive flags).
CommandUsage,
/// Hard runtime error: rendered with `fatal:` prefix.
Fatal,
/// Soft runtime error: rendered with `error:` prefix.
Failure,
}
/// Prefix level used for rendered messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorLevel {
/// Maps to `fatal:` prefix in human output.
Fatal,
/// Maps to `error:` prefix in human output.
Error,
}
/// Coarse process exit codes for shell and CI automation.
///
/// Values follow the Git convention: **128** for fatal runtime errors and
/// **129** for usage / invalid-argument errors, so existing scripts that
/// branch on Git's exit codes work unchanged with Libra.
///
/// The finer-grained failure category is still available through the
/// [`StableErrorCode`] carried in the structured JSON report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[repr(i32)]
pub enum CliExitCode {
/// Command succeeded but emitted warnings (`--exit-code-on-warning`).
Warning = 9,
/// Fatal runtime error (repo, conflict, network, auth, I/O, internal).
Fatal = 128,
/// CLI usage or invalid-target error.
Usage = 129,
}
impl CliExitCode {
/// Convert to the platform-native `i32` exit code accepted by `process::exit`.
pub const fn as_i32(self) -> i32 {
self as i32
}
}
/// Backward-compatible alias kept for older call sites.
pub type ExitCode = CliExitCode;
/// Stable error categories for machine classification.
///
/// Each `StableErrorCode` belongs to exactly one category; agents and CI scripts
/// can use the category to make broad routing decisions without tracking every
/// individual code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CliErrorCategory {
Cli,
Repo,
Conflict,
Network,
Auth,
Io,
Internal,
/// Command succeeded but emitted warnings; used with `--exit-code-on-warning`.
Warning,
}
impl CliErrorCategory {
/// Stable lowercase string used in JSON error envelopes (e.g. `"repo"`,
/// `"network"`). Keep in sync with the `serde(rename_all = "snake_case")`
/// attribute so manual string matching does not drift from the JSON output.
pub const fn as_str(self) -> &'static str {
match self {
Self::Cli => "cli",
Self::Repo => "repo",
Self::Conflict => "conflict",
Self::Network => "network",
Self::Auth => "auth",
Self::Io => "io",
Self::Internal => "internal",
Self::Warning => "warning",
}
}
}
/// Stable Libra CLI error codes for agents and structured tooling.
///
/// Each variant maps to a fixed `LBR-*` string ID rendered in JSON output and
/// `Error-Code:` headers. Adding a new code requires:
/// 1. Adding the variant here and a unique `LBR-*` ID in `as_str`.
/// 2. Adding the variant -> `CliErrorCategory` mapping in `category`.
/// 3. Adding a human-readable description in `description` (rendered by
/// `libra help error-codes`).
/// 4. Updating `docs/error-codes.md` and checking
/// `docs/development/cli-error-contract-design.md` for contract impact.
///
/// Removing or renaming an existing code is a breaking change for downstream
/// agents and CI scripts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StableErrorCode {
CliUnknownCommand,
CliInvalidArguments,
CliInvalidTarget,
RepoNotFound,
RepoCorrupt,
RepoStateInvalid,
ConflictUnresolved,
ConflictOperationBlocked,
NetworkUnavailable,
NetworkProtocol,
AuthMissingCredentials,
AuthPermissionDenied,
IoReadFailed,
IoWriteFailed,
InternalInvariant,
/// Command succeeded but emitted warnings (`--exit-code-on-warning`).
WarningEmitted,
/// All pathspecs matched ignored files; nothing was staged.
AddNothingStaged,
/// Feature or operation is not yet supported.
Unsupported,
}
impl Serialize for StableErrorCode {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl StableErrorCode {
/// Render the code as its stable `LBR-*` identifier. Documented in
/// `docs/error-codes.md` and treated as part of the public CLI contract.
pub const fn as_str(self) -> &'static str {
match self {
Self::CliUnknownCommand => "LBR-CLI-001",
Self::CliInvalidArguments => "LBR-CLI-002",
Self::CliInvalidTarget => "LBR-CLI-003",
Self::RepoNotFound => "LBR-REPO-001",
Self::RepoCorrupt => "LBR-REPO-002",
Self::RepoStateInvalid => "LBR-REPO-003",
Self::ConflictUnresolved => "LBR-CONFLICT-001",
Self::ConflictOperationBlocked => "LBR-CONFLICT-002",
Self::NetworkUnavailable => "LBR-NET-001",
Self::NetworkProtocol => "LBR-NET-002",
Self::AuthMissingCredentials => "LBR-AUTH-001",
Self::AuthPermissionDenied => "LBR-AUTH-002",
Self::IoReadFailed => "LBR-IO-001",
Self::IoWriteFailed => "LBR-IO-002",
Self::InternalInvariant => "LBR-INTERNAL-001",
Self::WarningEmitted => "LBR-WARN-001",
Self::AddNothingStaged => "LBR-ADD-001",
Self::Unsupported => "LBR-UNSUPPORTED-001",
}
}
/// Group this code under one of the broad categories used for shell
/// scripting and structured automation.
pub const fn category(self) -> CliErrorCategory {
match self {
Self::CliUnknownCommand | Self::CliInvalidArguments | Self::CliInvalidTarget => {
CliErrorCategory::Cli
}
Self::RepoNotFound | Self::RepoCorrupt | Self::RepoStateInvalid => {
CliErrorCategory::Repo
}
Self::ConflictUnresolved | Self::ConflictOperationBlocked => CliErrorCategory::Conflict,
Self::NetworkUnavailable | Self::NetworkProtocol => CliErrorCategory::Network,
Self::AuthMissingCredentials | Self::AuthPermissionDenied => CliErrorCategory::Auth,
Self::IoReadFailed | Self::IoWriteFailed => CliErrorCategory::Io,
Self::InternalInvariant | Self::Unsupported => CliErrorCategory::Internal,
Self::WarningEmitted => CliErrorCategory::Warning,
Self::AddNothingStaged => CliErrorCategory::Cli,
}
}
/// Default coarse exit code for this stable code, before any per-error
/// override is applied. `AddNothingStaged` is special-cased back to
/// `Fatal` (128) to match Git's behaviour for `git add` with only ignored
/// paths even though the category is `Cli`.
pub const fn exit_code(self) -> CliExitCode {
match self {
// AddNothingStaged falls in the Cli category (which normally
// maps to Usage/129), but "nothing to add" is a runtime
// condition, not a CLI usage error — exit 128 matches Git's
// behavior for `git add` with only ignored paths.
Self::AddNothingStaged => CliExitCode::Fatal,
_ => match self.category() {
CliErrorCategory::Cli => CliExitCode::Usage,
CliErrorCategory::Warning => CliExitCode::Warning,
_ => CliExitCode::Fatal,
},
}
}
/// Fine-grained exit code for backward compatibility.
///
/// Returns the category-specific exit code (2–9) used prior to the
/// Git-standard 128/129 migration. Activated by setting
/// `LIBRA_FINE_EXIT_CODES=1`.
pub const fn fine_exit_code(self) -> i32 {
match self.category() {
CliErrorCategory::Cli => 2,
CliErrorCategory::Repo => 3,
CliErrorCategory::Conflict => 4,
CliErrorCategory::Network => 5,
CliErrorCategory::Auth => 6,
CliErrorCategory::Io => 7,
CliErrorCategory::Internal => 8,
CliErrorCategory::Warning => 9,
}
}
/// Long-form description rendered by `libra help error-codes`.
/// Intended for direct human consumption — should be a complete sentence.
pub const fn description(self) -> &'static str {
match self {
Self::CliUnknownCommand => "Unknown command or unsupported top-level invocation.",
Self::CliInvalidArguments => "Invalid or missing CLI arguments.",
Self::CliInvalidTarget => "Invalid object, revision, pathspec, or command target.",
Self::RepoNotFound => "Current directory is not a Libra repository.",
Self::RepoCorrupt => "Repository metadata is missing, incompatible, or corrupt.",
Self::RepoStateInvalid => {
"Repository state prevents the requested operation from proceeding."
}
Self::ConflictUnresolved => {
"Operation stopped because unresolved conflicts are present."
}
Self::ConflictOperationBlocked => {
"Operation was blocked to avoid overwriting local or remote state."
}
Self::NetworkUnavailable => "Remote transport, connectivity, or reachability failure.",
Self::NetworkProtocol => "Remote protocol, sideband, or pack negotiation failure.",
Self::AuthMissingCredentials => {
"Required credentials, identity, key material, or tokens are missing."
}
Self::AuthPermissionDenied => {
"Credentials were present but the operation is not permitted."
}
Self::IoReadFailed => "Filesystem or storage read failed.",
Self::IoWriteFailed => "Filesystem or storage write failed.",
Self::InternalInvariant => {
"Unexpected internal failure or broken invariant. This should be reported."
}
Self::WarningEmitted => {
"Command completed successfully but emitted warnings (--exit-code-on-warning)."
}
Self::AddNothingStaged => "All specified paths are ignored; nothing was staged.",
Self::Unsupported => "Feature or operation is not yet supported.",
}
}
}
/// Structured hint text rendered after the main error line.
///
/// Hints are added via [`CliError::with_hint`] / [`CliError::with_priority_hint`].
/// The renderer prefixes every line with `Hint:` (Libra style — not the lowercase
/// `hint:` used by Git).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hint(String);
impl Hint {
/// Construct a hint from any string-like value. The text is stored verbatim;
/// any prefix stripping happens later in `with_hint`.
pub fn new(text: impl Into<String>) -> Self {
Self(text.into())
}
/// Borrow the hint text without the `Hint:` rendering prefix.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&str> for Hint {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl From<String> for Hint {
fn from(value: String) -> Self {
Self::new(value)
}
}
/// User-facing CLI error with explicit rendering and exit semantics.
///
/// Build via the family of constructors (`fatal`, `failure`, `repo_not_found`, ...)
/// then chain with `with_hint`, `with_usage`, `with_detail`, etc. The resulting
/// error knows how to render itself for both humans and machines.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliError {
kind: CliErrorKind,
stable_code: StableErrorCode,
message: String,
hints: Vec<Hint>,
usage: Option<String>,
details: BTreeMap<String, Value>,
/// Optional override for the process exit code. When set, this takes
/// precedence over the code derived from [`StableErrorCode`].
exit_code_override: Option<i32>,
/// When true, `print_for_output` / `print_stderr` emit nothing.
/// Used for exit-code-only signalling (e.g. `status --exit-code`).
silent: bool,
}
impl CliError {
/// Internal constructor used by every public builder.
///
/// Boundary conditions:
/// - Runs the legacy substring inference (`infer_stable_error_code`) so callers
/// that pre-date the structured-code era still get a reasonable default.
/// Callers should override with `with_stable_code` whenever the precise code
/// is known.
fn new(kind: CliErrorKind, message: impl Into<String>) -> Self {
let message = message.into();
let stable_code = infer_stable_error_code(kind, &message);
Self {
kind,
stable_code,
message,
hints: Vec::new(),
usage: None,
details: BTreeMap::new(),
exit_code_override: None,
silent: false,
}
}
/// Create a silent exit error that only sets the process exit code
/// without printing anything to stderr. Used for `--exit-code` style
/// flags where a non-zero exit is a signal, not an error.
///
/// Boundary conditions:
/// - `print_stderr` and `print_for_output` become no-ops on silent errors.
/// - The `kind` is set to `Failure` and the `stable_code` to
/// `InternalInvariant`; these are unused while silent but become visible if
/// a caller accidentally non-silently renders the error.
pub fn silent_exit(code: i32) -> Self {
Self {
kind: CliErrorKind::Failure,
stable_code: StableErrorCode::InternalInvariant,
message: String::new(),
hints: Vec::new(),
usage: None,
details: BTreeMap::new(),
exit_code_override: Some(code),
silent: true,
}
}
/// Canonical "not a Libra repository" error with the standard hint suggesting
/// `libra init`. Centralising it here keeps the wording identical across every
/// preflight site.
pub fn repo_not_found() -> Self {
Self::fatal("not a libra repository (or any of the parent directories): .libra")
.with_stable_code(StableErrorCode::RepoNotFound)
.with_hint("run 'libra init' to create a repository in the current directory.")
}
/// Top-level "no such subcommand" error. Rendered without a prefix so the
/// output matches Git's `'wat' is not a libra command.` style verbatim.
pub fn unknown_command(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::UnknownCommand, message)
.with_stable_code(StableErrorCode::CliUnknownCommand)
}
/// Argv parse error detected by clap (root-level). Renders with the `error:`
/// prefix. Use this for failures that occur before any subcommand handler runs.
pub fn parse_usage(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::ParseUsage, message)
.with_stable_code(StableErrorCode::CliInvalidArguments)
}
/// Subcommand-level usage error (e.g. mutually exclusive flags). Same `error:`
/// prefix as `parse_usage` but classifies as `CommandUsage` for downstream
/// reporting.
pub fn command_usage(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::CommandUsage, message)
.with_stable_code(StableErrorCode::CliInvalidArguments)
}
/// Hard runtime error rendered with `fatal:` prefix. Default exit code 128.
pub fn fatal(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::Fatal, message)
}
/// Soft runtime error rendered with `error:` prefix. Default exit code 128.
pub fn failure(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::Failure, message)
}
/// Conflict-class fatal with stable code `ConflictOperationBlocked`.
pub fn conflict(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::ConflictOperationBlocked)
}
/// Network-class fatal with stable code `NetworkUnavailable`.
pub fn network(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::NetworkUnavailable)
}
/// Auth-class fatal with stable code `AuthMissingCredentials`.
pub fn auth(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::AuthMissingCredentials)
}
/// IO-class fatal with stable code `IoReadFailed`. For write failures, prefer
/// `CliError::fatal(...).with_stable_code(StableErrorCode::IoWriteFailed)`.
pub fn io(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::IoReadFailed)
}
/// Internal-invariant fatal. Prefer this for "should not happen" code paths so
/// users see a clear "this is a Libra bug" categorisation.
pub fn internal(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::InternalInvariant)
}
/// Convert a legacy prefixed error string (e.g. `"fatal: ..."` or
/// `"error: ..."`) into a structured [`CliError`].
///
/// This is the shared bridge for commands whose inner implementation still
/// returns `Result<(), String>` with a human-readable prefix.
///
/// New command code should prefer setting [`StableErrorCode`] explicitly
/// with [`CliError::with_stable_code`] instead of depending on message
/// substring inference.
///
/// Boundary conditions:
/// - `usage:` prefix is converted into a `CommandUsage` error and the original
/// prefix is preserved in the usage block (prefix `usage:` retained for
/// round-trip compatibility).
/// - `warning:` prefix is folded into a `Failure` error so the message still
/// shows up; callers who want true warning behaviour should use
/// [`emit_warning`] instead.
/// - Any other input falls back to `Failure` with the trimmed message.
pub fn from_legacy_string(msg: impl Into<String>) -> Self {
let raw = msg.into();
let trimmed = raw.trim().to_string();
if let Some(rest) = trimmed.strip_prefix("fatal: ") {
Self::fatal(rest.to_string())
} else if let Some(rest) = trimmed.strip_prefix("error: ") {
Self::failure(rest.to_string())
} else if let Some(rest) = trimmed.strip_prefix("warning: ") {
Self::failure(rest.to_string())
} else if let Some(rest) = trimmed.strip_prefix("usage: ") {
Self::command_usage("invalid arguments").with_usage(format!("usage: {rest}"))
} else {
Self::failure(trimmed)
}
}
/// Borrow the [`CliErrorKind`] used to drive prefix selection.
pub fn kind(&self) -> CliErrorKind {
self.kind
}
/// Borrow the stable machine-readable error code.
pub fn stable_code(&self) -> StableErrorCode {
self.stable_code
}
/// Convenience: derive the broad [`CliErrorCategory`] from `stable_code`.
pub fn category(&self) -> CliErrorCategory {
self.stable_code.category()
}
/// Map kind to the human-facing severity level rendered as `fatal:` or
/// `error:`. Returns `None` for `UnknownCommand`, which renders without a
/// prefix.
pub fn level(&self) -> Option<ErrorLevel> {
match self.kind {
CliErrorKind::Fatal => Some(ErrorLevel::Fatal),
CliErrorKind::ParseUsage | CliErrorKind::CommandUsage | CliErrorKind::Failure => {
Some(ErrorLevel::Error)
}
CliErrorKind::UnknownCommand => None,
}
}
/// Borrow the primary error message.
pub fn message(&self) -> &str {
&self.message
}
/// Borrow the optional usage block displayed after the message.
pub fn usage(&self) -> Option<&str> {
self.usage.as_deref()
}
/// Borrow the (at most two) accumulated hints.
pub fn hints(&self) -> &[Hint] {
&self.hints
}
/// Borrow the structured details map (rendered into the JSON envelope).
pub fn details(&self) -> &BTreeMap<String, Value> {
&self.details
}
/// Override the stable code that was inferred from the message.
///
/// When this is called from a `From<DomainError> for CliError` mapping,
/// prefer adding a short nearby comment explaining why the selected code
/// represents the recovery intent. For example, a partially initialized
/// repository should usually map to [`StableErrorCode::RepoStateInvalid`],
/// while a missing input path should usually map to
/// [`StableErrorCode::IoReadFailed`].
pub fn with_stable_code(mut self, stable_code: StableErrorCode) -> Self {
self.stable_code = stable_code;
self
}
/// Append a hint to the error.
///
/// Boundary conditions:
/// - The third hint and beyond are silently dropped — the renderer caps
/// visible hints at two for readability.
/// - Any leading `Hint:` / `hint:` prefix on the input is stripped, so callers
/// who copy text from existing rendered errors are not double-prefixed.
/// - Empty / whitespace-only hints are ignored.
pub fn with_hint(mut self, hint: impl Into<Hint>) -> Self {
if self.hints.len() >= 2 {
return self;
}
let hint = normalize_hint_text(hint.into().0);
if hint.trim().is_empty() {
return self;
}
self.hints.push(Hint::new(hint));
self
}
/// Insert a high-priority hint at the front. If the hint budget (2) is
/// already full, the *last* (lowest-priority) hint is dropped to make room.
///
/// Boundary conditions:
/// - Empty / whitespace hints are still ignored.
/// - Used by repository-conversion preflight to surface a more relevant hint
/// ahead of the generic "run libra init" suggestion.
pub fn with_priority_hint(mut self, hint: impl Into<Hint>) -> Self {
let hint = normalize_hint_text(hint.into().0);
if hint.trim().is_empty() {
return self;
}
if self.hints.len() >= 2 {
self.hints.pop(); // drop lowest-priority
}
self.hints.insert(0, Hint::new(hint));
self
}
/// Attach a structured key/value detail. Detail keys are stable enough to be
/// matched against by automation; treat them as part of the public contract
/// once a release ships them.
pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.details.insert(key.into(), value.into());
self
}
/// Set the usage block. Empty / whitespace-only input is ignored so callers
/// can pipe through clap output without double-checking for emptiness.
pub fn with_usage(mut self, usage: impl Into<String>) -> Self {
let usage = usage.into();
if !usage.trim().is_empty() {
self.usage = Some(usage);
}
self
}
/// Override the process exit code for this error instance.
///
/// When set, this takes precedence over both the standard
/// [`StableErrorCode`]-derived code and the fine-grained exit code.
/// Use sparingly for cases where Git-compatible exit codes differ from
/// the Libra category mapping (e.g. `git config --get` returns 1 when
/// a key is not found).
pub fn with_exit_code(mut self, code: i32) -> Self {
self.exit_code_override = Some(code);
self
}
/// Resolve the final exit code in the order: explicit override > legacy
/// fine-grained codes (when env var is set) > coarse Git-style code.
pub fn exit_code(&self) -> i32 {
if let Some(code) = self.exit_code_override {
return code;
}
if fine_exit_codes_enabled() {
return self.stable_code.fine_exit_code();
}
self.stable_code.exit_code().as_i32()
}
/// Render the error as the structured JSON envelope.
///
/// Boundary conditions:
/// - Falls back to a hard-coded internal-invariant payload if `serde_json`
/// serialisation fails. This keeps `--json` mode honest even on the
/// pathological case of a bad `details` value.
pub fn render_json(&self) -> String {
// INVARIANT: `CliErrorReport` contains only serializable enums, strings,
// integers, vectors, maps, and `serde_json::Value`. Serialization is
// expected to succeed; this fallback only guards against an unexpected
// future regression in the report type itself.
serde_json::to_string(&self.report()).unwrap_or_else(|_| {
"{\"ok\":false,\"error_code\":\"LBR-INTERNAL-001\",\"category\":\"internal\",\
\"exit_code\":128,\"severity\":\"fatal\",\"message\":\"failed to serialize CLI error report\"}"
.to_string()
})
}
/// Render a single human-readable string (no `Error-Code:` header, no JSON).
pub fn render(&self) -> String {
self.render_human(false)
}
/// Render the human form *and* the JSON envelope on a trailing line.
/// Used when stderr is not a TTY so log scrapers can parse the JSON line.
pub fn render_report(&self) -> String {
format!("{}\n{}", self.render_human(true), self.render_json())
}
/// Pick the right renderer for the current stderr mode (human / structured)
/// based on env var override and TTY detection.
pub fn render_for_stderr(&self) -> String {
match stderr_render_mode() {
StderrRenderMode::Human => self.render(),
StderrRenderMode::Structured => self.render_report(),
}
}
/// Print the error to stderr with the appropriate renderer. Silent errors
/// (constructed with [`Self::silent_exit`]) are skipped.
pub fn print_stderr(&self) {
if self.silent {
return;
}
eprintln!("{}", self.render_for_stderr());
}
/// Print the error according to the global output configuration.
///
/// When JSON output is active, the error is rendered as a JSON envelope to
/// **stderr** so stdout remains reserved for successful command data.
///
/// Boundary conditions:
/// - In `JsonFormat::Pretty`, the rendered JSON is re-parsed into a
/// `serde_json::Value` so the output is human-readable. If that re-parse
/// fails, falls back to the original compact line.
/// - Compact / NDJSON output writes a single line plus a newline, matching
/// the format used by successful command output.
pub fn print_for_output(&self, config: &OutputConfig) {
if self.silent {
return;
}
if let Some(fmt) = config.json_format {
let json = self.render_json();
let stderr = std::io::stderr();
let mut writer = stderr.lock();
match fmt {
JsonFormat::Pretty => {
// Re-parse and pretty-print the JSON.
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&json) {
let _ = serde_json::to_writer_pretty(&mut writer, &value);
let _ = writeln!(writer);
} else {
let _ = writeln!(writer, "{json}");
}
}
JsonFormat::Compact | JsonFormat::Ndjson => {
let _ = writeln!(writer, "{json}");
}
}
} else {
self.print_stderr();
}
}
/// Rendered severity string used by JSON envelopes. Stable across releases.
fn severity(&self) -> &'static str {
match self.kind {
CliErrorKind::Fatal => "fatal",
CliErrorKind::UnknownCommand
| CliErrorKind::ParseUsage
| CliErrorKind::CommandUsage
| CliErrorKind::Failure => "error",
}
}
/// Materialise the error into the serde-friendly `CliErrorReport` snapshot.
fn report(&self) -> CliErrorReport {
CliErrorReport {
ok: false,
error_code: self.stable_code,
category: self.category(),
exit_code: self.exit_code(),
severity: self.severity(),
message: self.message.clone(),
usage: self.usage.clone(),
hints: self
.hints
.iter()
.map(|hint| hint.as_str().to_string())
.collect(),
details: self.details.clone(),
}
}
fn render_human(&self, include_error_code: bool) -> String {
let mut lines = Vec::new();
match self.kind {
CliErrorKind::UnknownCommand => lines.push(self.message.clone()),
CliErrorKind::ParseUsage | CliErrorKind::CommandUsage | CliErrorKind::Failure => {
lines.push(format!("error: {}", self.message));
}
CliErrorKind::Fatal => lines.push(format!("fatal: {}", self.message)),
}
if include_error_code {
lines.push(format!("Error-Code: {}", self.stable_code.as_str()));
}
if let Some(usage) = &self.usage
&& !usage.trim().is_empty()
{
lines.push(usage.trim_end().to_string());
}
if !self.hints.is_empty() {
lines.push(String::new());
for hint in &self.hints {
lines.extend(render_hint(hint.as_str()));
}
}
lines.join("\n")
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct CliErrorReport {
ok: bool,
error_code: StableErrorCode,
category: CliErrorCategory,
exit_code: i32,
severity: &'static str,
message: String,
#[serde(skip_serializing_if = "Option::is_none")]
usage: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
hints: Vec<String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
details: BTreeMap<String, Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StructuredStderrMode {
Auto,
Always,
}
impl StructuredStderrMode {
fn from_env() -> Self {
match env::var(LIBRA_ERROR_JSON_ENV) {
Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" | "always" => Self::Always,
_ => Self::Auto,
},
Err(_) => Self::Auto,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StderrRenderMode {
Human,
Structured,
}
fn stderr_render_mode() -> StderrRenderMode {
match StructuredStderrMode::from_env() {
StructuredStderrMode::Always => StderrRenderMode::Structured,
StructuredStderrMode::Auto => {
if io::stderr().is_terminal() {
StderrRenderMode::Human
} else {
StderrRenderMode::Structured
}
}
}
}
fn normalize_hint_text(text: String) -> String {
text.lines()
.map(strip_hint_prefix)
.collect::<Vec<_>>()
.join("\n")
}
fn strip_hint_prefix(line: &str) -> String {
let trimmed = line.trim_start();
if let Some(stripped) = trimmed.strip_prefix("Hint:") {
return stripped.trim_start().to_string();
}
if let Some(stripped) = trimmed.strip_prefix("hint:") {
return stripped.trim_start().to_string();
}
line.to_string()
}
// NOTE: We use "Hint:" (capital H) rather than Git's lowercase "hint:". This is
// a deliberate stylistic choice for Libra — not a bug.
fn render_hint(text: &str) -> Vec<String> {
text.lines().map(|line| format!("Hint: {}", line)).collect()
}
impl fmt::Display for CliError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.render())
}
}
impl std::error::Error for CliError {}
/// Emit a legacy CLI message to stderr, converting fatal/error lines into the
/// structured [`CliError`] report format.
pub fn emit_legacy_stderr(message: impl Into<String>) {
let message = message.into();
if let Some(text) = message.trim().strip_prefix("warning: ") {
record_warning();
eprintln!("warning: {}", text);
return;
}
CliError::from_legacy_string(message).print_stderr();
}
/// Emit a legacy CLI message to stderr and terminate the process with the
/// inferred exit code.
pub fn exit_with_legacy_stderr(message: impl Into<String>) -> ! {
let err = CliError::from_legacy_string(message.into());
err.print_stderr();
std::process::exit(err.exit_code());
}
/// Print a user-facing error to stderr.
///
/// New command code should prefer returning [`CliError`] instead of printing
/// directly. This macro remains for legacy command paths during migration.
#[macro_export]
macro_rules! cli_error {
($prefix:expr => $err:expr) => {{
$crate::utils::error::emit_legacy_stderr(format!("{}: {}", $prefix, $err));
}};
($err:expr, $($arg:tt)+) => {{
let prefix = format!($($arg)+);
$crate::utils::error::emit_legacy_stderr(format!("{prefix}: {}", $err));
}};
}
/// Emit a warning to stderr and record it for `--exit-code-on-warning`.
///
/// Use this instead of raw `eprintln!("warning: ...")` so that the
/// global warning tracker is updated and the `--exit-code-on-warning` flag
/// works correctly.
pub fn emit_warning(message: impl std::fmt::Display) {
record_warning();
eprintln!("warning: {message}");
}
/// Transitional best-effort classifier for legacy string-only error paths.
///
/// New command implementations should set [`StableErrorCode`] explicitly with
/// [`CliError::with_stable_code`] instead of relying on these message
/// heuristics.
fn infer_stable_error_code(kind: CliErrorKind, message: &str) -> StableErrorCode {
let lower = message.to_ascii_lowercase();
match kind {
CliErrorKind::UnknownCommand => StableErrorCode::CliUnknownCommand,
CliErrorKind::ParseUsage | CliErrorKind::CommandUsage => {
if is_invalid_target_error(&lower) {
StableErrorCode::CliInvalidTarget
} else {
StableErrorCode::CliInvalidArguments
}
}
CliErrorKind::Fatal | CliErrorKind::Failure => infer_runtime_error_code(&lower),
}
}
fn infer_runtime_error_code(lower: &str) -> StableErrorCode {
if is_internal_error(lower) {
return StableErrorCode::InternalInvariant;
}
if is_auth_permission_error(lower) {
return StableErrorCode::AuthPermissionDenied;
}
if is_auth_missing_error(lower) {
return StableErrorCode::AuthMissingCredentials;
}
if is_conflict_unresolved_error(lower) {
return StableErrorCode::ConflictUnresolved;
}
if is_conflict_blocked_error(lower) {
return StableErrorCode::ConflictOperationBlocked;
}
if is_repo_not_found_error(lower) {
return StableErrorCode::RepoNotFound;
}
if is_repo_corrupt_error(lower) {