From f93e5f6c4c45f8f6f1d032fb98091c46e0affc53 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 16:55:39 +0200 Subject: [PATCH] fix: parse first then add numbers from stdin #16 --- src/format.rs | 20 ++++++++++++++++++-- src/main.rs | 21 +++++++++++++++------ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/format.rs b/src/format.rs index 2f46b41..1534b33 100644 --- a/src/format.rs +++ b/src/format.rs @@ -68,10 +68,21 @@ pub struct FormatOptions { #[arg(short = 'z', long)] /// format to base32 base32: bool, - #[clap(value_parser=numf_parser::, required=true)] + #[clap(value_parser=numf_parser::, required=false)] /// at least one number that should be formatted /// - /// supports either base 10 or base 16 inputs (with 0xaaaa) + /// Any of the [Formats](Format::format) are supported, but the prefixes are needed for formats + /// other than decimal. + /// + /// Formats: + /// + /// - '0x' - Hexadecimal + /// - '0b' - Binary + /// - '0o' - Octal + /// - '0s' - Base64 + /// - '032s' - Base32 + /// + /// The numbers may be left empty at first, if numbers are provided with the stdin. numbers: Vec, } @@ -142,6 +153,11 @@ impl FormatOptions { pub fn set_prefix(&mut self, value: bool) { self.prefix = value; } + + /// manually add a number + pub fn push_number(&mut self, value: NumberType) { + self.numbers.push(value) + } } impl Default for FormatOptions { diff --git a/src/main.rs b/src/main.rs index 342c755..0588508 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,16 +6,15 @@ use std::io::Read; use std::process::exit; -use clap::Parser; +use clap::{CommandFactory, Parser}; mod format; use format::*; +use numf::format::numf_parser; fn main() { // try to read from stdin first, appending the numbers we read to the FormatOptions - let mut args: Vec = std::env::args_os() - .map(|x| x.into_string().unwrap()) - .collect(); + let mut options = FormatOptions::parse(); let mut stdin_nums = Vec::new(); match std::io::stdin().lock().read_to_end(&mut stdin_nums) { Ok(_) => { @@ -28,7 +27,14 @@ fn main() { }; let split = whole.split_whitespace(); for s in split { - args.push(s.to_string()); + let number = match numf_parser(s) { + Ok(n) => n, + Err(e) => { + eprintln!("could not parse number from stdin: {e:#?}"); + exit(2); + } + }; + options.push_number(number) } } Err(e) => { @@ -37,7 +43,10 @@ fn main() { } }; - let options = FormatOptions::parse_from(args); + if options.numbers().is_empty() { + format!("{}", FormatOptions::command().render_usage()); + exit(1); + } let mut out: Vec = Vec::new();