Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(color-eyre): Add pre-hook callbacks #183

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions color-eyre/examples/pre_hook_callbacks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use color_eyre::eyre::Report;
use tracing::instrument;

#[instrument]
fn main() -> Result<(), Report> {
#[cfg(feature = "capture-spantrace")]
install_tracing();

color_eyre::config::HookBuilder::default()
.add_pre_hook_callback(Box::new(|| {
eprintln!("This is a pre hook callback");
}))
.install()
.unwrap();

read_config();

Ok(())
}

#[cfg(feature = "capture-spantrace")]
fn install_tracing() {
use tracing_error::ErrorLayer;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{fmt, EnvFilter};

let fmt_layer = fmt::layer().with_target(false);
let filter_layer = EnvFilter::try_from_default_env()
.or_else(|_| EnvFilter::try_new("info"))
.unwrap();

tracing_subscriber::registry()
.with(filter_layer)
.with(fmt_layer)
.with(ErrorLayer::default())
.init();
}

#[instrument]
fn read_file(path: &str) {
if let Err(e) = std::fs::read_to_string(path) {
panic!("{}", e);
}
}

#[instrument]
fn read_config() {
read_file("fake_file")
}
67 changes: 34 additions & 33 deletions color-eyre/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,6 @@ 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 {
Expand Down Expand Up @@ -418,6 +385,7 @@ impl Frame {
/// Builder for customizing the behavior of the global panic and error report hooks
pub struct HookBuilder {
filters: Vec<Box<FilterCallback>>,
pre_hook_callbacks: Vec<Box<PreHookCallback>>,
capture_span_trace_by_default: bool,
display_env_section: bool,
#[cfg(feature = "track-caller")]
Expand Down Expand Up @@ -461,6 +429,7 @@ impl HookBuilder {
pub fn blank() -> Self {
HookBuilder {
filters: vec![],
pre_hook_callbacks: vec![],
capture_span_trace_by_default: false,
display_env_section: true,
#[cfg(feature = "track-caller")]
Expand Down Expand Up @@ -698,6 +667,28 @@ impl HookBuilder {
self
}

/// Add a custom pre-hook callback to the set of pre-hook callbacks
///
/// This callback will be called before the panic / error hook is called. It can be used to
/// print additional information or perform other actions before the panic / error hook is
/// called (such as clearing the terminal, printing a message, etc.)
///
/// **Note**: This callback will be called in the context of the panic hook, so it should be
/// fast and not panic.
///
/// # Examples
///
/// ```rust
/// color_eyre::config::HookBuilder::default()
/// .add_pre_hook_callback(Box::new(|| eprintln!("pre-hook callback")))
/// .install()
/// .unwrap();
/// ```
pub fn add_pre_hook_callback(mut self, callback: Box<PreHookCallback>) -> Self {
self.pre_hook_callbacks.push(callback);
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()?;
Expand Down Expand Up @@ -726,6 +717,7 @@ impl HookBuilder {
let metadata = Arc::new(self.issue_metadata);
let panic_hook = PanicHook {
filters: self.filters.into(),
pre_hook_callbacks: self.pre_hook_callbacks.into(),
section: self.panic_section,
#[cfg(feature = "capture-spantrace")]
capture_span_trace_by_default: self.capture_span_trace_by_default,
Expand All @@ -744,6 +736,7 @@ impl HookBuilder {

let eyre_hook = EyreHook {
filters: panic_hook.filters.clone(),
// TODO pre_hook_callbacks: panic_hook.pre_hook_callbacks.clone(),
#[cfg(feature = "capture-spantrace")]
capture_span_trace_by_default: self.capture_span_trace_by_default,
display_env_section: self.display_env_section,
Expand Down Expand Up @@ -941,6 +934,7 @@ impl fmt::Display for PanicReport<'_> {
/// A panic reporting hook
pub struct PanicHook {
filters: Arc<[Box<FilterCallback>]>,
pre_hook_callbacks: Arc<[Box<PreHookCallback>]>,
section: Option<Box<dyn Display + Send + Sync + 'static>>,
panic_message: Box<dyn PanicMessage>,
theme: Theme,
Expand Down Expand Up @@ -984,6 +978,9 @@ impl PanicHook {
self,
) -> Box<dyn Fn(&std::panic::PanicInfo<'_>) + Send + Sync + 'static> {
Box::new(move |panic_info| {
for callback in self.pre_hook_callbacks.iter() {
callback();
}
eprintln!("{}", self.panic_report(panic_info));
})
}
Expand Down Expand Up @@ -1023,6 +1020,7 @@ impl PanicHook {
/// An eyre reporting hook used to construct `EyreHandler`s
pub struct EyreHook {
filters: Arc<[Box<FilterCallback>]>,
// TODO pre_hook_callbacks: Arc<[Box<PreHookCallback>]>,
#[cfg(feature = "capture-spantrace")]
capture_span_trace_by_default: bool,
display_env_section: bool,
Expand Down Expand Up @@ -1215,6 +1213,9 @@ pub(crate) fn lib_verbosity() -> Verbosity {
/// Callback for filtering a vector of `Frame`s
pub type FilterCallback = dyn Fn(&mut Vec<&Frame>) + Send + Sync + 'static;

/// Callback to run before running the panic / error hook
pub type PreHookCallback = dyn Fn() + Send + Sync + 'static;

/// Callback for filtering issue url generation in error reports
#[cfg(feature = "issue-url")]
#[cfg_attr(docsrs, doc(cfg(feature = "issue-url")))]
Expand Down
8 changes: 8 additions & 0 deletions color-eyre/src/writers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@ impl<W> WriterExt for W {
}
}

#[cfg(feature = "issue-url")]
pub(crate) trait DisplayExt: Sized + Display {
fn with_header<H: Display>(self, header: H) -> Header<Self, H>;
fn with_footer<F: Display>(self, footer: F) -> Footer<Self, F>;
}

#[cfg(feature = "issue-url")]
impl<T> DisplayExt for T
where
T: Display,
Expand Down Expand Up @@ -80,11 +82,13 @@ where
}
}

#[cfg(feature = "issue-url")]
pub(crate) struct FooterWriter<W> {
inner: W,
had_output: bool,
}

#[cfg(feature = "issue-url")]
impl<W> fmt::Write for FooterWriter<W>
where
W: fmt::Write,
Expand All @@ -98,6 +102,7 @@ where
}
}

#[cfg(feature = "issue-url")]
#[allow(explicit_outlives_requirements)]
pub(crate) struct Footer<B, H>
where
Expand All @@ -108,6 +113,7 @@ where
footer: H,
}

#[cfg(feature = "issue-url")]
impl<B, H> fmt::Display for Footer<B, H>
where
B: Display,
Expand All @@ -129,6 +135,7 @@ where
}
}

#[cfg(feature = "issue-url")]
#[allow(explicit_outlives_requirements)]
pub(crate) struct Header<B, H>
where
Expand All @@ -139,6 +146,7 @@ where
h: H,
}

#[cfg(feature = "issue-url")]
impl<B, H> fmt::Display for Header<B, H>
where
B: Display,
Expand Down
Loading