-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathjson.rs
More file actions
87 lines (76 loc) · 2.25 KB
/
Copy pathjson.rs
File metadata and controls
87 lines (76 loc) · 2.25 KB
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
use std::{
fs::File,
io::{self, Read},
path::PathBuf,
};
use clap::Parser;
use promkit::{
core::crossterm::{event, execute, terminal},
preset::json::Json,
widgets::{
json::{config::OverflowMode, Document},
serde_json::{self, Deserializer, Value},
},
Prompt,
};
/// Interactive JSON viewer powered by promkit.
#[derive(Debug, Parser)]
#[command(name = "json", version)]
struct Args {
/// Optional path to a JSON file. Reads from stdin when omitted or when "-" is specified.
input: Option<PathBuf>,
}
/// Read JSON input from a file or stdin based on the provided arguments.
fn parse_input(args: &Args) -> anyhow::Result<String> {
let mut input = String::new();
match &args.input {
None => {
io::stdin().read_to_string(&mut input)?;
}
Some(path) if path == &PathBuf::from("-") => {
io::stdin().read_to_string(&mut input)?;
}
Some(path) => {
File::open(path)?.read_to_string(&mut input)?;
}
}
Ok(input)
}
/// Parse a JSON string into a vector of serde_json::Value,
/// allowing for multiple JSON objects in the input.
fn parse_json_values(input: &str) -> anyhow::Result<Vec<Value>> {
let deserializer: serde_json::StreamDeserializer<'_, serde_json::de::StrRead<'_>, Value> =
Deserializer::from_str(input).into_iter::<Value>();
deserializer
.collect::<Result<Vec<_>, _>>()
.map_err(anyhow::Error::from)
}
/// Ensure the terminal is restored to its original state when dropped.
struct TerminalGuard;
impl Drop for TerminalGuard {
fn drop(&mut self) {
let _ = execute!(
io::stdout(),
terminal::LeaveAlternateScreen,
event::DisableMouseCapture
);
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args = Args::parse();
let input = parse_input(&args)?;
let values = parse_json_values(&input)?;
execute!(
io::stdout(),
terminal::EnterAlternateScreen,
event::EnableMouseCapture
)?;
let _terminal_guard = TerminalGuard;
let document = Document::new(values.iter());
Json::new(document)
.title("JSON Viewer")
.overflow_mode(OverflowMode::Wrap)
.run()
.await
}