akv_cli/
json.rs

1// Copyright 2025 Heath Stewart.
2// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
3
4#[cfg(feature = "color")]
5use crate::color;
6use serde::Serialize;
7use std::io::{stdout, IsTerminal as _};
8
9pub fn print<T: Serialize>(
10    value: &T,
11    #[allow(unused_variables)] mode: ColorMode,
12) -> crate::Result<()> {
13    #[cfg(feature = "color")]
14    {
15        use colored_json::Styler;
16
17        let styler: Styler = color::Config::from_env().into();
18        match stdout().is_terminal() {
19            false => {
20                let mut stdout = stdout();
21                colored_json::ColoredFormatter::with_styler(
22                    serde_json::ser::CompactFormatter,
23                    styler,
24                )
25                .write_colored_json(value, &mut stdout, mode.into())?;
26
27                Ok(())
28            }
29            true => {
30                use std::io::Write as _;
31
32                let mut stdout = stdout();
33                colored_json::ColoredFormatter::with_styler(
34                    serde_json::ser::PrettyFormatter::new(),
35                    styler,
36                )
37                .write_colored_json(value, &mut stdout, mode.into())?;
38                writeln!(&mut stdout)?;
39
40                Ok(())
41            }
42        }
43    }
44
45    #[cfg(not(feature = "color"))]
46    match stdout().is_terminal() {
47        false => Ok(serde_json::to_writer(stdout(), value)?),
48        true => {
49            use std::io::Write as _;
50
51            let mut stdout = stdout();
52            serde_json::to_writer_pretty(&stdout, value)?;
53            writeln!(&mut stdout)?;
54
55            Ok(())
56        }
57    }
58}
59
60#[derive(Debug, Default)]
61pub enum ColorMode {
62    #[default]
63    Auto,
64    Always,
65    Never,
66}
67
68#[cfg(feature = "color")]
69impl From<ColorMode> for colored_json::ColorMode {
70    fn from(value: ColorMode) -> Self {
71        match value {
72            ColorMode::Always => Self::On,
73            ColorMode::Auto => Self::Auto(colored_json::Output::StdOut),
74            ColorMode::Never => Self::Off,
75        }
76    }
77}