feat: init commit

This commit is contained in:
2020-10-01 10:11:45 +08:00
parent 9be5329c59
commit d19f06eb1b
7 changed files with 414 additions and 3 deletions

12
src/cmd.rs Normal file
View File

@@ -0,0 +1,12 @@
use clap::{ ArgMatches, App };
pub type CommandError = Result<(), Box<dyn std::error::Error>>;
pub trait Command {
fn name(&self) -> &str;
fn subcommand<'a>(&self) -> App<'a, 'a>;
fn run(&self, arg_matches: &ArgMatches, _: &ArgMatches) -> CommandError;
}

24
src/cmd_default.rs Normal file
View File

@@ -0,0 +1,24 @@
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!("[INFO] Verbose count: {}", verbose_count);
println!("[INFO] This is default command cli ...");
// TODO ...
Ok(())
}
}

45
src/cmd_show.rs Normal file
View File

@@ -0,0 +1,45 @@
use clap::{ ArgMatches, SubCommand, App };
use toml::Value;
use crate::cmd::{ Command, CommandError };
pub struct CommandShow;
impl Command for CommandShow {
fn name(&self) -> &str { "show" }
fn subcommand<'a>(&self) -> App<'a, 'a> {
SubCommand::with_name(self.name()).about("Show subcommand")
}
fn run(&self, _arg_matches: &ArgMatches, _sub_arg_matches: &ArgMatches) -> CommandError {
let cargo_toml = std::fs::read_to_string("Cargo.toml")?;
let cargo_toml_value = cargo_toml.parse::<Value>()?;
println!("{}", find_dependencies(&cargo_toml_value).map(|v| {
print_dependencies(v).iter().map(|e| format!("{} -> {}", e.0, e.1)).collect::<Vec<_>>().join("\n")
}).unwrap_or_else(|| "None".into()));
Ok(())
}
}
fn print_dependencies(dependencies_value: &Value) -> Vec<(String, String)> {
let mut ret = vec![];
match dependencies_value {
Value::Table(t) => {
t.iter().for_each(|(k, v)| {
ret.push((k.clone(), format!("{}", v.clone())));
});
},
_ => (),
}
ret
}
fn find_dependencies(cargo_toml_value: &Value) -> Option<&Value> {
match cargo_toml_value {
Value::Table(t) => t.get("dependencies"),
_ => None,
}
}

31
src/main.rs Normal file
View File

@@ -0,0 +1,31 @@
use clap::App;
mod cmd;
mod cmd_show;
mod cmd_default;
use cmd::{ Command, CommandError, };
use cmd_show::CommandShow;
use cmd_default::CommandDefault;
fn main() -> CommandError {
let commands: Vec<Box<dyn Command>> = vec![
Box::new(CommandShow),
];
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)
}