diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..41bbbc7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "buildrs" +version = "0.1.0" +authors = ["Hatter Jiang "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +clap = "2.33.1" diff --git a/src/cmd.rs b/src/cmd.rs new file mode 100644 index 0000000..7b40197 --- /dev/null +++ b/src/cmd.rs @@ -0,0 +1,12 @@ +use clap::{ ArgMatches, App, }; + +pub type CommandError = Result<(), Box>; + +pub trait Command { + + fn subcommand<'a>(&self) -> App<'a, 'a>; + + fn name(&self) -> &str; + + fn run(&self, arg_matches: &ArgMatches, _: &ArgMatches) -> CommandError; +} diff --git a/src/cmd_default.rs b/src/cmd_default.rs new file mode 100644 index 0000000..fd5c96f --- /dev/null +++ b/src/cmd_default.rs @@ -0,0 +1,23 @@ +use clap::{ App, Arg, ArgMatches, }; +use crate::cmd::CommandError; + +pub struct CommandDefault; + +impl CommandDefault { + + pub fn process_command<'a>(app: App<'a, 'a>) -> App<'a, 'a> { + app.arg(Arg::with_name("verbose") + .long("verbose") + .short("v") + .multiple(true) + .help("Show verbose info") + ) + } + + pub fn run(arg_matches: &ArgMatches) -> CommandError { + let verbose_count = arg_matches.occurrences_of("verbose"); + println!("Verbose count: {}", verbose_count); + // TODO ... + Ok(()) + } +} \ No newline at end of file diff --git a/src/cmd_sample.rs b/src/cmd_sample.rs new file mode 100644 index 0000000..b1bd812 --- /dev/null +++ b/src/cmd_sample.rs @@ -0,0 +1,20 @@ +use clap::{ ArgMatches, SubCommand, App, }; +use crate::cmd::{ Command, CommandError, }; + +pub struct CommandSample; + +impl Command for CommandSample { + + fn subcommand<'a>(&self) -> App<'a, 'a> { + SubCommand::with_name(self.name()).about("Sample subcommand") + } + + fn name(&self) -> &str { + "sample" + } + + fn run(&self, _arg_matches: &ArgMatches, _sub_arg_matches: &ArgMatches) -> CommandError { + println!("This is test command!"); + Ok(()) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..ec50fe9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,31 @@ +use clap::App; + +mod cmd; +mod cmd_sample; +mod cmd_default; + +use cmd::{ Command, CommandError, }; +use cmd_sample::CommandSample; +use cmd_default::CommandDefault; + +fn main() -> CommandError { + let commands = vec![ + CommandSample{}, + ]; + let mut app = App::new(env!("CARGO_PKG_NAME")) + .version(env!("CARGO_PKG_VERSION")) + .about(env!("CARGO_PKG_DESCRIPTION")); + app = CommandDefault::process_command(app); + for command in &commands { + app = app.subcommand(command.subcommand()); + } + + let matches = app.get_matches(); + for command in &commands { + if let Some(sub_cmd_matches) = matches.subcommand_matches(command.name()) { + return command.run(&matches, sub_cmd_matches); + } + } + + CommandDefault::run(&matches) +}