Skip to content

Commit

Permalink
chore: optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
lencx committed Dec 2, 2022
1 parent d9c1565 commit eccdc9c
Show file tree
Hide file tree
Showing 12 changed files with 60 additions and 68 deletions.
10 changes: 5 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
62 changes: 28 additions & 34 deletions src/core/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(" "));

Expand All @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions src/core/clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = Vec::new();
let mut path_map: HashMap<String, PathBuf> = HashMap::new();

Expand All @@ -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();
Expand Down
9 changes: 5 additions & 4 deletions src/core/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>, mode: &Option<String>) {
Create::new(
Expand All @@ -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();
Expand Down
14 changes: 7 additions & 7 deletions src/core/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -113,15 +113,15 @@ 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"(?P<name>rsw-template)").unwrap();
let cargo = re.replace(std::str::from_utf8(&template.cargo).unwrap(), name);
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(())
Expand Down
2 changes: 1 addition & 1 deletion src/core/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/core/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/core/watch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,5 +117,5 @@ pub fn rsw_cli() {
std::process::exit(1);
}

Cli::new();
Cli::init();
}
2 changes: 0 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use rsw;

#[tokio::main]
async fn main() {
rsw::rsw_cli();
Expand Down
2 changes: 1 addition & 1 deletion src/template/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
pub readme: Vec<u8>,
Expand Down
17 changes: 8 additions & 9 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand All @@ -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;
Expand All @@ -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::<Value>().unwrap();
value
content.parse::<Value>().unwrap()
}

pub fn path_exists(path: &Path) -> bool {
Expand All @@ -62,7 +61,7 @@ pub fn get_pkg(name: &str) -> (String, String) {
let re = Regex::new(r"(?x)(@([\w\d_-]+)/)?((?P<pkg_name>[\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();
}

Expand Down Expand Up @@ -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()),
};

Expand Down Expand Up @@ -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())
);
}
Expand Down

0 comments on commit eccdc9c

Please sign in to comment.