diff --git a/src/uucore/Cargo.toml b/src/uucore/Cargo.toml index aeab77705..1689c734e 100644 --- a/src/uucore/Cargo.toml +++ b/src/uucore/Cargo.toml @@ -6,6 +6,7 @@ authors = [] [dependencies] libc = "*" winapi = "*" +getopts = "*" data-encoding = "^1.1" [lib] diff --git a/src/uucore/coreopts.rs b/src/uucore/coreopts.rs new file mode 100644 index 000000000..fa2f31fc2 --- /dev/null +++ b/src/uucore/coreopts.rs @@ -0,0 +1,53 @@ +extern crate getopts; +use std::io::Write; + +pub struct CoreOptions { + pub options : getopts::Options, + longhelp : Option +} + +impl<'a> CoreOptions { + pub fn new() -> Self { + let mut ret = CoreOptions { + options : getopts::Options::new(), + longhelp : None + }; + ret.options + .optflag("", "help", "print usage information") + .optflag("", "version", "print name and version number"); + ret + } + pub fn optopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str) -> &mut CoreOptions { + self.options.optopt(short_name, long_name, desc, hint); + self + } + pub fn optflag(&mut self, short_name: &str, long_name: &str, desc: &str) -> &mut CoreOptions { + self.options.optflag(short_name, long_name, desc); + self + } + pub fn help>(&mut self, longhelp : T) -> &mut CoreOptions { + self.longhelp = Some(longhelp.into()); + self + } + pub fn usage(&self, summary : &str) -> String { + self.options.usage(summary) + } + pub fn parse(&mut self, args : Vec) -> getopts::Matches { + let matches = match self.options.parse(&args[1..]) { + Ok(m) => { Some(m) }, + Err(f) => { + crash!(1, "{}", msg_invalid_input!(format!("{}", f))); + } + }.unwrap(); + if matches.opt_present("help") { + exit!(match self.longhelp { + Some(ref lhelp) => { print!("{}", lhelp); 0} + None => 1 + }); + } else if matches.opt_present("version") { + print!("{}", msg_version!()); + exit!(0); + } + matches + } +} \ No newline at end of file diff --git a/src/uucore/lib.rs b/src/uucore/lib.rs index d61d93516..f3cd5bebc 100644 --- a/src/uucore/lib.rs +++ b/src/uucore/lib.rs @@ -8,6 +8,7 @@ pub mod fs; pub mod parse_time; pub mod utf8; pub mod encoding; +pub mod coreopts; #[cfg(unix)] pub mod c_types; #[cfg(unix)] pub mod process;