wasm_pack/command/
utils.rs1#![allow(clippy::redundant_closure)]
3
4use anyhow::Result;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::time::Duration;
8use walkdir::WalkDir;
9
10pub fn get_crate_path(path: Option<PathBuf>) -> Result<PathBuf> {
13 match path {
14 Some(p) => Ok(p),
15 None => find_manifest_from_cwd(),
16 }
17}
18
19fn find_manifest_from_cwd() -> Result<PathBuf> {
23 let mut parent_path = std::env::current_dir()?;
24 let mut manifest_path = parent_path.join("Cargo.toml");
25 loop {
26 if !manifest_path.is_file() {
27 if parent_path.pop() {
28 manifest_path = parent_path.join("Cargo.toml");
29 } else {
30 return Ok(PathBuf::from("."));
31 }
32 } else {
33 return Ok(parent_path);
34 }
35 }
36}
37
38pub fn create_pkg_dir(out_dir: &Path, no_gitignore: bool) -> Result<()> {
40 let _ = fs::remove_file(out_dir.join("package.json")); fs::create_dir_all(&out_dir)?;
42 if !no_gitignore {
43 fs::write(out_dir.join(".gitignore"), "*")?;
44 }
45 Ok(())
46}
47
48pub fn find_pkg_directory(path: &Path, pkg_directory: &Path) -> Option<PathBuf> {
51 if is_pkg_directory(path, pkg_directory) {
52 return Some(path.to_owned());
53 }
54
55 WalkDir::new(path)
56 .into_iter()
57 .filter_map(|x| x.ok().map(|e| e.into_path()))
58 .find(|x| is_pkg_directory(&x, pkg_directory))
59}
60
61fn is_pkg_directory(path: &Path, pkg_directory: &Path) -> bool {
62 path.exists() && path.is_dir() && path.ends_with(pkg_directory)
63}
64
65pub fn elapsed(duration: Duration) -> String {
67 let secs = duration.as_secs();
68
69 if secs >= 60 {
70 format!("{}m {:02}s", secs / 60, secs % 60)
71 } else {
72 format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
73 }
74}