3 releases

0.1.6 Mar 19, 2024
0.1.5 Sep 24, 2023
0.1.4 Jul 20, 2023

#99 in Value formatting


Used in 3 crates (2 directly)

MIT license

69KB
2K SLoC

Pretty Struct

Displays (json) structures in a pretty way.

This crate is linked to the crud library. If I have time and motivation to generalize it, it can be an indenpendant crate.

Example

use crud_pretty_struct_derive::PrettyPrint;
#[derive(PrettyPrint)]
struct Foo {
    #[pretty(color="green")]
    a: u32,
    #[pretty(skip_none)]
    b: Option<String>,
    #[pretty(formatter=crud_pretty_struct::formatters::bool_check_formatter)]
    c: bool,
    #[pretty(is_pretty)]
    d: OtherPrettyStruct
}

Field Options

is_pretty

the nested struct implements PrettyPrint and should be printed using it.

use crud_pretty_struct_derive::PrettyPrint;
#[derive(PrettyPrint)]
struct OtherPrettyStruct {}
#[derive(PrettyPrint)]
struct Foo {
    #[pretty(is_pretty)]
    field: OtherPrettyStruct
}
label

custom label for this field

#[derive(PrettyPrint)]
struct Foo {
    #[pretty(label="☀️ my field")]
    field: u32
}
color

custom color for this field. The avaiable colors are [Color].

#[derive(PrettyPrint)]
struct Foo {
    #[pretty(color="red")]
    field: u32
}
label_color

custom color for the label of this field. The avaiable colors are [Color].

#[derive(PrettyPrint)]
struct Foo {
    #[pretty(color="red")]
    field: u32
}
skip

skip the field. It won't be display.

#[derive(PrettyPrint)]
struct Foo {
    #[pretty(skip)]
    field: u32
}
skip_none

skip the field if the value is None. The type of the field should be an Option<T>.

#[derive(PrettyPrint)]
struct Foo {
    #[pretty(skip_none)]
    field: Option<u32>
}
formatter

Custom value formatter for this field.

Some [formatters] are shipped in this crate.

#[derive(PrettyPrint)]
struct Foo {
    #[pretty(formatter=crud_pretty_struct::formatters::bool_check_formatter)]
    field: bool
}

Formatters should follow this signature:

type Formatter = dyn Fn(/*value:*/ &dyn ToString, /*colored:*/ bool) -> miette::Result<(String, bool)>;

Parameters:

  • value: the value to format
  • colored: when true the formatted value can be colored

Result:

  • String: the formatted value
  • bool: returns true if the value have colors. returns false if the value don't have colors then default color will be applied.
#[derive(PrettyPrint)]
struct Foo {
    #[pretty(formatter=|x, _| Ok((format!("{} kg", x.to_string()), false)))]
    field: f32
}

Dependencies

~5–15MB
~192K SLoC