1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#![forbid(rust_2018_idioms)]
#![deny(unsafe_code, nonstandard_style)]
mod cli;
use jql::walker;
use anyhow::Result;
use async_std::{fs, io, path::Path, prelude::*, process::exit, task};
use clap::ArgMatches;
use colored_json::{ColoredFormatter, CompactFormatter, PrettyFormatter};
use serde_json::{Deserializer, Value};
/// Try to serialize the raw JSON content, output the selection or throw an
/// error.
fn render_output(json_content: &str, cli: &ArgMatches<'_>) {
    let inline = cli.is_present("inline");
    let raw_output = cli.is_present("raw-output");
    let selectors = cli.value_of("selectors");
    Deserializer::from_str(json_content)
        .into_iter::<Value>()
        .for_each(|value| match value {
            Ok(valid_json) => {
                // Walk through the JSON content with the provided selectors as
                // input.
                match walker(&valid_json, selectors) {
                    Ok(selection) => println!(
                        "{}",
                        // Inline or pretty output.
                        (if inline {
                            ColoredFormatter::new(CompactFormatter {})
                                .to_colored_json_auto(&selection)
                                .unwrap()
                        } else {
                            // If the selection is a string and the raw-output
                            // flag is passed, directly return the raw string
                            // without JSON double-quotes.
                            // https://github.com/serde-rs/json/issues/367
                            if raw_output && selection.is_string() {
                                String::from(selection.as_str().unwrap())
                            } else {
                                ColoredFormatter::new(PrettyFormatter::new())
                                    .to_colored_json_auto(&selection)
                                    .unwrap()
                            }
                        })
                    ),
                    Err(error) => {
                        eprintln!("{}", error);
                        exit(1);
                    }
                }
            }
            Err(_) => {
                eprintln!("Invalid JSON file or content");
                exit(1);
            }
        });
}
#[async_std::main]
async fn main() -> Result<()> {
    let cli = cli::get_matches();
    match cli.value_of("JSON") {
        // JSON content coming from the CLI.
        Some(json) => {
            let path = Path::new(json);
            let contents = fs::read_to_string(path).await?;
            render_output(&contents, &cli);
            Ok(())
        }
        // JSON content coming from stdin.
        None => {
            let stream = cli.is_present("stream");
            task::block_on(async {
                let stdin = io::stdin();
                let mut stdout = io::stdout();
                let mut line = String::new();
                loop {
                    // Read a line from stdin.
                    let n = stdin.read_line(&mut line).await?;
                    // Check for the EOF.
                    if n == 0 {
                        // Render the output for the general case.
                        if !stream {
                            render_output(&line, &cli);
                        }
                        return Ok(());
                    }
                    // Render every line for the stream option.
                    if stream {
                        render_output(&line, &cli);
                        stdout.flush().await?;
                        line.clear();
                    }
                }
            })
        }
    }
}