Skip to content

Commit

Permalink
If stdout is not a TTY, print pretty printed JSON to stdout and exit.
Browse files Browse the repository at this point in the history
  • Loading branch information
PaulJuliusMartinez committed Feb 6, 2022
1 parent 20d5252 commit 04bc1ac
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use termion::raw::IntoRawMode;
use termion::screen::AlternateScreen;

use jless::app::App;
use jless::flatjson::{parse_top_level_json2, Value};
use jless::input;
use jless::options::Opt;

Expand All @@ -19,11 +20,16 @@ fn main() {
let (json_string, input_filename) = match get_json_input(&opt) {
Ok(json_string) => json_string,
Err(err) => {
println!("Unable to get input: {}", err);
eprintln!("Unable to get input: {}", err);
std::process::exit(1);
}
};

if !isatty::stdout_isatty() {
print_pretty_printed_json(json_string);
std::process::exit(0);
}

let stdout = MouseTerminal::from(HideCursor::from(AlternateScreen::from(
io::stdout().into_raw_mode().unwrap(),
)));
Expand All @@ -38,6 +44,44 @@ fn main() {
app.run(Box::new(input::get_input()));
}

fn print_pretty_printed_json(json: String) {
let flatjson = match jless::flatjson::parse_top_level_json2(json) {
Ok(flatjson) => flatjson,
Err(err) => {
eprintln!("Unable to parse input: {:?}", err);
std::process::exit(1);
}
};

for row in flatjson.0.iter() {
for _ in 0..row.depth {
print!(" ");
}
if let Some(ref key_range) = row.key_range {
print!("{}: ", &flatjson.1[key_range.clone()]);
}
let mut trailing_comma = row.parent.is_some() && row.next_sibling.is_some();
if let Some(container_type) = row.value.container_type() {
if row.value.is_opening_of_container() {
print!("{}", container_type.open_str());
// Don't print trailing commas after { or [.
trailing_comma = false;
} else {
print!("{}", container_type.close_str());
// Check container opening to see if we have a next sibling.
trailing_comma = row.parent.is_some()
&& flatjson.0[row.pair_index().unwrap()].next_sibling.is_some();
}
} else {
print!("{}", &flatjson.1[row.range.clone()]);
}
if trailing_comma {
print!(",");
}
println!("");
}
}

fn get_json_input(opt: &Opt) -> io::Result<(String, String)> {
let mut json_string = String::new();
let filename;
Expand Down

0 comments on commit 04bc1ac

Please sign in to comment.