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 crate::ColorMode;
7use serde::Serialize;
8use std::io::{stdout, IsTerminal as _};
9
10pub fn print<T: Serialize>(
11    value: &T,
12    #[allow(unused_variables)] mode: ColorMode,
13) -> crate::Result<()> {
14    #[cfg(feature = "color")]
15    {
16        use colored_json::Styler;
17
18        let styler: Styler = color::Config::from_env().into();
19        match stdout().is_terminal() {
20            false => {
21                let mut stdout = stdout();
22                colored_json::ColoredFormatter::with_styler(
23                    serde_json::ser::CompactFormatter,
24                    styler,
25                )
26                .write_colored_json(value, &mut stdout, mode.into())?;
27
28                Ok(())
29            }
30            true => {
31                use std::io::Write as _;
32
33                let mut stdout = stdout();
34                colored_json::ColoredFormatter::with_styler(
35                    serde_json::ser::PrettyFormatter::new(),
36                    styler,
37                )
38                .write_colored_json(value, &mut stdout, mode.into())?;
39                writeln!(&mut stdout)?;
40
41                Ok(())
42            }
43        }
44    }
45
46    #[cfg(not(feature = "color"))]
47    match stdout().is_terminal() {
48        false => Ok(serde_json::to_writer(stdout(), value)?),
49        true => {
50            use std::io::Write as _;
51
52            let mut stdout = stdout();
53            serde_json::to_writer_pretty(&stdout, value)?;
54            writeln!(&mut stdout)?;
55
56            Ok(())
57        }
58    }
59}
60
61#[cfg(feature = "color")]
62impl From<ColorMode> for colored_json::ColorMode {
63    fn from(value: ColorMode) -> Self {
64        match value {
65            ColorMode::Always => Self::On,
66            ColorMode::Auto => Self::Auto(colored_json::Output::StdOut),
67            ColorMode::Never => Self::Off,
68        }
69    }
70}