Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Command-line type hint arguments #4

Merged
merged 1 commit into from
Jan 21, 2024
Merged
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
28 changes: 24 additions & 4 deletions src/bin/gvas2json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use clap::{Parser, ValueEnum};
use colored_json::{ColorMode, Output};
use gvas::GvasFile;
use minus::Pager;
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, BufWriter, Cursor, Read, Write};

Expand All @@ -17,6 +18,10 @@ struct Args {
#[clap(short, long, id = "OUTPUT_FILE")]
output: Option<String>,

/// Type hints as key-value pairs.
#[clap(short = 't', long = "type")]
types: Vec<String>,

/// Pretty-print JSON output.
#[clap(short, long, id = "PRETTY", default_value_t = true)]
pretty: bool,
Expand All @@ -30,6 +35,18 @@ struct Args {
no_pager: bool,
}

fn parse_types(args: Vec<String>) -> HashMap<String, String> {
let mut result = HashMap::<String, String>::new();
for arg in args {
let parts: Vec<&str> = arg.split('=').collect();
assert_eq!(parts.len(), 2, "Hint should be in the format key=value");
let k = String::from(parts[0]);
let v = String::from(parts[1]);
result.insert(k, v);
}
result
}

#[derive(ValueEnum, Clone, Debug)]
enum WhenValues {
/// Always show colored output.
Expand Down Expand Up @@ -60,10 +77,13 @@ fn main() -> Result<()> {
WhenValues::Never => ColorMode::Off,
};

// Parse type hint arguments
let types = parse_types(args.types);

// Read from input
let gvas = match args.input {
None => from_reader(std::io::stdin()),
Some(input) => from_reader(File::open(input)?),
None => from_reader(std::io::stdin(), &types),
Some(input) => from_reader(File::open(input)?, &types),
}?;

// Transcode the data
Expand Down Expand Up @@ -99,14 +119,14 @@ fn format_json(gvas: &GvasFile, color_mode: ColorMode, pretty: bool) -> Result<S
Ok(json)
}

fn from_reader<R: Read>(input: R) -> Result<GvasFile> {
fn from_reader<R: Read>(input: R, types: &HashMap<String, String>) -> Result<GvasFile> {
let mut input = BufReader::new(input);
// WORKAROUND: GvasFile requires Seek attribute
let mut buf = Vec::new();
input.read_to_end(&mut buf)?;
let mut input = Cursor::new(buf);
// END WORKAROUND
Ok(GvasFile::read(&mut input)?)
Ok(GvasFile::read_with_hints(&mut input, types)?)
}

fn to_writer<W: Write>(writer: W, output: &[u8]) -> Result<()> {
Expand Down
Loading