From 03376ffba1ed4745b19ab8c8bf857bc686b05a89 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Sun, 8 Aug 2021 15:00:18 +0100 Subject: [PATCH] backtraces: Print only when RUST_BACKTRACE=1 Signed-off-by: Ian Jackson --- Cargo.lock | 1 + Cargo.toml | 1 + src/prelude.rs | 2 ++ src/reporter.rs | 32 ++++++++++++++++++++++++++------ 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0c05f7d..0a7897e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -426,6 +426,7 @@ dependencies = [ "ipnet", "itertools", "lazy-regex", + "lazy_static", "log", "mime", "parking_lot", diff --git a/Cargo.toml b/Cargo.toml index 1b1a3df..8d27fef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ itertools = "0.10" mime = "0.3" parking_lot = "0.11" regex = "1.5" +lazy_static = "1.4" log = "0.4" sha2 = "0.9" structopt = "0.3" diff --git a/src/prelude.rs b/src/prelude.rs index e09747e..ceb57d1 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -8,6 +8,7 @@ pub use std::convert::{Infallible, TryFrom, TryInto}; pub use std::borrow::Cow; pub use std::cell::{RefCell, RefMut}; pub use std::cmp::{min, max}; +pub use std::env; pub use std::fs; pub use std::fmt::{self, Debug, Display, Write as _}; pub use std::future::Future; @@ -34,6 +35,7 @@ pub use hyper_tls::HttpsConnector; pub use ipnet::IpNet; pub use itertools::{iproduct, Itertools}; pub use lazy_regex::{regex_captures, regex_is_match, regex_replace_all}; +pub use lazy_static::lazy_static; pub use log::{trace, debug, info, warn, error}; pub use structopt::StructOpt; pub use thiserror::Error; diff --git a/src/reporter.rs b/src/reporter.rs index 49b784b..0776dce 100644 --- a/src/reporter.rs +++ b/src/reporter.rs @@ -117,7 +117,7 @@ use indenter::indented; #[derive(Debug)] struct EyreDedupHandler { - backtrace: Arc>, + backtrace: Option>>, } type EyreDynError<'r> = &'r (dyn std::error::Error + 'static); @@ -161,17 +161,37 @@ impl eyre::EyreHandler for EyreDedupHandler { } } - let mut backtrace = self.backtrace.lock(); - backtrace.resolve(); - write!(f, "\n\nStack backtrace:\n{:?}", backtrace)?; + if let Some(bt) = &self.backtrace { + let mut bt = bt.lock(); + bt.resolve(); + write!(f, "\n\nStack backtrace:\n{:?}", bt)?; + } } } #[throws(AE)] pub fn dedup_eyre_setup() { eyre::set_hook(Box::new(|_error| { - let backtrace = Backtrace::new_unresolved(); - let backtrace = Arc::new(backtrace.into()); + lazy_static! { + static ref BACKTRACE: bool = { + match env::var("RUST_BACKTRACE") { + Ok(s) if s.starts_with("1") => true, + Ok(s) if s == "0" => false, + Err(env::VarError::NotPresent) => false, + x => { + eprintln!("warning: RUST_BACKTRACE not understood: {:?}", x); + false + }, + } + }; + } + let backtrace = if *BACKTRACE { + let bt = Backtrace::new_unresolved(); + let bt = Arc::new(bt.into()); + Some(bt) + } else { + None + }; Box::new(EyreDedupHandler { backtrace }) })) .context("set error handler")?; -- 2.30.2