-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy patherror.rs
More file actions
1335 lines (1205 loc) · 42.9 KB
/
error.rs
File metadata and controls
1335 lines (1205 loc) · 42.9 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.
use std::{
collections::BTreeMap,
env, fmt,
io::{self, IsTerminal, Write},
};
use serde::{Serialize, Serializer};
use serde_json::Value;
/// Shared CLI result type.
pub type CliResult<T = ()> = Result<T, CliError>;
pub const LIBRA_ERROR_JSON_ENV: &str = "LIBRA_ERROR_JSON";
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.
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.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CliErrorKind {
UnknownCommand,
ParseUsage,
CommandUsage,
Fatal,
Failure,
}
/// Prefix level used for rendered messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorLevel {
Fatal,
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 {
pub const fn as_i32(self) -> i32 {
self as i32
}
}
pub type ExitCode = CliExitCode;
/// Stable error categories for machine classification.
#[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 {
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.
#[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,
}
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 {
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",
}
}
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 => CliErrorCategory::Internal,
Self::WarningEmitted => CliErrorCategory::Warning,
Self::AddNothingStaged => CliErrorCategory::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,
}
}
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.",
}
}
}
/// Structured hint text rendered after the main error line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hint(String);
impl Hint {
pub fn new(text: impl Into<String>) -> Self {
Self(text.into())
}
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.
#[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 {
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.
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,
}
}
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.")
}
pub fn unknown_command(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::UnknownCommand, message)
.with_stable_code(StableErrorCode::CliUnknownCommand)
}
pub fn parse_usage(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::ParseUsage, message)
.with_stable_code(StableErrorCode::CliInvalidArguments)
}
pub fn command_usage(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::CommandUsage, message)
.with_stable_code(StableErrorCode::CliInvalidArguments)
}
pub fn fatal(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::Fatal, message)
}
pub fn failure(message: impl Into<String>) -> Self {
Self::new(CliErrorKind::Failure, message)
}
pub fn conflict(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::ConflictOperationBlocked)
}
pub fn network(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::NetworkUnavailable)
}
pub fn auth(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::AuthMissingCredentials)
}
pub fn io(message: impl Into<String>) -> Self {
Self::fatal(message).with_stable_code(StableErrorCode::IoReadFailed)
}
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.
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)
}
}
pub fn kind(&self) -> CliErrorKind {
self.kind
}
pub fn stable_code(&self) -> StableErrorCode {
self.stable_code
}
pub fn category(&self) -> CliErrorCategory {
self.stable_code.category()
}
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,
}
}
pub fn message(&self) -> &str {
&self.message
}
pub fn usage(&self) -> Option<&str> {
self.usage.as_deref()
}
pub fn hints(&self) -> &[Hint] {
&self.hints
}
pub fn details(&self) -> &BTreeMap<String, Value> {
&self.details
}
pub fn with_stable_code(mut self, stable_code: StableErrorCode) -> Self {
self.stable_code = stable_code;
self
}
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.
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
}
pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
self.details.insert(key.into(), value.into());
self
}
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
}
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()
}
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()
})
}
pub fn render(&self) -> String {
self.render_human(false)
}
pub fn render_report(&self) -> String {
format!("{}\n{}", self.render_human(true), self.render_json())
}
pub fn render_for_stderr(&self) -> String {
match stderr_render_mode() {
StderrRenderMode::Human => self.render(),
StderrRenderMode::Structured => self.render_report(),
}
}
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.
pub fn print_for_output(&self, config: &crate::utils::output::OutputConfig) {
if self.silent {
return;
}
use crate::utils::output::JsonFormat;
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();
}
}
fn severity(&self) -> &'static str {
match self.kind {
CliErrorKind::Fatal => "fatal",
CliErrorKind::UnknownCommand
| CliErrorKind::ParseUsage
| CliErrorKind::CommandUsage
| CliErrorKind::Failure => "error",
}
}
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());
}
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: ") {
crate::utils::output::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) {
crate::utils::output::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) {
return StableErrorCode::RepoCorrupt;
}
if is_repo_state_error(lower) {
return StableErrorCode::RepoStateInvalid;
}
if is_network_protocol_error(lower) {
return StableErrorCode::NetworkProtocol;
}
if is_network_unavailable_error(lower) {
return StableErrorCode::NetworkUnavailable;
}
if is_io_write_error(lower) {
return StableErrorCode::IoWriteFailed;
}
if is_io_read_error(lower) {
return StableErrorCode::IoReadFailed;
}
if is_invalid_target_error(lower) {
return StableErrorCode::CliInvalidTarget;
}
if is_usage_error(lower) {
return StableErrorCode::CliInvalidArguments;
}
StableErrorCode::InternalInvariant
}
fn contains_any(haystack: &str, needles: &[&str]) -> bool {
needles.iter().any(|needle| haystack.contains(needle))
}
fn is_usage_error(lower: &str) -> bool {
contains_any(
lower,
&[
"unexpected argument",
"invalid arguments",
"invalid argument",
"missing required",
"requires a value",
"conflicts with",
"required when",
"please specify the destination path explicitly",
"branch name is required",
"too many arguments",
"expected format",
"clean requires -f or -n",
"must use http or https",
"is not a valid url",
"one of '-t', '-s', '-p', '-e' or an --ai* flag is required",
],
)
}
fn is_invalid_target_error(lower: &str) -> bool {
contains_any(
lower,
&[
"pathspec",
"not a valid object name",
"invalid reference",
"invalid upstream",
"invalid remote branch",
"invalid object",
"invalid revision",
"ambiguous argument",
"<object> is required",
"outside of the repository",
"outside repository",
"not something we can merge",
"is not a valid stash reference",
"bad source",
"is not a directory",
"can not move directory into itself",
],
)
}
fn is_repo_not_found_error(lower: &str) -> bool {
lower.contains("not a libra repository")
|| lower.contains("does not appear to be a libra repository")
|| (lower.contains("repository '") && lower.contains("does not exist"))
}
fn is_repo_corrupt_error(lower: &str) -> bool {
contains_any(
lower,
&[
"repository database not found",
"unsupported object format",
"storage broken",
"corrupted",
"invalid tag object encoding",
"failed to load tag object",
"object storage error",
"repository broken",
],
)
}
fn is_repo_state_error(lower: &str) -> bool {
contains_any(
lower,
&[
"head is detached",
"detached head",
"no configured remote",
"no remote configured",
"no upstream specified",
"no rebase in progress",
"not on a branch",
"current branch",
"your current branch",
"no configured push destination",
"no commit at head",
"no such remote",
"refusing to merge unrelated histories",
"no names found, cannot describe anything",
"stash does not exist",
"reflog entry",
],
) || ((lower.contains("branch") || lower.contains("tag") || lower.contains("remote"))
&& lower.contains("not found"))
}
fn is_conflict_unresolved_error(lower: &str) -> bool {
contains_any(
lower,
&[
"resolve all conflicts",
"unresolved conflict",
"merge conflict",
"on conflict",
"conflicted",
"conflict:",
"conflict marker",
],
)
}
fn is_conflict_blocked_error(lower: &str) -> bool {
contains_any(
lower,
&[
"already exists",
"already in progress",
"would be overwritten",
"working tree not clean",
"unstaged changes",
"uncommitted changes",
"untracked working tree file would be overwritten",
"cannot overwrite",
"non-fast-forward",
"not possible to fast-forward",
"destination path",
"ignored by one of your",
"address already in use",
"multiple root commits",
"multiple sources moving to the same target path",
"not under version control",
],
)
}
fn is_network_unavailable_error(lower: &str) -> bool {
contains_any(
lower,
&[
"failed to discover references",
"failed to fetch objects",
"failed to send request",
"failed to send pack data",
"failed to read server response",
"host key verification failed",
"connection refused",
"timed out",
"timeout",
"tls",
"ssl",
"could not resolve host",
"network error",
"connection closed unexpectedly",
"connection reset by peer",
"remote end hung up unexpectedly",
"failed to start mcp server",
"failed to start web server",
],
)
}
fn is_network_protocol_error(lower: &str) -> bool {
contains_any(
lower,
&[
"protocol error",
"packet line",
"pkt-line",
"pkt line",
"invalid packet line",