use std ::{ fmt , error } ;
pub fn prog_name ( ) -> & ' static str
{
lazy_static ! {
static ref NAME : String = std ::env ::args ( ) . next ( ) . unwrap ( ) ;
}
& NAME [ .. ]
}
/// Print usage then exit with error code `0`.
pub fn usage ( ) -> !
{
println! ( "Unit conversion v{}" , env! ( "CARGO_PKG_VERSION" ) ) ;
println! ( " by {} with <3 (license GPL3+)" , env! ( "CARGO_PKG_AUTHORS" ) ) ;
println! ( ) ;
println! ( "This program takes a value with a unit and outputs the smallest value corresponding to that type to `stdout`. It then outputs the multiplyer used to convert this unit to `stderr`, if there is one needed." ) ;
println! ( ) ;
println! ( "usage: {} <unit> <value>" , prog_name ( ) ) ;
println! ( "usage: {} --help" , prog_name ( ) ) ;
println! ( ) ;
//TODO: generalise units
println! ( r #" Units :
BYTES Convert byte unit ( k , m , g , p ) into single bytes " #) ;
std ::process ::exit ( 0 )
}
#[ derive(Debug, Clone, PartialEq, Eq, Hash) ]
pub enum Operation
{
Help ,
Convert ( String , String ) ,
}
#[ inline ] pub fn parse_args ( ) -> Result < Operation , ArgParseError >
{
parse ( std ::env ::args ( ) . skip ( 1 ) )
}
fn parse < T : Into < String > > ( from : impl IntoIterator < Item = T > ) -> Result < Operation , ArgParseError >
{
let mut from = from . into_iter ( ) . map ( Into ::into ) ;
let first = from . next ( ) . ok_or ( ArgParseError ) ? ;
match first . to_lowercase ( ) . trim ( ) {
"--help" = > Ok ( Operation ::Help ) ,
_ = > {
Ok ( Operation ::Convert ( first , from . next ( ) . ok_or ( ArgParseError ) ? ) )
} ,
}
}
#[ derive(Debug) ]
pub struct ArgParseError ;
impl error ::Error for ArgParseError { }
impl fmt ::Display for ArgParseError
{
fn fmt ( & self , f : & mut fmt ::Formatter < ' _ > ) -> fmt ::Result
{
write! ( f , "Failed to parse args. Try passing `--help`." )
}
}