zint/
lookup.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//! Binary lookup util

use anyhow::Result;
use serde::Deserialize;
use std::{fs, path::PathBuf};

/// Cargo Manifest for parsing package.
#[derive(Deserialize)]
struct Manifest {
    /// The package.
    pub package: Package,
}

/// Cargo Package for parsing package name.
#[derive(Deserialize)]
struct Package {
    /// Package name.
    pub name: String,
}

/// Get the name of the current package.
pub fn pkg_name() -> Result<String> {
    let manifest = fs::read_to_string(etc::find_up("Cargo.toml")?)?;
    Ok(toml::from_str::<Manifest>(&manifest)?.package.name)
}

/// Get the wasm binary of the provided name from the target directory.
pub fn wasm(name: &str) -> Result<PathBuf> {
    let target = target_dir()?;
    let search = |profile: &str| -> Result<PathBuf> {
        let target = target.join(profile);
        let mut wasm = target.join(name).with_extension("wasm");
        if !wasm.exists() {
            wasm = target.join("examples").join(name).with_extension("wasm");
        }

        if wasm.exists() {
            Ok(wasm)
        } else {
            Err(anyhow::anyhow!("{} not found", wasm.to_string_lossy()))
        }
    };

    search("release").or_else(|_| search("debug"))
}

/// Get the current target directory.
fn target_dir() -> Result<PathBuf> {
    cargo_metadata::MetadataCommand::new()
        .no_deps()
        .exec()
        .map_err(Into::into)
        .map(|metadata| {
            metadata
                .target_directory
                .join("wasm32-unknown-unknown")
                .into()
        })
}