diff --git a/Cargo.toml b/Cargo.toml index 3245061..1494460 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,4 +15,4 @@ name = "x" path = "src/main.rs" [dependencies] -clap = "4.4.11" +clap = { version = "~4.4.11", features = ["cargo"] } diff --git a/src/cmd/root.rs b/src/cmd/root.rs index a92d744..caf0dce 100644 --- a/src/cmd/root.rs +++ b/src/cmd/root.rs @@ -1,15 +1,22 @@ -use clap::{Command, Arg, ArgAction}; +use clap::{crate_authors, crate_description, crate_version, Arg, ArgMatches, Command}; + use proxy_rs::proxy_manager; pub fn execute() { - let mut command = Command::new("Proxy Manager") - .version("1.0") - .author("Mystic") - .about("Manages proxy settings for git and npm") + let matches = parser(); + handler(matches); +} + +fn parser() -> ArgMatches { + Command::new("Proxy Manager") + .arg_required_else_help(true) + .version(crate_version!()) + .author(crate_authors!("\n")) + .about(crate_description!()) .arg( Arg::new("enable") .long("enable") - .action(ArgAction::Set) // 设置为 true 当标志被使用时 + .short('e') .value_name("PROXY_URL") .help("Enables the proxy with the given URL") .num_args(1), // 接受一个参数 @@ -17,18 +24,17 @@ pub fn execute() { .arg( Arg::new("disable") .long("disable") - .action(ArgAction::SetFalse) // 设置为 false 当标志被使用时 + .short('d') .help("Disables the proxy") .num_args(0), // 不接受参数 - ); - - let matches = command.clone().get_matches(); + ) + .get_matches() +} +fn handler(matches: ArgMatches) { if let Some(proxy_url) = matches.get_one::("enable") { proxy_manager::enable_proxy(proxy_url); } else if matches.contains_id("disable") { proxy_manager::disable_proxy(); - } else { - command.print_help().unwrap(); } } diff --git a/src/lib.rs b/src/lib.rs index cb7840a..b68a6b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,12 +1,13 @@ // lib.rs #[cfg(windows)] -pub const NPM: &'static str = "npm.cmd"; +pub const NPM: &str = "npm.cmd"; #[cfg(not(windows))] -pub const NPM: &'static str = "npm"; +pub const NPM: &str = "npm"; pub mod proxy_manager { use std::process::Command; + use crate::NPM; pub fn enable_proxy(proxy_url: &str) { @@ -43,10 +44,7 @@ pub mod proxy_manager { Some(v) => args.extend_from_slice(&[key, v]), None => args.extend_from_slice(&["--unset", key]), } - Command::new("git") - .args(&args) - .output() - .ok(); + Command::new("git").args(&args).output().ok(); } // npm config. if value is None, unset the key @@ -56,9 +54,6 @@ pub mod proxy_manager { Some(v) => args.extend_from_slice(&[key, v]), None => args.extend_from_slice(&["delete", key]), } - Command::new(NPM) - .args(&args) - .output() - .ok(); + Command::new(NPM).args(&args).output().ok(); } }