Skip to content

Commit 201764c

Browse files
author
Mingshen Sun
committed
other/dummy: add sample to handle options
1 parent 723dbb7 commit 201764c

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

libmesabox/src/other/dummy.rs

+37-9
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,35 @@ use {UtilSetup, ArgsIter, Result, UtilRead, UtilWrite};
1313
const NAME: &str = "dummy";
1414
pub const DESCRIPTION: &str = "A dummy utility to demonstrate the framework";
1515

16+
type DummyResult<T> = ::std::result::Result<T, DummyError>;
17+
1618
#[derive(Fail, Debug)]
1719
enum DummyError {
18-
#[fail(display = "something wrong")]
20+
#[fail(display = "oh no, something wrong")]
1921
SomethingWrong
2022
}
2123

22-
type DummyResult<T> = ::std::result::Result<T, DummyError>;
24+
struct DummyOptions {
25+
verbose: bool
26+
}
27+
28+
impl DummyOptions {
29+
fn from_matches(matches: &ArgMatches) -> Self {
30+
let mut options = Self::default();
31+
32+
options.verbose = matches.is_present("verbose");
33+
34+
options
35+
}
36+
}
37+
38+
impl Default for DummyOptions {
39+
fn default() -> Self {
40+
Self {
41+
verbose: false
42+
}
43+
}
44+
}
2345

2446
struct Dummyer<O>
2547
where
@@ -36,18 +58,23 @@ where
3658
Dummyer { output }
3759
}
3860

39-
fn dummy(&mut self) -> DummyResult<()> {
40-
writeln!(self.output, "write something to the output");
61+
fn dummy(&mut self, options: &DummyOptions) -> DummyResult<()> {
62+
if options.verbose {
63+
writeln!(self.output, "Hello, world! This is a dummy utility. I am very verbose :)");
64+
return Err(DummyError::SomethingWrong)
65+
} else {
66+
writeln!(self.output, "Hello, world!");
67+
}
4168
Ok(())
4269
}
4370
}
4471

4572
fn create_app() -> App<'static, 'static> {
4673
util_app!(NAME)
47-
.arg(Arg::with_name("about")
48-
.short("a")
49-
.long("about")
50-
.help("show about"))
74+
.arg(Arg::with_name("verbose")
75+
.short("v")
76+
.long("verbose")
77+
.help("Say hello in verbose mode"))
5178
}
5279

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

6189
let output = setup.output();
6290
let mut output = output.lock()?;
6391

6492
let mut dummyer = Dummyer::new(output);
65-
dummyer.dummy()?;
93+
dummyer.dummy(&options)?;
6694
Ok(())
6795
}

0 commit comments

Comments
 (0)