From eccdc9c8f944deb08d6d435484cb0e05200861df Mon Sep 17 00:00:00 2001 From: lencx Date: Fri, 2 Dec 2022 18:49:22 +0800 Subject: [PATCH] chore: optimization --- src/config.rs | 10 ++++---- src/core/build.rs | 62 ++++++++++++++++++++------------------------- src/core/clean.rs | 4 +-- src/core/cli.rs | 9 ++++--- src/core/create.rs | 14 +++++----- src/core/info.rs | 2 +- src/core/init.rs | 2 +- src/core/watch.rs | 2 +- src/lib.rs | 2 +- src/main.rs | 2 -- src/template/mod.rs | 2 +- src/utils.rs | 17 ++++++------- 12 files changed, 60 insertions(+), 68 deletions(-) diff --git a/src/config.rs b/src/config.rs index 01c1165..c5ac37a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -6,11 +6,11 @@ use std::{env, fs, process}; use crate::core::RswErr; use crate::utils::print; -pub static RSW_FILE: &'static str = "rsw.toml"; -pub static RSW_DIR: &'static str = ".rsw"; -pub static RSW_CRATES: &'static str = "rsw.crates"; -pub static RSW_INFO: &'static str = "rsw.info"; -pub static RSW_ERR: &'static str = "rsw.err"; +pub static RSW_FILE: &str = "rsw.toml"; +pub static RSW_DIR: &str = ".rsw"; +pub static RSW_CRATES: &str = "rsw.crates"; +pub static RSW_INFO: &str = "rsw.info"; +pub static RSW_ERR: &str = "rsw.err"; /// rust crate config #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/src/core/build.rs b/src/core/build.rs index 51e8061..b756123 100644 --- a/src/core/build.rs +++ b/src/core/build.rs @@ -59,14 +59,11 @@ impl Build { if !scope2.is_empty() { args.push("--scope"); args.push(scope2.as_str()); - } else { - if !scope.is_none() && !scope.unwrap().is_empty() { - args.push("--scope"); - args.push(scope.unwrap()); - } + } else if scope.is_some() && !scope.unwrap().is_empty() { + args.push("--scope"); + args.push(scope.unwrap()); } - let metadata = get_crate_metadata(name, crate_root); info!("🚧 wasm-pack {}", args.join(" ")); @@ -75,38 +72,35 @@ impl Build { .status() .expect("failed to execute process"); - println!(""); + println!(" "); let mut is_ok = true; - match status.code() { - Some(code) => { - if code == 0 { - print(RswInfo::CrateOk( - name.into(), - rsw_type.into(), - metadata["package"]["version"].to_string(), - )); - } else { - let output = Command::new("wasm-pack") - .args(&args) - .stderr(std::process::Stdio::piped()) - .output() - .unwrap(); - - let err = std::str::from_utf8(&output.stderr).unwrap(); - let info_content = format!( - "[RSW::ERR]\n[RSW::NAME] :~> {}\n[RSW::BUILD] :~> wasm-pack {}", - name, - &args.join(" ") - ); - rsw_watch_file(info_content.as_bytes(), err.as_bytes(), "err".into()).unwrap(); - print(RswInfo::CrateFail(name.into(), rsw_type.into())); - - is_ok = false; - } + if let Some(code) = status.code() { + if code == 0 { + print(RswInfo::CrateOk( + name.into(), + rsw_type.into(), + metadata["package"]["version"].to_string(), + )); + } else { + let output = Command::new("wasm-pack") + .args(&args) + .stderr(std::process::Stdio::piped()) + .output() + .unwrap(); + + let err = std::str::from_utf8(&output.stderr).unwrap(); + let info_content = format!( + "[RSW::ERR]\n[RSW::NAME] :~> {}\n[RSW::BUILD] :~> wasm-pack {}", + name, + &args.join(" ") + ); + rsw_watch_file(info_content.as_bytes(), err.as_bytes(), "err".into()).unwrap(); + print(RswInfo::CrateFail(name.into(), rsw_type.into())); + + is_ok = false; } - _ => {} } if config.link.unwrap() && self.is_link { diff --git a/src/core/clean.rs b/src/core/clean.rs index b71e6a5..4550403 100644 --- a/src/core/clean.rs +++ b/src/core/clean.rs @@ -11,7 +11,7 @@ pub struct Clean; // clean: link & build impl Clean { - pub fn new(config: RswConfig) { + pub fn init(config: RswConfig) { let mut crates: Vec = Vec::new(); let mut path_map: HashMap = HashMap::new(); @@ -30,7 +30,7 @@ impl Clean { crates.push(rsw_crate.name); } - Link::unlink(&config.cli.unwrap().to_owned(), crates); + Link::unlink(&config.cli.unwrap(), crates); for (_crate, _path) in path_map { std::fs::remove_dir_all(_path).unwrap(); diff --git a/src/core/cli.rs b/src/core/cli.rs index b559487..f56249c 100644 --- a/src/core/cli.rs +++ b/src/core/cli.rs @@ -45,13 +45,14 @@ pub enum Commands { } impl Cli { - pub fn new() { + pub fn init() { match &Cli::parse().command { Commands::Init => Cli::rsw_init(), Commands::Clean => Cli::rsw_clean(), Commands::Build => { Cli::rsw_build(); } + Commands::Watch => { Cli::rsw_watch(Some(Arc::new(|a, b| { let name = &a.name; @@ -85,10 +86,10 @@ impl Cli { Watch::new(config, callback.unwrap()).init(); } pub fn rsw_init() { - Init::new().unwrap(); + Init::init().unwrap(); } pub fn rsw_clean() { - Clean::new(Cli::parse_toml()); + Clean::init(Cli::parse_toml()); } pub fn rsw_new(name: &String, template: &Option, mode: &Option) { Create::new( @@ -113,7 +114,7 @@ impl Cli { crates.push(format!( "{} :~> {}", name, - crate_out.clean().to_string_lossy().to_string() + crate_out.clean().to_string_lossy() )); } init_rsw_crates(crates.join("\n").as_bytes()).unwrap(); diff --git a/src/core/create.rs b/src/core/create.rs index a02d54b..3ef735a 100644 --- a/src/core/create.rs +++ b/src/core/create.rs @@ -51,19 +51,19 @@ impl Create { self.check_crate(); // --template: https://rustwasm.github.io/docs/wasm-pack/commands/new.html#template - if !arg_tpl.is_none() { + if arg_tpl.is_some() { args.push("--template"); - args.push(arg_tpl.unwrap()); + args.push(arg_tpl.unwrap_or("https://github.com/rustwasm/wasm-pack-template")); } // --mode: https://rustwasm.github.io/docs/wasm-pack/commands/new.html#mode - if !arg_mode.is_none() { + if arg_mode.is_some() { args.push("--mode"); - args.push(arg_mode.unwrap()); + args.push(arg_mode.unwrap_or("normal")); } // wasm-pack - if arg_use == "wasm-pack" || !arg_tpl.is_none() { + if arg_use == "wasm-pack" || arg_tpl.is_some() { self.wp_cmd(&args, &scope2); } @@ -113,7 +113,7 @@ impl Create { fn create_crate(&self) -> Result<()> { let target = get_root().join(&self.name); let root = std::path::Path::new(&target); - let template = Template::new(&root); + let template = Template::new(root); let (name, _) = utils::get_pkg(&self.name); let re = Regex::new(r"(?Prsw-template)").unwrap(); @@ -121,7 +121,7 @@ impl Create { let readme = re.replace(std::str::from_utf8(&template.readme).unwrap(), &self.name); write_file(root, "README.md", readme.as_bytes())?; - write_file(root, "Cargo.toml", &cargo.as_bytes())?; + write_file(root, "Cargo.toml", cargo.as_bytes())?; write_file(root, "src/lib.rs", &template.lib)?; Ok(()) diff --git a/src/core/info.rs b/src/core/info.rs index faaa4e0..9bce71e 100644 --- a/src/core/info.rs +++ b/src/core/info.rs @@ -2,7 +2,7 @@ use colored::Colorize; use core::fmt::Display; use std::fmt::Debug; -#[derive(Debug, PartialEq)] +#[derive(Debug)] pub enum RswInfo { SplitLine, RswTomlOk, diff --git a/src/core/init.rs b/src/core/init.rs index 5a222cc..07f0e37 100644 --- a/src/core/init.rs +++ b/src/core/init.rs @@ -13,7 +13,7 @@ use crate::{ pub struct Init; impl Init { - pub fn new() -> std::io::Result<()> { + pub fn init() -> std::io::Result<()> { if !path_exists(Path::new(config::RSW_FILE)) { File::create(config::RSW_FILE)?.write_all(template::RSW_TOML)?; print(RswInfo::RswTomlOk); diff --git a/src/core/watch.rs b/src/core/watch.rs index 661ab63..d0a3ec4 100644 --- a/src/core/watch.rs +++ b/src/core/watch.rs @@ -90,7 +90,7 @@ impl Watch { Err(_) => continue, }; - if gitignore.matched(&project_path, false).is_ignore() { + if gitignore.matched(project_path, false).is_ignore() { continue; } diff --git a/src/lib.rs b/src/lib.rs index c16a282..42dd10e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -117,5 +117,5 @@ pub fn rsw_cli() { std::process::exit(1); } - Cli::new(); + Cli::init(); } diff --git a/src/main.rs b/src/main.rs index 8f1a0f9..72ef786 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,3 @@ -use rsw; - #[tokio::main] async fn main() { rsw::rsw_cli(); diff --git a/src/template/mod.rs b/src/template/mod.rs index 76c7742..cb892be 100644 --- a/src/template/mod.rs +++ b/src/template/mod.rs @@ -12,7 +12,7 @@ pub static CARGO_TOML: &[u8] = include_bytes!("rsw_cargo.toml"); pub static LIB_RS: &[u8] = include_bytes!("rsw_lib.rs"); pub static README: &[u8] = include_bytes!("rsw_readme.md"); -#[derive(Debug, PartialEq)] +#[derive(Debug)] pub struct Template { pub cargo: Vec, pub readme: Vec, diff --git a/src/utils.rs b/src/utils.rs index a4af783..7359a40 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -20,7 +20,7 @@ pub fn check_env_cmd(program: &str) -> bool { if is_program_in_path(program) { true } else { - eprint!("{}\n", e); + eprintln!("{}", e); false } } @@ -30,7 +30,7 @@ pub fn check_env_cmd(program: &str) -> bool { pub fn is_program_in_path(program: &str) -> bool { if let Ok(path) = env::var("PATH") { - for p in path.split(":") { + for p in path.split(':') { let p_str = format!("{}/{}", p, program); if fs::metadata(p_str).is_ok() { return true; @@ -48,8 +48,7 @@ pub fn get_crate_metadata(name: &str, root: PathBuf) -> Value { print(RswErr::Crate(name.into(), e)); std::process::exit(1); }); - let value = content.parse::().unwrap(); - value + content.parse::().unwrap() } pub fn path_exists(path: &Path) -> bool { @@ -62,7 +61,7 @@ pub fn get_pkg(name: &str) -> (String, String) { let re = Regex::new(r"(?x)(@([\w\d_-]+)/)?((?P[\w\d_-]+))").unwrap(); let caps = re.captures(name).unwrap(); let mut scope = "".into(); - if caps.get(2) != None { + if caps.get(2).is_some() { scope = caps.get(2).unwrap().as_str().into(); } @@ -148,7 +147,7 @@ pub fn init_logger() { }; let log_target = match record.level() { - Level::Info | Level::Error => format!(""), + Level::Info | Level::Error => String::new(), _ => format!(" {}", record.target().yellow()), }; @@ -249,18 +248,18 @@ mod pkg_name_tests { #[test] fn pkg_word() { - assert_eq!(get_pkg("@rsw/test".into()), ("test".into(), "rsw".into())); + assert_eq!(get_pkg("@rsw/test"), ("test".into(), "rsw".into())); } #[test] fn pkg_word_num() { - assert_eq!(get_pkg("wasm123".into()), ("wasm123".into(), "".into())); + assert_eq!(get_pkg("wasm123"), ("wasm123".into(), "".into())); } #[test] fn pkg_word_num_line() { assert_eq!( - get_pkg("@rsw-org/my_wasm".into()), + get_pkg("@rsw-org/my_wasm"), ("my_wasm".into(), "rsw-org".into()) ); }