This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
config.rs
1222 lines (1088 loc) · 39.3 KB
/
config.rs
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
//! Configuration options for customizing the behavior of the provided panic
//! and error reporting hooks
use crate::{
section::PanicMessage,
writers::{EnvSection, WriterExt},
};
use eyre::WrapErr;
use fmt::Display;
use indenter::{indented, Format};
use owo_colors::{style, OwoColorize, Style};
use std::env;
use std::fmt::Write as _;
use std::{fmt, path::PathBuf, sync::Arc};
#[derive(Debug)]
struct InstallError;
impl fmt::Display for InstallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("could not install the BacktracePrinter as another was already installed")
}
}
impl std::error::Error for InstallError {}
#[derive(Debug)]
struct InstallThemeError;
impl fmt::Display for InstallThemeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("could not set the provided `Theme` globally as another was already set")
}
}
impl std::error::Error for InstallThemeError {}
#[derive(Debug)]
struct InstallColorSpantraceThemeError;
impl fmt::Display for InstallColorSpantraceThemeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("could not set the provided `Theme` via `color_spantrace::set_theme` globally as another was already set")
}
}
impl std::error::Error for InstallColorSpantraceThemeError {}
/// A struct that represents a theme that is used by `color_eyre`
#[derive(Debug, Copy, Clone, Default)]
pub struct Theme {
pub(crate) file: Style,
pub(crate) line_number: Style,
pub(crate) spantrace_target: Style,
pub(crate) spantrace_fields: Style,
pub(crate) active_line: Style,
pub(crate) error: Style,
pub(crate) help_info_note: Style,
pub(crate) help_info_warning: Style,
pub(crate) help_info_suggestion: Style,
pub(crate) help_info_error: Style,
pub(crate) dependency_code: Style,
pub(crate) crate_code: Style,
pub(crate) code_hash: Style,
pub(crate) panic_header: Style,
pub(crate) panic_message: Style,
pub(crate) panic_file: Style,
pub(crate) panic_line_number: Style,
pub(crate) hidden_frames: Style,
}
macro_rules! theme_setters {
($(#[$meta:meta] $name:ident),* $(,)?) => {
$(
#[$meta]
pub fn $name(mut self, style: Style) -> Self {
self.$name = style;
self
}
)*
};
}
impl Theme {
/// Creates a blank theme
pub fn new() -> Self {
Self::default()
}
/// Returns a theme for dark backgrounds. This is the default
pub fn dark() -> Self {
Self {
file: style().purple(),
line_number: style().purple(),
active_line: style().white().bold(),
error: style().bright_red(),
help_info_note: style().bright_cyan(),
help_info_warning: style().bright_yellow(),
help_info_suggestion: style().bright_cyan(),
help_info_error: style().bright_red(),
dependency_code: style().green(),
crate_code: style().bright_red(),
code_hash: style().bright_black(),
panic_header: style().red(),
panic_message: style().cyan(),
panic_file: style().purple(),
panic_line_number: style().purple(),
hidden_frames: style().bright_cyan(),
spantrace_target: style().bright_red(),
spantrace_fields: style().bright_cyan(),
}
}
// XXX it would be great, if someone with more style optimizes the light theme below. I just fixed the biggest problems, but ideally there would be darker colors (however, the standard ANSI colors don't seem to have many dark enough colors. Maybe xterm colors or RGB colors would be better (however, again, see my comment regarding xterm colors in `color_spantrace`))
/// Returns a theme for light backgrounds
pub fn light() -> Self {
Self {
file: style().purple(),
line_number: style().purple(),
spantrace_target: style().red(),
spantrace_fields: style().blue(),
active_line: style().bold(),
error: style().red(),
help_info_note: style().blue(),
help_info_warning: style().bright_red(),
help_info_suggestion: style().blue(),
help_info_error: style().red(),
dependency_code: style().green(),
crate_code: style().red(),
code_hash: style().bright_black(),
panic_header: style().red(),
panic_message: style().blue(),
panic_file: style().purple(),
panic_line_number: style().purple(),
hidden_frames: style().blue(),
}
}
theme_setters! {
/// Styles printed paths
file,
/// Styles the line number of a file
line_number,
/// Styles the `color_spantrace` target (i.e. the module and function name, and so on)
spantrace_target,
/// Styles fields associated with a the `tracing::Span`.
spantrace_fields,
/// Styles the selected line of displayed code
active_line,
// XXX not sure how to describe this better (or if this is even completely correct)
/// Styles errors printed by `EyreHandler`
error,
/// Styles the "note" section header
help_info_note,
/// Styles the "warning" section header
help_info_warning,
/// Styles the "suggestion" section header
help_info_suggestion,
/// Styles the "error" section header
help_info_error,
/// Styles code that is not part of your crate
dependency_code,
/// Styles code that's in your crate
crate_code,
/// Styles the hash after `dependency_code` and `crate_code`
code_hash,
/// Styles the header of a panic
panic_header,
/// Styles the message of a panic
panic_message,
/// Styles paths of a panic
panic_file,
/// Styles the line numbers of a panic
panic_line_number,
/// Styles the "N frames hidden" message
hidden_frames,
}
}
/// A representation of a Frame from a Backtrace or a SpanTrace
#[derive(Debug)]
#[non_exhaustive]
pub struct Frame {
/// Frame index
pub n: usize,
/// frame symbol name
pub name: Option<String>,
/// source line number
pub lineno: Option<u32>,
/// source file path
pub filename: Option<PathBuf>,
}
#[derive(Debug)]
struct StyledFrame<'a>(&'a Frame, Theme);
impl<'a> fmt::Display for StyledFrame<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self(frame, theme) = self;
let is_dependency_code = frame.is_dependency_code();
// Print frame index.
write!(f, "{:>2}: ", frame.n)?;
// Does the function have a hash suffix?
// (dodging a dep on the regex crate here)
let name = frame.name.as_deref().unwrap_or("<unknown>");
let has_hash_suffix = name.len() > 19
&& &name[name.len() - 19..name.len() - 16] == "::h"
&& name[name.len() - 16..]
.chars()
.all(|x| x.is_ascii_hexdigit());
let hash_suffix = if has_hash_suffix {
&name[name.len() - 19..]
} else {
"<unknown>"
};
// Print function name.
let name = if has_hash_suffix {
&name[..name.len() - 19]
} else {
name
};
if is_dependency_code {
write!(f, "{}", (name).style(theme.dependency_code))?;
} else {
write!(f, "{}", (name).style(theme.crate_code))?;
}
write!(f, "{}", (hash_suffix).style(theme.code_hash))?;
let mut separated = f.header("\n");
// Print source location, if known.
let file = frame.filename.as_ref().map(|path| path.display());
let file: &dyn fmt::Display = if let Some(ref filename) = file {
filename
} else {
&"<unknown source file>"
};
let lineno = frame
.lineno
.map_or("<unknown line>".to_owned(), |x| x.to_string());
write!(
&mut separated.ready(),
" at {}:{}",
file.style(theme.file),
lineno.style(theme.line_number),
)?;
let v = if std::thread::panicking() {
panic_verbosity()
} else {
lib_verbosity()
};
// Maybe print source.
if v >= Verbosity::Full {
write!(&mut separated.ready(), "{}", SourceSection(frame, *theme))?;
}
Ok(())
}
}
struct SourceSection<'a>(&'a Frame, Theme);
impl fmt::Display for SourceSection<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self(frame, theme) = self;
let (lineno, filename) = match (frame.lineno, frame.filename.as_ref()) {
(Some(a), Some(b)) => (a, b),
// Without a line number and file name, we can't sensibly proceed.
_ => return Ok(()),
};
let file = match std::fs::File::open(filename) {
Ok(file) => file,
Err(ref e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
e @ Err(_) => e.unwrap(),
};
use std::fmt::Write;
use std::io::BufRead;
// Extract relevant lines.
let reader = std::io::BufReader::new(file);
let start_line = lineno - 2.min(lineno - 1);
let surrounding_src = reader.lines().skip(start_line as usize - 1).take(5);
let mut separated = f.header("\n");
let mut f = separated.in_progress();
for (line, cur_line_no) in surrounding_src.zip(start_line..) {
let line = line.unwrap();
if cur_line_no == lineno {
write!(
&mut f,
"{:>8} {} {}",
cur_line_no.style(theme.active_line),
">".style(theme.active_line),
line.style(theme.active_line),
)?;
} else {
write!(&mut f, "{:>8} │ {}", cur_line_no, line)?;
}
f = separated.ready();
}
Ok(())
}
}
impl Frame {
fn is_dependency_code(&self) -> bool {
const SYM_PREFIXES: &[&str] = &[
"std::",
"core::",
"backtrace::backtrace::",
"_rust_begin_unwind",
"color_traceback::",
"__rust_",
"___rust_",
"__pthread",
"_main",
"main",
"__scrt_common_main_seh",
"BaseThreadInitThunk",
"_start",
"__libc_start_main",
"start_thread",
];
// Inspect name.
if let Some(ref name) = self.name {
if SYM_PREFIXES.iter().any(|x| name.starts_with(x)) {
return true;
}
}
const FILE_PREFIXES: &[&str] = &[
"/rustc/",
"src/libstd/",
"src/libpanic_unwind/",
"src/libtest/",
];
// Inspect filename.
if let Some(ref filename) = self.filename {
let filename = filename.to_string_lossy();
if FILE_PREFIXES.iter().any(|x| filename.starts_with(x))
|| filename.contains("/.cargo/registry/src/")
{
return true;
}
}
false
}
/// Heuristically determine whether a frame is likely to be a post panic
/// frame.
///
/// Post panic frames are frames of a functions called after the actual panic
/// is already in progress and don't contain any useful information for a
/// reader of the backtrace.
fn is_post_panic_code(&self) -> bool {
const SYM_PREFIXES: &[&str] = &[
"_rust_begin_unwind",
"rust_begin_unwind",
"core::result::unwrap_failed",
"core::option::expect_none_failed",
"core::panicking::panic_fmt",
"color_backtrace::create_panic_handler",
"std::panicking::begin_panic",
"begin_panic_fmt",
"failure::backtrace::Backtrace::new",
"backtrace::capture",
"failure::error_message::err_msg",
"<failure::error::Error as core::convert::From<F>>::from",
];
match self.name.as_ref() {
Some(name) => SYM_PREFIXES.iter().any(|x| name.starts_with(x)),
None => false,
}
}
/// Heuristically determine whether a frame is likely to be part of language
/// runtime.
fn is_runtime_init_code(&self) -> bool {
const SYM_PREFIXES: &[&str] = &[
"std::rt::lang_start::",
"test::run_test::run_test_inner::",
"std::sys_common::backtrace::__rust_begin_short_backtrace",
];
let (name, file) = match (self.name.as_ref(), self.filename.as_ref()) {
(Some(name), Some(filename)) => (name, filename.to_string_lossy()),
_ => return false,
};
if SYM_PREFIXES.iter().any(|x| name.starts_with(x)) {
return true;
}
// For Linux, this is the best rule for skipping test init I found.
if name == "{{closure}}" && file == "src/libtest/lib.rs" {
return true;
}
false
}
}
/// Builder for customizing the behavior of the global panic and error report hooks
pub struct HookBuilder {
filters: Vec<Box<FilterCallback>>,
capture_span_trace_by_default: bool,
display_env_section: bool,
#[cfg(feature = "track-caller")]
display_location_section: bool,
panic_section: Option<Box<dyn Display + Send + Sync + 'static>>,
panic_message: Option<Box<dyn PanicMessage>>,
theme: Theme,
#[cfg(feature = "issue-url")]
issue_url: Option<String>,
#[cfg(feature = "issue-url")]
issue_metadata: Vec<(String, Box<dyn Display + Send + Sync + 'static>)>,
#[cfg(feature = "issue-url")]
issue_filter: Arc<IssueFilterCallback>,
}
impl HookBuilder {
/// Construct a HookBuilder
///
/// # Details
///
/// By default this function calls `add_default_filters()` and
/// `capture_span_trace_by_default(true)`. To get a `HookBuilder` with all
/// features disabled by default call `HookBuilder::blank()`.
///
/// # Example
///
/// ```rust
/// use color_eyre::config::HookBuilder;
///
/// HookBuilder::new()
/// .install()
/// .unwrap();
/// ```
pub fn new() -> Self {
Self::blank()
.add_default_filters()
.capture_span_trace_by_default(true)
}
/// Construct a HookBuilder with minimal features enabled
pub fn blank() -> Self {
HookBuilder {
filters: vec![],
capture_span_trace_by_default: false,
display_env_section: true,
#[cfg(feature = "track-caller")]
display_location_section: true,
panic_section: None,
panic_message: None,
theme: Theme::dark(),
#[cfg(feature = "issue-url")]
issue_url: None,
#[cfg(feature = "issue-url")]
issue_metadata: vec![],
#[cfg(feature = "issue-url")]
issue_filter: Arc::new(|_| true),
}
}
/// Set the global styles that `color_eyre` should use.
///
/// **Tip:** You can test new styles by editing `examples/theme.rs` in the `color-eyre` repository.
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = theme;
self
}
/// Add a custom section to the panic hook that will be printed
/// in the panic message.
///
/// # Examples
///
/// ```rust
/// color_eyre::config::HookBuilder::default()
/// .panic_section("consider reporting the bug at https://github.com/yaahc/color-eyre")
/// .install()
/// .unwrap()
/// ```
pub fn panic_section<S: Display + Send + Sync + 'static>(mut self, section: S) -> Self {
self.panic_section = Some(Box::new(section));
self
}
/// Overrides the main error message printing section at the start of panic
/// reports
///
/// # Examples
///
/// ```rust
/// use std::{panic::Location, fmt};
/// use color_eyre::section::PanicMessage;
/// use owo_colors::OwoColorize;
///
/// struct MyPanicMessage;
///
/// color_eyre::config::HookBuilder::default()
/// .panic_message(MyPanicMessage)
/// .install()
/// .unwrap();
///
/// impl PanicMessage for MyPanicMessage {
/// fn display(&self, pi: &std::panic::PanicInfo<'_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// writeln!(f, "{}", "The application panicked (crashed).".red())?;
///
/// // Print panic message.
/// let payload = pi
/// .payload()
/// .downcast_ref::<String>()
/// .map(String::as_str)
/// .or_else(|| pi.payload().downcast_ref::<&str>().cloned())
/// .unwrap_or("<non string panic payload>");
///
/// write!(f, "Message: ")?;
/// writeln!(f, "{}", payload.cyan())?;
///
/// // If known, print panic location.
/// write!(f, "Location: ")?;
/// if let Some(loc) = pi.location() {
/// write!(f, "{}", loc.file().purple())?;
/// write!(f, ":")?;
/// write!(f, "{}", loc.line().purple())?;
///
/// write!(f, "\n\nConsider reporting the bug at {}", custom_url(loc, payload))?;
/// } else {
/// write!(f, "<unknown>")?;
/// }
///
/// Ok(())
/// }
/// }
///
/// fn custom_url(location: &Location<'_>, message: &str) -> impl fmt::Display {
/// "todo"
/// }
/// ```
pub fn panic_message<S: PanicMessage>(mut self, section: S) -> Self {
self.panic_message = Some(Box::new(section));
self
}
/// Set an upstream github repo and enable issue reporting url generation
///
/// # Details
///
/// Once enabled, color-eyre will generate urls that will create customized
/// issues pre-populated with information about the associated error report.
///
/// Additional information can be added to the metadata table in the
/// generated urls by calling `add_issue_metadata` when configuring the
/// HookBuilder.
///
/// # Examples
///
/// ```rust
/// color_eyre::config::HookBuilder::default()
/// .issue_url(concat!(env!("CARGO_PKG_REPOSITORY"), "/issues/new"))
/// .install()
/// .unwrap();
/// ```
#[cfg(feature = "issue-url")]
#[cfg_attr(docsrs, doc(cfg(feature = "issue-url")))]
pub fn issue_url<S: ToString>(mut self, url: S) -> Self {
self.issue_url = Some(url.to_string());
self
}
/// Add a new entry to the metadata table in generated github issue urls
///
/// **Note**: this metadata will be ignored if no `issue_url` is set.
///
/// # Examples
///
/// ```rust
/// color_eyre::config::HookBuilder::default()
/// .issue_url(concat!(env!("CARGO_PKG_REPOSITORY"), "/issues/new"))
/// .add_issue_metadata("version", env!("CARGO_PKG_VERSION"))
/// .install()
/// .unwrap();
/// ```
#[cfg(feature = "issue-url")]
#[cfg_attr(docsrs, doc(cfg(feature = "issue-url")))]
pub fn add_issue_metadata<K, V>(mut self, key: K, value: V) -> Self
where
K: Display,
V: Display + Send + Sync + 'static,
{
let pair = (key.to_string(), Box::new(value) as _);
self.issue_metadata.push(pair);
self
}
/// Configures a filter for disabling issue url generation for certain kinds of errors
///
/// If the closure returns `true`, then the issue url will be generated.
///
/// # Examples
///
/// ```rust
/// color_eyre::config::HookBuilder::default()
/// .issue_url(concat!(env!("CARGO_PKG_REPOSITORY"), "/issues/new"))
/// .issue_filter(|kind| match kind {
/// color_eyre::ErrorKind::NonRecoverable(payload) => {
/// let payload = payload
/// .downcast_ref::<String>()
/// .map(String::as_str)
/// .or_else(|| payload.downcast_ref::<&str>().cloned())
/// .unwrap_or("<non string panic payload>");
///
/// !payload.contains("my irrelevant error message")
/// },
/// color_eyre::ErrorKind::Recoverable(error) => !error.is::<std::fmt::Error>(),
/// })
/// .install()
/// .unwrap();
///
#[cfg(feature = "issue-url")]
#[cfg_attr(docsrs, doc(cfg(feature = "issue-url")))]
pub fn issue_filter<F>(mut self, predicate: F) -> Self
where
F: Fn(crate::ErrorKind<'_>) -> bool + Send + Sync + 'static,
{
self.issue_filter = Arc::new(predicate);
self
}
/// Configures the default capture mode for `SpanTraces` in error reports and panics
pub fn capture_span_trace_by_default(mut self, cond: bool) -> Self {
self.capture_span_trace_by_default = cond;
self
}
/// Configures the enviroment varible info section and whether or not it is displayed
pub fn display_env_section(mut self, cond: bool) -> Self {
self.display_env_section = cond;
self
}
/// Configures the location info section and whether or not it is displayed.
///
/// # Notes
///
/// This will not disable the location section in a panic message.
#[cfg(feature = "track-caller")]
#[cfg_attr(docsrs, doc(cfg(feature = "track-caller")))]
pub fn display_location_section(mut self, cond: bool) -> Self {
self.display_location_section = cond;
self
}
/// Add a custom filter to the set of frame filters
///
/// # Examples
///
/// ```rust
/// color_eyre::config::HookBuilder::default()
/// .add_frame_filter(Box::new(|frames| {
/// let filters = &[
/// "uninteresting_function",
/// ];
///
/// frames.retain(|frame| {
/// !filters.iter().any(|f| {
/// let name = if let Some(name) = frame.name.as_ref() {
/// name.as_str()
/// } else {
/// return true;
/// };
///
/// name.starts_with(f)
/// })
/// });
/// }))
/// .install()
/// .unwrap();
/// ```
pub fn add_frame_filter(mut self, filter: Box<FilterCallback>) -> Self {
self.filters.push(filter);
self
}
/// Install the given Hook as the global error report hook
pub fn install(self) -> Result<(), crate::eyre::Report> {
let (panic_hook, eyre_hook) = self.try_into_hooks()?;
eyre_hook.install()?;
panic_hook.install();
Ok(())
}
/// Add the default set of filters to this `HookBuilder`'s configuration
pub fn add_default_filters(self) -> Self {
self.add_frame_filter(Box::new(default_frame_filter))
.add_frame_filter(Box::new(eyre_frame_filters))
}
/// Create a `PanicHook` and `EyreHook` from this `HookBuilder`.
/// This can be used if you want to combine these handlers with other handlers.
pub fn into_hooks(self) -> (PanicHook, EyreHook) {
self.try_into_hooks().expect("into_hooks should only be called when no `color_spantrace` themes have previously been set")
}
/// Create a `PanicHook` and `EyreHook` from this `HookBuilder`.
/// This can be used if you want to combine these handlers with other handlers.
pub fn try_into_hooks(self) -> Result<(PanicHook, EyreHook), crate::eyre::Report> {
let theme = self.theme;
#[cfg(feature = "issue-url")]
let metadata = Arc::new(self.issue_metadata);
let panic_hook = PanicHook {
filters: self.filters.into(),
section: self.panic_section,
#[cfg(feature = "capture-spantrace")]
capture_span_trace_by_default: self.capture_span_trace_by_default,
display_env_section: self.display_env_section,
panic_message: self
.panic_message
.unwrap_or_else(|| Box::new(DefaultPanicMessage(theme))),
theme,
#[cfg(feature = "issue-url")]
issue_url: self.issue_url.clone(),
#[cfg(feature = "issue-url")]
issue_metadata: metadata.clone(),
#[cfg(feature = "issue-url")]
issue_filter: self.issue_filter.clone(),
};
let eyre_hook = EyreHook {
filters: panic_hook.filters.clone(),
#[cfg(feature = "capture-spantrace")]
capture_span_trace_by_default: self.capture_span_trace_by_default,
display_env_section: self.display_env_section,
#[cfg(feature = "track-caller")]
display_location_section: self.display_location_section,
theme,
#[cfg(feature = "issue-url")]
issue_url: self.issue_url,
#[cfg(feature = "issue-url")]
issue_metadata: metadata,
#[cfg(feature = "issue-url")]
issue_filter: self.issue_filter,
};
#[cfg(feature = "capture-spantrace")]
color_spantrace::set_theme(self.theme.into()).wrap_err("could not set the provided `Theme` via `color_spantrace::set_theme` globally as another was already set")?;
Ok((panic_hook, eyre_hook))
}
}
#[cfg(feature = "capture-spantrace")]
impl From<Theme> for color_spantrace::Theme {
fn from(src: Theme) -> color_spantrace::Theme {
color_spantrace::Theme::new()
.file(src.file)
.line_number(src.line_number)
.target(src.spantrace_target)
.fields(src.spantrace_fields)
.active_line(src.active_line)
}
}
#[allow(missing_docs)]
impl Default for HookBuilder {
fn default() -> Self {
Self::new()
}
}
fn default_frame_filter(frames: &mut Vec<&Frame>) {
let top_cutoff = frames
.iter()
.rposition(|x| x.is_post_panic_code())
.map(|x| x + 2) // indices are 1 based
.unwrap_or(0);
let bottom_cutoff = frames
.iter()
.position(|x| x.is_runtime_init_code())
.unwrap_or(frames.len());
let rng = top_cutoff..=bottom_cutoff;
frames.retain(|x| rng.contains(&x.n))
}
fn eyre_frame_filters(frames: &mut Vec<&Frame>) {
let filters = &[
"<color_eyre::Handler as eyre::EyreHandler>::default",
"eyre::",
"color_eyre::",
];
frames.retain(|frame| {
!filters.iter().any(|f| {
let name = if let Some(name) = frame.name.as_ref() {
name.as_str()
} else {
return true;
};
name.starts_with(f)
})
});
}
struct DefaultPanicMessage(Theme);
impl PanicMessage for DefaultPanicMessage {
fn display(&self, pi: &std::panic::PanicInfo<'_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// XXX is my assumption correct that this function is guaranteed to only run after `color_eyre` was setup successfully (including setting `THEME`), and that therefore the following line will never panic? Otherwise, we could return `fmt::Error`, but if the above is true, I like `unwrap` + a comment why this never fails better
let theme = &self.0;
writeln!(
f,
"{}",
"The application panicked (crashed).".style(theme.panic_header)
)?;
// Print panic message.
let payload = pi
.payload()
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| pi.payload().downcast_ref::<&str>().cloned())
.unwrap_or("<non string panic payload>");
write!(f, "Message: ")?;
writeln!(f, "{}", payload.style(theme.panic_message))?;
// If known, print panic location.
write!(f, "Location: ")?;
write!(f, "{}", crate::fmt::LocationSection(pi.location(), *theme))?;
Ok(())
}
}
/// A type representing an error report for a panic.
pub struct PanicReport<'a> {
hook: &'a PanicHook,
panic_info: &'a std::panic::PanicInfo<'a>,
backtrace: Option<backtrace::Backtrace>,
#[cfg(feature = "capture-spantrace")]
span_trace: Option<tracing_error::SpanTrace>,
}
fn print_panic_info(report: &PanicReport<'_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
report.hook.panic_message.display(report.panic_info, f)?;
let v = panic_verbosity();
let capture_bt = v != Verbosity::Minimal;
let mut separated = f.header("\n\n");
if let Some(ref section) = report.hook.section {
write!(&mut separated.ready(), "{}", section)?;
}
#[cfg(feature = "capture-spantrace")]
{
if let Some(span_trace) = report.span_trace.as_ref() {
write!(
&mut separated.ready(),
"{}",
crate::writers::FormattedSpanTrace(span_trace)
)?;
}
}
if let Some(bt) = report.backtrace.as_ref() {
let fmted_bt = report.hook.format_backtrace(bt);
write!(
indented(&mut separated.ready()).with_format(Format::Uniform { indentation: " " }),
"{}",
fmted_bt
)?;
}
if report.hook.display_env_section {
let env_section = EnvSection {
bt_captured: &capture_bt,
#[cfg(feature = "capture-spantrace")]
span_trace: report.span_trace.as_ref(),
};
write!(&mut separated.ready(), "{}", env_section)?;
}
#[cfg(feature = "issue-url")]
{
let payload = report.panic_info.payload();
if report.hook.issue_url.is_some()
&& (*report.hook.issue_filter)(crate::ErrorKind::NonRecoverable(payload))
{
let url = report.hook.issue_url.as_ref().unwrap();
let payload = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().cloned())
.unwrap_or("<non string panic payload>");
let issue_section = crate::section::github::IssueSection::new(url, payload)
.with_backtrace(report.backtrace.as_ref())
.with_location(report.panic_info.location())
.with_metadata(&**report.hook.issue_metadata);
#[cfg(feature = "capture-spantrace")]
let issue_section = issue_section.with_span_trace(report.span_trace.as_ref());
write!(&mut separated.ready(), "{}", issue_section)?;
}
}
Ok(())
}
impl fmt::Display for PanicReport<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
print_panic_info(self, f)
}
}
/// A panic reporting hook
pub struct PanicHook {
filters: Arc<[Box<FilterCallback>]>,
section: Option<Box<dyn Display + Send + Sync + 'static>>,
panic_message: Box<dyn PanicMessage>,
theme: Theme,
#[cfg(feature = "capture-spantrace")]
capture_span_trace_by_default: bool,
display_env_section: bool,
#[cfg(feature = "issue-url")]
issue_url: Option<String>,
#[cfg(feature = "issue-url")]
issue_metadata: Arc<Vec<(String, Box<dyn Display + Send + Sync + 'static>)>>,
#[cfg(feature = "issue-url")]
issue_filter: Arc<IssueFilterCallback>,
}
impl PanicHook {
pub(crate) fn format_backtrace<'a>(
&'a self,
trace: &'a backtrace::Backtrace,
) -> BacktraceFormatter<'a> {
BacktraceFormatter {
filters: &self.filters,
inner: trace,
theme: self.theme,
}
}
#[cfg(feature = "capture-spantrace")]
fn spantrace_capture_enabled(&self) -> bool {
std::env::var("RUST_SPANTRACE")
.map(|val| val != "0")
.unwrap_or(self.capture_span_trace_by_default)
}
/// Install self as a global panic hook via `std::panic::set_hook`.
pub fn install(self) {
std::panic::set_hook(self.into_panic_hook());
}
/// Convert self into the type expected by `std::panic::set_hook`.
pub fn into_panic_hook(
self,
) -> Box<dyn Fn(&std::panic::PanicInfo<'_>) + Send + Sync + 'static> {
Box::new(move |panic_info| {
eprintln!("{}", self.panic_report(panic_info));
})
}
/// Construct a panic reporter which prints it's panic report via the
/// `Display` trait.
pub fn panic_report<'a>(
&'a self,
panic_info: &'a std::panic::PanicInfo<'_>,
) -> PanicReport<'a> {
let v = panic_verbosity();
let capture_bt = v != Verbosity::Minimal;