Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions y2j/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ edition = "2021"
atty = { version = "0.2" }
serde_json = { version = "1.0", features = ["preserve_order"] }
serde_yaml = { version = "0.9" }
syntect = { version = "5.0", features = ["default-fancy"], default-features = false }
25 changes: 24 additions & 1 deletion y2j/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
use atty::Stream;
use std::{io::{self, Read}, process::exit};
use syntect::easy::HighlightLines;
use syntect::parsing::SyntaxSet;
use syntect::highlighting::{ThemeSet, Style};
use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};

const EXIT_SUCCESS: i32 = 0;
const EXIT_INVALID_INPUT: i32 = 1;
Expand Down Expand Up @@ -40,6 +44,25 @@ fn main() {
false => serde_json::to_string_pretty(&input).unwrap(),
};

println!("{}", output);
// if stdout is not redirected, print with syntax highlighting
if atty::is(Stream::Stdout) {
let ps = SyntaxSet::load_defaults_newlines();
let ts = ThemeSet::load_defaults();
let syntax = match is_json {
true => ps.find_syntax_by_extension("json").unwrap(),
false => ps.find_syntax_by_extension("yaml").unwrap(),
};

let mut h = HighlightLines::new(syntax, &ts.themes["base16-ocean.dark"]);

for line in LinesWithEndings::from(output.as_str()) {
let ranges: Vec<(Style, &str)> = h.highlight_line(line, &ps).unwrap();
let escaped = as_24_bit_terminal_escaped(&ranges[..], true);
print!("{}", escaped);
}
} else {
println!("{}", output);
}

exit(EXIT_SUCCESS);
}