detect/
detect.rs

1#![expect(clippy::print_stdout, clippy::use_debug)]
2// This example shows how you can use the `supports-color` and `supports-unicode` crates to
3// automatically enable or disable the color mode and set the appropriate charset.
4// Your default terminal should automatically show colored unicode output, to emulate a terminal
5// that does not support color set your `$TERM` env-variable **temporarily** to "dumb", or set the
6// env-variable `NO_COLOR=1`. To emulate no-unicode support set your `$TERM` variable
7// **temporarily** to `linux`.
8
9use core::fmt::{Display, Formatter};
10use std::path::Path;
11
12use error_stack::{
13    fmt::{Charset, ColorMode},
14    Report, Result,
15};
16
17type Config = String;
18
19#[derive(Debug)]
20struct ParseConfigError;
21
22impl Display for ParseConfigError {
23    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
24        f.write_str("unable to parse config")
25    }
26}
27
28impl core::error::Error for ParseConfigError {}
29
30fn parse_config(path: impl AsRef<Path>) -> Result<Config, ParseConfigError> {
31    _ = path.as_ref();
32
33    /*
34       usually you would actually do something here, we just error out, for a more complete example
35       check out the other examples
36    */
37
38    Err(Report::new(ParseConfigError).attach_printable("unable to read configuration"))
39}
40
41fn main() {
42    // error-stack only uses ANSI codes for colors
43    let supports_color = supports_color::on_cached(supports_color::Stream::Stdout)
44        .map_or(false, |level| level.has_basic);
45
46    let color_mode = if supports_color {
47        ColorMode::Color
48    } else {
49        ColorMode::None
50    };
51
52    let supports_unicode = supports_unicode::on(supports_unicode::Stream::Stdout);
53
54    let charset = if supports_unicode {
55        Charset::Utf8
56    } else {
57        Charset::Ascii
58    };
59
60    Report::set_color_mode(color_mode);
61    Report::set_charset(charset);
62
63    if let Err(err) = parse_config("config.json") {
64        // if you would use `eprintln!` instead, you should check support on `Stream::Stderr`
65        // instead.
66        println!("{err:?}");
67    }
68}