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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use std::process::{Command, Stdio};

use anyhow::{Context, Error};
use clap::Parser;
use wasmer_registry::{Bindings, PartialWapmConfig, ProgrammingLanguage};

use crate::cli::SplitVersion;

/// Add a WAPM package's bindings to your application.
#[derive(Debug, Parser)]
pub struct Add {
    /// The registry to fetch bindings from.
    #[clap(long, env = "WAPM_REGISTRY")]
    registry: Option<String>,
    /// Add the JavaScript bindings using "npm install".
    #[clap(long, groups = &["bindings", "js"])]
    npm: bool,
    /// Add the JavaScript bindings using "yarn add".
    #[clap(long, groups = &["bindings", "js"])]
    yarn: bool,
    /// Add the package as a dev-dependency.
    #[clap(long, requires = "js")]
    dev: bool,
    /// Add the Python bindings using "pip install".
    #[clap(long, groups = &["bindings", "py"])]
    pip: bool,
    /// The packages to add (e.g. "wasmer/wasmer-pack@0.5.0" or "python/python")
    #[clap(parse(try_from_str))]
    packages: Vec<SplitVersion>,
}

impl Add {
    /// Execute [`Add`].
    pub fn execute(&self) -> Result<(), Error> {
        anyhow::ensure!(!self.packages.is_empty(), "No packages specified");

        let registry = self
            .registry()
            .context("Unable to determine which registry to use")?;

        let bindings = self.lookup_bindings(&registry)?;

        let mut cmd = self.target().command(&bindings);

        #[cfg(feature = "debug")]
        log::debug!("Running {cmd:?}");

        let status = cmd
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .status()
            .with_context(|| {
                format!(
                    "Unable to start \"{:?}\". Is it installed?",
                    cmd.get_program()
                )
            })?;

        anyhow::ensure!(status.success(), "Command failed: {:?}", cmd);

        Ok(())
    }

    fn lookup_bindings(&self, registry: &str) -> Result<Vec<Bindings>, Error> {
        #[cfg(feature = "debug")]
        log::debug!("Querying WAPM for the bindings packages");

        let mut bindings_to_add = Vec::new();
        let language = self.target().language();

        for pkg in &self.packages {
            let bindings = lookup_bindings_for_package(registry, pkg, &language)
                .with_context(|| format!("Unable to find bindings for {pkg}"))?;
            bindings_to_add.push(bindings);
        }

        Ok(bindings_to_add)
    }

    fn registry(&self) -> Result<String, Error> {
        match &self.registry {
            Some(r) => Ok(r.clone()),
            None => {
                let cfg = PartialWapmConfig::from_file()
                    .map_err(Error::msg)
                    .context("Unable to load WAPM's config file")?;
                Ok(cfg.registry.get_current_registry())
            }
        }
    }

    fn target(&self) -> Target {
        match (self.pip, self.npm, self.yarn) {
            (true, false, false) => Target::Pip,
            (false, true, false) => Target::Npm { dev: self.dev },
            (false, false, true) => Target::Yarn { dev: self.dev },
            _ => unreachable!(
                "Clap should ensure at least one item in the \"bindings\" group is specified"
            ),
        }
    }
}

fn lookup_bindings_for_package(
    registry: &str,
    pkg: &SplitVersion,
    language: &ProgrammingLanguage,
) -> Result<Bindings, Error> {
    let all_bindings =
        wasmer_registry::list_bindings(registry, &pkg.package, pkg.version.as_deref())?;

    match all_bindings.iter().find(|b| b.language == *language) {
        Some(b) => {
            #[cfg(feature = "debug")]
            {
                let Bindings { url, generator, .. } = b;
                log::debug!("Found {pkg} bindings generated by {generator} at {url}");
            }

            Ok(b.clone())
        }
        None => {
            if all_bindings.is_empty() {
                anyhow::bail!("The package doesn't contain any bindings");
            } else {
                todo!();
            }
        }
    }
}

#[derive(Debug, Copy, Clone)]
enum Target {
    Pip,
    Yarn { dev: bool },
    Npm { dev: bool },
}

impl Target {
    fn language(self) -> ProgrammingLanguage {
        match self {
            Target::Pip => ProgrammingLanguage::PYTHON,
            Target::Yarn { .. } | Target::Npm { .. } => ProgrammingLanguage::JAVASCRIPT,
        }
    }

    /// Construct a command which we can run to add packages.
    ///
    /// This deliberately runs the command using the OS shell instead of
    /// invoking the tool directly. That way we can handle when a version
    /// manager (e.g. `nvm` or `asdf`) replaces the tool with a script (e.g.
    /// `npm.cmd` or `yarn.ps1`).
    ///
    /// See <https://github.com/wasmerio/wapm-cli/issues/291> for more.
    fn command(self, packages: &[Bindings]) -> Command {
        let command_line = match self {
            Target::Pip => "pip install",
            Target::Yarn { dev: true } => "yarn add --dev",
            Target::Yarn { dev: false } => "yarn add",
            Target::Npm { dev: true } => "npm install --dev",
            Target::Npm { dev: false } => "npm install",
        };
        let mut command_line = command_line.to_string();

        for pkg in packages {
            command_line.push(' ');
            command_line.push_str(&pkg.url);
        }

        if cfg!(windows) {
            let mut cmd = Command::new("cmd");
            cmd.arg("/C").arg(command_line);
            cmd
        } else {
            let mut cmd = Command::new("sh");
            cmd.arg("-c").arg(command_line);
            cmd
        }
    }
}