From a0a864a12944abec3251ad88768db1d5b9192d8f Mon Sep 17 00:00:00 2001 From: Kareem Medhat Date: Sun, 17 Apr 2022 13:07:43 +0200 Subject: [PATCH] feat(main.rs)!: Read from stdin in absence of path argument Added ability to read from stdin by: - Moving path argument to be last positional argument - Setting path argument as optional to allow reading from stdin BREAKING CHANGE --- src/main.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1c644fa..1d2b698 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod query_parser; use std::fs; +use std::io::{self, Read}; use std::path::PathBuf; use std::str; @@ -17,11 +18,11 @@ use query_parser::{Query, TpathSegment, parse_query}; enum Args { /// Print some data from the file Get { - /// Path to the TOML file to read - #[structopt(parse(from_os_str))] - path: PathBuf, /// Query within the TOML data (e.g. `dependencies.serde`, `foo[0].bar`) query: String, + /// Path to the TOML file to read + #[structopt(parse(from_os_str))] + path: Option, #[structopt(flatten)] opts: GetOpts, }, @@ -71,9 +72,17 @@ fn read_parse(path: PathBuf) -> Result { Ok(data.parse::()?) } -fn get(path: PathBuf, query: &str, opts: GetOpts) -> Result<(), Error> { +fn get(path: Option, query: &str, opts: GetOpts) -> Result<(), Error> { let tpath = parse_query_cli(query)?.0; - let doc = read_parse(path)?; + let doc: Document = match path { + Some(path) => read_parse(path)?, + None => { + let mut buf: Vec = vec![]; + io::stdin().read_to_end(&mut buf)?; + let data = str::from_utf8(&buf)?; + data.parse::()? + } + }; if opts.output_toml { print_toml_fragment(&doc, &tpath);