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
182
183
184
185
186
187
188
189
190
191
192
use std::process::{Command, Stdio};

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

/// Add a Wasmer package's bindings to your application.
#[derive(Debug, Parser)]
pub struct Add {
    #[clap(flatten)]
    env: WasmerEnv,
    /// 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")
    packages: Vec<wasmer_registry::Package>,
}

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

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

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

        let mut cmd = self.target()?.command(&bindings)?;
        cmd.stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit());

        println!("Running: {cmd:?}");

        let status = cmd.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> {
        println!("Querying Wasmer for package bindings");

        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 target(&self) -> Result<Target, Error> {
        match (self.pip, self.npm, self.yarn) {
            (false, false, false) => Err(anyhow::anyhow!(
                "at least one of --npm, --pip or --yarn has to be specified"
            )),
            (true, false, false) => Ok(Target::Pip),
            (false, true, false) => Ok(Target::Npm { dev: self.dev }),
            (false, false, true) => Ok(Target::Yarn { dev: self.dev }),
            _ => Err(anyhow::anyhow!(
                "only one of --npm, --pip or --yarn has to be specified"
            )),
        }
    }
}

fn lookup_bindings_for_package(
    registry: &str,
    pkg: &wasmer_registry::Package,
    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) => {
            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]) -> Result<Command, Error> {
        let command_line = match self {
            Target::Pip => {
                if Command::new("pip").arg("--version").output().is_ok() {
                    "pip install"
                } else if Command::new("pip3").arg("--version").output().is_ok() {
                    "pip3 install"
                } else if Command::new("python").arg("--version").output().is_ok() {
                    "python -m pip install"
                } else if Command::new("python3").arg("--version").output().is_ok() {
                    "python3 -m pip install"
                } else {
                    return Err(anyhow::anyhow!(
                        "neither pip, pip3, python or python3 installed"
                    ));
                }
            }
            Target::Yarn { dev } => {
                if Command::new("yarn").arg("--version").output().is_err() {
                    return Err(anyhow::anyhow!("yarn not installed"));
                }
                if dev {
                    "yarn add --dev"
                } else {
                    "yarn add"
                }
            }
            Target::Npm { dev } => {
                if Command::new("npm").arg("--version").output().is_err() {
                    return Err(anyhow::anyhow!("yarn not installed"));
                }
                if dev {
                    "npm install --dev"
                } else {
                    "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);
            Ok(cmd)
        } else {
            let mut cmd = Command::new("sh");
            cmd.arg("-c").arg(command_line);
            Ok(cmd)
        }
    }
}