error-stack: implementing conditional fmt::Display
behaviour based on ColorMode
for an attachment
#3932
-
I am adding an attachment called /// wrapper attachment that is used to refer to the type of an object
/// rather than the value
pub struct Type(&'static str);
impl Type {
// const fn when `std::any::type_name` is const fn in stable
pub fn of<T>() -> Self {
Self(std::any::type_name::<T>())
}
}
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "<{}>", self.0)
}
}
impl std::fmt::Debug for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Type").field(&self.0).finish()
}
} I would like to evaluate the colour mode for each attachment that I display: const GREEN_LT: &'static str = '<'.green();
// const ...
impl std::fmt::Display for Type {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match somehow_get_color_mode() {
ColorMode::None => write!(f, "<{}>", self.0),
ColorMode::Color => write!(f, "{GREEN_LT}{}{GREEN_GT}"}, self.0),
ColorMode::Emphasis => write!(f, "{BOLD_LT}{}{BOLD_GT}", self.0),
}
}
} The suggested approach for dealing with conditional formatting is use
hash/libs/error-stack/src/fmt/hook.rs Lines 497 to 507 in 1c930a0 I'm curious if there's a good way to allow attachments to define their own conditional formatting and have them be instantiated into the prelude along with the builtin types. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I apologize for the late reply; this completely flew under my radar.
In the first iteration of the output, we actually thought about utilizing The other question is: Why don't we use |
Beta Was this translation helpful? Give feedback.
I apologize for the late reply; this completely flew under my radar.
Report::install_debug_hook
is the thing you're looking for; it is invoked for every attachment typeT
and provides the color mode as well as charset. You will need to callinstall_debug_hook
at the start of your application (just as you would when you're trying to configure tracing).In the first iteration of the output, we actually thought about utilizing
Display
for this exact purpose but came to the conclusion that it wouldn't be of much help and that we needed to create a separate way to do this. This is because we cannot "smuggle" any data into theFormatter
without sacrificing quite a bit of general usability. We a…