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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
use std::cell::RefCell;
use anyhow::Result;
use gag::Gag;
use promkit::{
crossterm::{
event::Event,
style::{Attribute, Attributes, Color, ContentStyle},
},
json::{self, JsonNode, JsonPathSegment, JsonStream},
listbox,
pane::Pane,
serde_json::{self, Deserializer},
snapshot::Snapshot,
style::StyleBuilder,
suggest::Suggest,
switch::ActiveKeySwitcher,
text, text_editor, PaneFactory, Prompt, PromptSignal,
};
use crate::trie::FilterTrie;
mod keymap;
/// Deserializes a JSON string into a vector of `serde_json::Value`.
///
/// This function takes a JSON string as input and attempts to parse it into a vector
/// of `serde_json::Value`, which represents any valid JSON value (e.g., object, array, string, number).
/// It leverages `serde_json::Deserializer` to parse the string and collect the results.
///
/// # Arguments
/// * `json_str` - A string slice that holds the JSON data to be deserialized.
///
/// # Returns
/// An `anyhow::Result` wrapping a vector of `serde_json::Value`. On success, it contains the parsed
/// JSON data. On failure, it contains an error detailing what went wrong during parsing.
fn deserialize_json(
json_str: &str,
limit_length: Option<usize>,
) -> anyhow::Result<Vec<serde_json::Value>> {
let deserializer = Deserializer::from_str(json_str).into_iter::<serde_json::Value>();
let results = match limit_length {
Some(l) => deserializer.take(l).collect::<Result<Vec<_>, _>>(),
None => deserializer.collect::<Result<Vec<_>, _>>(),
};
results.map_err(anyhow::Error::from)
}
fn run_jq(query: &str, json_stream: &[serde_json::Value]) -> anyhow::Result<Vec<String>> {
// libjq writes to the console when an internal error occurs.
//
// e.g.
// ```
// let _ = j9::run(". | select(.number == invalid_no_quote)", "{}");
// jq: error: invalid_no_quote/0 is not defined at <top-level>, line 1:
// . | select(.number == invalid_no_quote)
// ```
//
// While errors themselves are not an issue,
// they interfere with the console output handling mechanism
// in promkit and qjq (e.g., causing line numbers to shift).
// Therefore, we'll ignore console output produced inside j9::run.
//
// It's possible that this could be handled
// within github.com/ynqa/j9, but for now,
// we'll proceed with this workaround.
//
// For reference, the functionality of a quiet mode in libjq is
// also being discussed at https://github.com/jqlang/jq/issues/1225.
let ignore_err = Gag::stderr().unwrap();
let mut jq_ret = Vec::<String>::new();
for v in json_stream.iter() {
let inner_ret: Vec<String> = match j9::run(query, &v.to_string()) {
Ok(ret) => ret,
Err(e) => {
return Err(anyhow::anyhow!(e));
}
};
jq_ret.extend(inner_ret);
}
drop(ignore_err);
Ok(jq_ret)
}
pub struct JsonTheme {
/// Style for {}.
pub curly_brackets_style: ContentStyle,
/// Style for [].
pub square_brackets_style: ContentStyle,
/// Style for "key".
pub key_style: ContentStyle,
/// Style for string values.
pub string_value_style: ContentStyle,
/// Style for number values.
pub number_value_style: ContentStyle,
/// Style for boolean values.
pub boolean_value_style: ContentStyle,
/// Style for null values.
pub null_value_style: ContentStyle,
/// Attribute for the selected line.
pub active_item_attribute: Attribute,
/// Attribute for unselected lines.
pub inactive_item_attribute: Attribute,
/// Number of lines available for rendering.
pub lines: Option<usize>,
/// The number of spaces used for indentation in the rendered JSON structure.
/// This value multiplies with the indentation level of a JSON element to determine
/// the total indentation space. For example, an `indent` value of 4 means each
/// indentation level will be 4 spaces wide.
pub indent: usize,
}
pub struct Jnv {
input_stream: Vec<serde_json::Value>,
// Keybindings
keymap: RefCell<ActiveKeySwitcher<keymap::Keymap>>,
// For Rendering
filter_editor: Snapshot<text_editor::State>,
hint_message: Snapshot<text::State>,
suggestions: listbox::State,
json: json::State,
// Store the filter history
trie: FilterTrie,
// Store the filter suggestions
suggest: Suggest,
json_expand_depth: Option<usize>,
json_limit_length: Option<usize>,
no_hint: bool,
}
impl Jnv {
#[allow(clippy::too_many_arguments)]
pub fn try_new(
input: String,
filter_editor: text_editor::State,
hint_message: text::State,
suggestions: listbox::State,
json_theme: JsonTheme,
json_expand_depth: Option<usize>,
json_limit_length: Option<usize>,
no_hint: bool,
) -> Result<Prompt<Self>> {
let input_stream = deserialize_json(&input, json_limit_length)?;
let mut trie = FilterTrie::default();
trie.insert(".", input_stream.clone());
let all_kinds = JsonStream::new(input_stream.clone(), None).flatten_kinds();
let suggest = Suggest::from_iter(all_kinds.iter().filter_map(|kind| kind.path()).map(
|segments| {
if segments.is_empty() {
".".to_string()
} else {
segments
.iter()
.enumerate()
.map(|(i, segment)| match segment {
JsonPathSegment::Key(key) => {
if key.contains('.') || key.contains('-') || key.contains('@') {
format!(".\"{}\"", key)
} else {
format!(".{}", key)
}
}
JsonPathSegment::Index(index) => {
if i == 0 {
format!(".[{}]", index)
} else {
format!("[{}]", index)
}
}
})
.collect::<String>()
}
},
));
Ok(Prompt {
renderer: Self {
keymap: RefCell::new(
ActiveKeySwitcher::new("default", self::keymap::default as keymap::Keymap)
.register("on_suggest", self::keymap::on_suggest),
),
filter_editor: Snapshot::<text_editor::State>::new(filter_editor),
hint_message: Snapshot::<text::State>::new(hint_message),
suggestions,
json: json::State {
stream: JsonStream::new(input_stream.clone(), json_expand_depth),
curly_brackets_style: json_theme.curly_brackets_style,
square_brackets_style: json_theme.square_brackets_style,
key_style: json_theme.key_style,
string_value_style: json_theme.string_value_style,
number_value_style: json_theme.number_value_style,
boolean_value_style: json_theme.boolean_value_style,
null_value_style: json_theme.null_value_style,
active_item_attribute: json_theme.active_item_attribute,
inactive_item_attribute: json_theme.inactive_item_attribute,
lines: json_theme.lines,
indent: json_theme.indent,
},
trie,
suggest,
json_expand_depth,
json_limit_length,
no_hint,
input_stream,
},
})
}
fn update_hint_message(&mut self, text: String, style: ContentStyle) {
if !self.no_hint {
self.hint_message
.after_mut()
.replace(text::State { text, style })
}
}
}
impl promkit::Finalizer for Jnv {
type Return = String;
fn finalize(&self) -> anyhow::Result<Self::Return> {
Ok(self
.filter_editor
.after()
.texteditor
.text_without_cursor()
.to_string())
}
}
impl promkit::Renderer for Jnv {
fn create_panes(&self, width: u16, height: u16) -> Vec<Pane> {
vec![
self.filter_editor.create_pane(width, height),
self.hint_message.create_pane(width, height),
self.suggestions.create_pane(width, height),
self.json.create_pane(width, height),
]
}
fn evaluate(&mut self, event: &Event) -> anyhow::Result<PromptSignal> {
let keymap = *self.keymap.borrow_mut().get();
let signal = keymap(event, self);
let filter = self
.filter_editor
.after()
.texteditor
.text_without_cursor()
.to_string();
// Check if the query has changed
if filter
!= self
.filter_editor
.borrow_before()
.texteditor
.text_without_cursor()
.to_string()
{
self.hint_message.reset_after_to_init();
match self.trie.exact_search(&filter) {
Some(jsonl) => {
self.json.stream = JsonStream::new(jsonl.clone(), self.json_expand_depth);
self.update_hint_message(
format!(
"JSON query ('{}') was already executed. Result was retrieved from cache.",
&filter
),
StyleBuilder::new()
.fgc(Color::DarkGrey)
.attrs(Attributes::from(Attribute::Bold))
.build(),
);
}
None => {
match run_jq(&filter, &self.input_stream) {
Ok(ret) => {
if ret.is_empty() {
self.update_hint_message(
format!(
"JSON query ('{}') was executed, but no results were returned.",
&filter
),
StyleBuilder::new()
.fgc(Color::Red)
.attrs(Attributes::from(Attribute::Bold))
.build(),
);
if let Some(searched) = self.trie.prefix_search(&filter) {
self.json.stream =
JsonStream::new(searched.clone(), self.json_expand_depth);
}
} else {
match deserialize_json(&ret.join("\n"), self.json_limit_length) {
Ok(jsonl) => {
let stream =
JsonStream::new(jsonl.clone(), self.json_expand_depth);
let is_null = stream.roots().iter().all(|node| {
node == &JsonNode::Leaf(serde_json::Value::Null)
});
if is_null {
self.update_hint_message(
format!("JSON query resulted in 'null', which may indicate a typo or incorrect query: '{}'", &filter),
StyleBuilder::new()
.fgc(Color::Yellow)
.attrs(Attributes::from(Attribute::Bold))
.build(),
);
if let Some(searched) = self.trie.prefix_search(&filter)
{
self.json.stream = JsonStream::new(
searched.clone(),
self.json_expand_depth,
);
}
} else {
// SUCCESS!
self.trie.insert(&filter, jsonl);
self.json.stream = stream;
}
}
Err(e) => {
self.update_hint_message(
format!(
"Failed to parse query result for viewing: {}",
e
),
StyleBuilder::new()
.fgc(Color::Red)
.attrs(Attributes::from(Attribute::Bold))
.build(),
);
if let Some(searched) = self.trie.prefix_search(&filter) {
self.json.stream = JsonStream::new(
searched.clone(),
self.json_expand_depth,
);
}
}
}
}
}
Err(_) => {
self.update_hint_message(
format!("Failed to execute jq query '{}'", &filter),
StyleBuilder::new()
.fgc(Color::Red)
.attrs(Attributes::from(Attribute::Bold))
.build(),
);
if let Some(searched) = self.trie.prefix_search(&filter) {
self.json.stream =
JsonStream::new(searched.clone(), self.json_expand_depth);
}
return signal;
}
}
}
}
}
signal
}
}