| 1 | use std::io::{stdin, IsTerminal, Read}; |
| 2 | |
| 3 | use anyhow::Context; |
| 4 | use human_bytes::human_bytes; |
| 5 | use lexopt::prelude::*; |
| 6 | |
| 7 | const fn usage() -> &'static str { |
| 8 | "Usage: hb [options] <bytes> |
| 9 | -h, --help Print this help message |
| 10 | -V, --version Print version info" |
| 11 | } |
| 12 | |
| 13 | fn main() -> anyhow::Result<()> { |
| 14 | let mut bytes: Option<u64> = None; |
| 15 | |
| 16 | if stdin().is_terminal() { |
| 17 | let mut cli = lexopt::Parser::from_env(); |
| 18 | while let Some(arg) = cli.next()? { |
| 19 | match arg { |
| 20 | Value(val) if bytes.is_none() => { |
| 21 | bytes = Some(val.to_string_lossy().parse()?); |
| 22 | } |
| 23 | Short('h') | Long("help") => { |
| 24 | println!("{}", usage()); |
| 25 | std::process::exit(0); |
| 26 | } |
| 27 | Short('V') | Long("version") => { |
| 28 | println!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); |
| 29 | std::process::exit(0); |
| 30 | } |
| 31 | _ => return Err(arg.unexpected())?, |
| 32 | } |
| 33 | } |
| 34 | } else { |
| 35 | let mut tmp = String::new(); |
| 36 | std::io::stdin().read_to_string(&mut tmp)?; |
| 37 | bytes = Some(tmp.trim().parse()?); |
| 38 | } |
| 39 | |
| 40 | let bytes = bytes.context("missing <bytes> (see -h)")?; |
| 41 | println!("{}", human_bytes(bytes as f64)); |
| 42 | Ok(()) |
| 43 | } |