Skip to content

Commit

Permalink
other/dummy: add sample to handle options
Browse files Browse the repository at this point in the history
  • Loading branch information
Mingshen Sun committed Sep 1, 2018
1 parent 723dbb7 commit ecbe97d
Showing 1 changed file with 37 additions and 9 deletions.
46 changes: 37 additions & 9 deletions libmesabox/src/other/dummy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,35 @@ use {UtilSetup, ArgsIter, Result, UtilRead, UtilWrite};
const NAME: &str = "dummy";
pub const DESCRIPTION: &str = "A dummy utility to demonstrate the framework";

type DummyResult<T> = ::std::result::Result<T, DummyError>;

#[derive(Fail, Debug)]
enum DummyError {
#[fail(display = "something wrong")]
#[fail(display = "oh no, something wrong")]
SomethingWrong
}

type DummyResult<T> = ::std::result::Result<T, DummyError>;
struct DummyOptions {
verbose: bool
}

impl DummyOptions {
fn from_matches(matches: &ArgMatches) -> Self {
let mut options = Self::default();

options.verbose = matches.is_present("verbose");

options
}
}

impl Default for DummyOptions {
fn default() -> Self {
Self {
verbose: false
}
}
}

struct Dummyer<O>
where
Expand All @@ -36,18 +58,23 @@ where
Dummyer { output }
}

fn dummy(&mut self) -> DummyResult<()> {
writeln!(self.output, "write something to the output");
fn dummy(&mut self, options: &DummyOptions) -> DummyResult<()> {
if options.verbose {
writeln!(self.output, "Hello, world! This is a dummy utility. I am very verbose :)");
return Err(DummyError::SomethingWrong)?
} else {
writeln!(self.output, "Hello, world!");
}
Ok(())
}
}

fn create_app() -> App<'static, 'static> {
util_app!(NAME)
.arg(Arg::with_name("about")
.short("a")
.long("about")
.help("show about"))
.arg(Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Say hello in verbose mode"))
}

pub fn execute<S, T>(setup: &mut S, args: T) -> Result<()>
Expand All @@ -57,11 +84,12 @@ where
{
let app = create_app();
let matches = app.get_matches_from_safe(args)?;
let options = DummyOptions::from_matches(&matches);

let output = setup.output();
let mut output = output.lock()?;

let mut dummyer = Dummyer::new(output);
dummyer.dummy()?;
dummyer.dummy(&options)?;
Ok(())
}

0 comments on commit ecbe97d

Please sign in to comment.