From 09b370854b00d9b3410b370ca3839d5b322a74e8 Mon Sep 17 00:00:00 2001 From: Scott Anderson Date: Sun, 21 Jan 2024 17:32:50 -0500 Subject: [PATCH] Command-line type hint arguments (#4) --- src/bin/gvas2json.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/bin/gvas2json.rs b/src/bin/gvas2json.rs index 09c7339..461358a 100644 --- a/src/bin/gvas2json.rs +++ b/src/bin/gvas2json.rs @@ -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}; @@ -17,6 +18,10 @@ struct Args { #[clap(short, long, id = "OUTPUT_FILE")] output: Option, + /// Type hints as key-value pairs. + #[clap(short = 't', long = "type")] + types: Vec, + /// Pretty-print JSON output. #[clap(short, long, id = "PRETTY", default_value_t = true)] pretty: bool, @@ -30,6 +35,18 @@ struct Args { no_pager: bool, } +fn parse_types(args: Vec) -> HashMap { + let mut result = HashMap::::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. @@ -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 @@ -99,14 +119,14 @@ fn format_json(gvas: &GvasFile, color_mode: ColorMode, pretty: bool) -> Result(input: R) -> Result { +fn from_reader(input: R, types: &HashMap) -> Result { 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(writer: W, output: &[u8]) -> Result<()> {