wasm_pack/command/
utils.rs

1//! Utility functions for commands.
2#![allow(clippy::redundant_closure)]
3
4use anyhow::Result;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::time::Duration;
8use walkdir::WalkDir;
9
10/// If an explicit path is given, then use it, otherwise assume the current
11/// directory is the crate path.
12pub 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
19/// Search up the path for the manifest file from the current working directory
20/// If we don't find the manifest file then return back the current working directory
21/// to provide the appropriate error
22fn 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
38/// Construct our `pkg` directory in the crate.
39pub fn create_pkg_dir(out_dir: &Path) -> Result<()> {
40    let _ = fs::remove_file(out_dir.join("package.json")); // Clean up package.json from previous runs
41    fs::create_dir_all(&out_dir)?;
42    fs::write(out_dir.join(".gitignore"), "*")?;
43    Ok(())
44}
45
46/// Locates the pkg directory from a specific path
47/// Returns None if unable to find the 'pkg' directory
48pub fn find_pkg_directory(path: &Path, pkg_directory: &Path) -> Option<PathBuf> {
49    if is_pkg_directory(path, pkg_directory) {
50        return Some(path.to_owned());
51    }
52
53    WalkDir::new(path)
54        .into_iter()
55        .filter_map(|x| x.ok().map(|e| e.into_path()))
56        .find(|x| is_pkg_directory(&x, pkg_directory))
57}
58
59fn is_pkg_directory(path: &Path, pkg_directory: &Path) -> bool {
60    path.exists() && path.is_dir() && path.ends_with(pkg_directory)
61}
62
63/// Render a `Duration` to a form suitable for display on a console
64pub fn elapsed(duration: Duration) -> String {
65    let secs = duration.as_secs();
66
67    if secs >= 60 {
68        format!("{}m {:02}s", secs / 60, secs % 60)
69    } else {
70        format!("{}.{:02}s", secs, duration.subsec_nanos() / 10_000_000)
71    }
72}