1use std::io::{BufWriter, Write};
2
3use clap::{Args, ColorChoice, ValueEnum};
4use gq_core::data::{format, DataType};
5use serde_json::Value;
6
7use self::output_format::OutputFormat;
8
9pub mod output_format;
10
11#[derive(Debug, Clone, ValueEnum)]
12pub enum OutputType {
13 Match,
14 Json,
15 Yaml,
16}
17
18impl OutputType {
19 pub fn into_data_type(self, original_data_type: DataType) -> DataType {
20 match self {
21 OutputType::Match => original_data_type,
22 OutputType::Json => DataType::Json,
23 OutputType::Yaml => DataType::Yaml,
24 }
25 }
26}
27
28#[derive(Debug, Args)]
29pub struct Output {
30 #[clap(long, short, value_parser, default_value = "-")]
32 pub output: clio::Output,
33 #[clap(long, default_value_t = OutputType::Match)]
34 #[arg(value_enum)]
35 pub output_type: OutputType,
36 #[clap(flatten)]
37 pub output_format: OutputFormat,
38}
39
40impl Output {
41 pub fn write_value(self, value: &Value, original_type: DataType) -> format::Result<()> {
42 let color = &self.output_format.color;
43 let indentation = self.output_format.indentation();
44 let output_type = self.output_type.into_data_type(original_type);
45 let is_tty = self.output.is_tty();
46 let mut buf_writer = BufWriter::new(self.output);
47
48 match color {
49 ColorChoice::Auto => {
50 if is_tty {
51 output_type.pretty_format_colored_to_writer(
52 &mut buf_writer,
53 value,
54 indentation,
55 )?
56 } else {
57 output_type.pretty_format_to_writer(&mut buf_writer, value, indentation)?
58 }
59 }
60 ColorChoice::Always => {
61 output_type.pretty_format_colored_to_writer(&mut buf_writer, value, indentation)?
62 }
63 ColorChoice::Never => {
64 output_type.pretty_format_to_writer(&mut buf_writer, value, indentation)?
65 }
66 };
67
68 if is_tty {
69 buf_writer.write_all(b"\n")?
70 };
71 Ok(())
72 }
73}