Skip to main content

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