Skip to content
Merged

Y2j #21

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
2 changes: 1 addition & 1 deletion build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ else {
}

$windows_projects = @("ntreg","ntstatuserror","ntuserinfo","registry")
$projects = @("config")
$projects = @("config","y2j")
if ($IsWindows) {
$projects += $windows_projects
}
Expand Down
9 changes: 9 additions & 0 deletions y2j/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "y2j"
version = "0.1.0"
edition = "2021"

[dependencies]
atty = { version = "0.2" }
serde_json = { version = "1.0", features = ["preserve_order"] }
serde_yaml = { version = "0.9" }
26 changes: 26 additions & 0 deletions y2j/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Y2J

Simple tool to convert YAML -> JSON -> YAML making it easier to read by a person.

## Input

This command has no parameters and takes input only via STDIN (as UTF-8).

If the input is JSON, then it outputs YAML.
If the input is YAML, then it outputs pretty JSON.

JSON input is expected to be a single JSON document.

## Example

Get the JSON schema for registry resource as YAML:

```powershell
registry schema | y2j
```

Convert back to JSON to get pretty print JSON:

```powershell
registry schema | y2j | y2j
```
45 changes: 45 additions & 0 deletions y2j/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use atty::Stream;
use std::{io::{self, Read}, process::exit};

const EXIT_SUCCESS: i32 = 0;
const EXIT_INVALID_INPUT: i32 = 1;

fn main() {
let input: String = if atty::is(Stream::Stdin) {
eprintln!("Error: Input JSON/YAML via STDIN is required.");
exit(EXIT_INVALID_INPUT);
} else {
let mut buffer: Vec<u8> = Vec::new();
io::stdin().read_to_end(&mut buffer).unwrap();
match String::from_utf8(buffer) {
Ok(input) => input,
Err(e) => {
eprintln!("Invalid UTF-8 sequence: {}", e);
exit(EXIT_INVALID_INPUT);
}
}
};

let mut is_json = true;
let input: serde_json::Value = match serde_json::from_str(&input) {
Ok(json) => json,
Err(_) => {
is_json = false;
match serde_yaml::from_str(&input) {
Ok(yaml) => yaml,
Err(err) => {
eprintln!("Error: Input is not valid JSON or YAML: {}", err);
exit(EXIT_INVALID_INPUT);
}
}
}
};

let output = match is_json {
true => serde_yaml::to_string(&input).unwrap(),
false => serde_json::to_string_pretty(&input).unwrap(),
};

println!("{}", output);
exit(EXIT_SUCCESS);
}