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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use crate::App;

use anyhow::{anyhow, bail};
use clap::Args;
use codespan_reporting::files::SimpleFile;
use jsona::{
    dom::{DomNode, Keys, Node},
    parser,
};
use jsona_util::environment::Environment;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};

impl<E: Environment> App<E> {
    pub async fn execute_get(&self, cmd: GetCommand) -> Result<(), anyhow::Error> {
        let mut stdout = self.env.stdout();

        let source = match &cmd.file_path {
            Some(p) => {
                let (_, source) = self.load_file(p).await?;
                source
            }
            None => {
                let mut stdin = self.env.stdin();
                let mut s = String::new();
                stdin.read_to_string(&mut s).await?;
                s
            }
        };

        let parse = parser::parse(&source);

        let file_path = cmd.file_path.as_deref().unwrap_or("-");

        self.print_parse_errors(&SimpleFile::new(file_path, &source), &parse.errors)
            .await?;

        if !parse.errors.is_empty() {
            return Err(anyhow!("syntax errors found"));
        }

        let node = parse.into_dom();

        if let Err(errors) = node.validate() {
            self.print_semantic_errors(&SimpleFile::new(file_path, &source), errors)
                .await?;

            return Err(anyhow!("semantic errors found"));
        }

        let nodes = match cmd.pattern {
            Some(p) => {
                let p = p.trim_start_matches('.');

                let keys = p
                    .parse::<Keys>()
                    .map_err(|err| anyhow!("invalid pattern: {err}"))?;

                node.matches_all(keys, false)
                    .map_err(|err| anyhow!("invalid pattern: {err}"))?
                    .map(|(_, v)| v)
                    .collect()
            }
            None => vec![node],
        };
        let buf = {
            let items: Vec<Value> = if cmd.annotation {
                nodes.iter().map(to_json).collect()
            } else {
                nodes.iter().map(|v| v.to_plain_json()).collect()
            };
            let value = match items.len() {
                0 => {
                    bail!("no found");
                }
                1 => items[0].clone(),
                _ => Value::Array(items),
            };
            if let Some(value) = value.as_str() {
                value.as_bytes().to_vec()
            } else {
                serde_json::to_vec_pretty(&value).unwrap()
            }
        };
        stdout.write_all(&buf).await?;
        stdout.flush().await?;
        Ok(())
    }
}

#[derive(Debug, Clone, Args)]
pub struct GetCommand {
    /// Whether output includes annotation
    #[clap(short = 'A', long)]
    pub annotation: bool,

    /// Path to the JSONA document, if omitted the standard input will be used.
    #[clap(short, long)]
    pub file_path: Option<String>,

    /// A dotted key pattern to the value within the JSONA document.
    ///
    /// If omitted, the entire document will be printed.
    ///
    /// If the pattern yielded no values, the operation will fail.
    ///
    /// The pattern supports `jq`-like syntax and glob patterns as well:
    ///
    /// Examples:
    ///
    /// - table.array[1].foo
    /// - table.array.1.foo
    /// - table.array[*].foo
    /// - table.array.*.foo
    /// - dependencies.tokio-*.version
    ///
    pub pattern: Option<String>,
}

pub fn to_json(node: &Node) -> Value {
    let annotations = node.annotations().map(|a| {
        Value::Object(
            a.value()
                .read()
                .kv_iter()
                .map(|(k, v)| (k.to_string(), v.to_plain_json()))
                .collect(),
        )
    });
    match node {
        Node::Null(_) => match annotations {
            Some(annotations) => {
                json!({
                    "value": null,
                    "annotations": annotations
                })
            }
            None => {
                json!({
                    "value": null,
                })
            }
        },
        Node::Bool(v) => match annotations {
            Some(annotations) => {
                json!({
                    "value": v.value(),
                    "annotations": annotations
                })
            }
            None => {
                json!({
                    "value": v.value(),
                })
            }
        },
        Node::Number(v) => match annotations {
            Some(annotations) => {
                json!({
                    "value": v.value(),
                    "annotations": annotations
                })
            }
            None => {
                json!({
                    "value": v.value(),
                })
            }
        },
        Node::String(v) => match annotations {
            Some(annotations) => {
                json!({
                    "value": v.value(),
                    "annotations": annotations
                })
            }
            None => {
                json!({
                    "value": v.value(),
                })
            }
        },
        Node::Array(v) => {
            let value = Value::Array(v.value().read().iter().map(to_json).collect());
            match annotations {
                Some(annotations) => {
                    json!({
                        "value": value,
                        "annotations": annotations
                    })
                }
                None => {
                    json!({
                        "value": value,
                    })
                }
            }
        }
        Node::Object(v) => {
            let value = Value::Object(
                v.value()
                    .read()
                    .kv_iter()
                    .map(|(k, v)| (k.to_string(), to_json(v)))
                    .collect(),
            );
            match annotations {
                Some(annotations) => {
                    json!({
                        "value": value,
                        "annotations": annotations
                    })
                }
                None => {
                    json!({
                        "value": value,
                    })
                }
            }
        }
    }
}