shepmaster / snafu

Easily assign underlying errors into domain-specific errors while adding context
https://docs.rs/snafu/
Apache License 2.0
1.39k stars 60 forks source link

Use the alternate formatting macros from `color_print`. #461

Open iago-lito opened 1 month ago

iago-lito commented 1 month ago

I like how the color_print crate provides the cformat!() macro to statically generate ANSI colored strings.

Would it be an option to enable opt-in into this alternate formatting style for the #[snafu(display(..))] attributes?

Something along:

use color_print::cformat;

#[derive(Debug, Snafu)]
enum Error {
    #[snafu(display(cformat, "<green>{username}</> may not log in until they pay USD <yellow,bold>{amount:E}</>"))]
    UserMustPayForService { username: String, amount: f32 },
}

?

(maybe one condition would be that color_print features cwrite!(), the colored version of write!(), rather than cformat!()?)

8573 commented 1 month ago

Would this mean that (for types opting in) the errors would be displayable only in terminal, and specifically only terminals supporting these color codes?

iago-lito commented 1 month ago

I guess it would, yes. There is a terminfo feature in this crate to accommodate various terminals, but non-ANSI are explicitly not supported.

Also, I guess that if you want to format!("a string with the {error} message.") without the escape codes inside, you'd need to remove them, or ask that color_print features some API to render without them and turn that into format!("a string with the {} message.", error.unpaint()) or something.

To be honest, I am not 100% sure that color_print is ready for the job yet, or that making it interact with snafu would be free of quirks. But I'm happy to investigate because I like the approach taken by color_print and I wonder how much work it would represent to integrate the two together.

Is the #[snafu(display(..))] attribute deeply entangled with write!(..) / format_args!(..), or could it easily handle alternative formatting macros?