dioxus-cli 0.6.3

CLI for building fullstack web, desktop, and mobile apps with a single codebase.
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use crate::{CliSettings, Result};
use anyhow::{anyhow, Context};
use flate2::read::GzDecoder;
use std::path::PathBuf;
use std::{path::Path, process::Stdio};
use tar::Archive;
use tempfile::TempDir;
use tokio::{fs, process::Command};

pub(crate) struct WasmBindgen {
    version: String,
    input_path: PathBuf,
    out_dir: PathBuf,
    out_name: String,
    target: String,
    debug: bool,
    keep_debug: bool,
    demangle: bool,
    remove_name_section: bool,
    remove_producers_section: bool,
}

impl WasmBindgen {
    pub fn new(version: &str) -> Self {
        Self {
            version: version.to_string(),
            input_path: PathBuf::new(),
            out_dir: PathBuf::new(),
            out_name: String::new(),
            target: String::new(),
            debug: true,
            keep_debug: true,
            demangle: true,
            remove_name_section: false,
            remove_producers_section: false,
        }
    }

    pub fn input_path(self, input_path: &Path) -> Self {
        Self {
            input_path: input_path.to_path_buf(),
            ..self
        }
    }

    pub fn out_dir(self, out_dir: &Path) -> Self {
        Self {
            out_dir: out_dir.to_path_buf(),
            ..self
        }
    }

    pub fn out_name(self, out_name: &str) -> Self {
        Self {
            out_name: out_name.to_string(),
            ..self
        }
    }

    pub fn target(self, target: &str) -> Self {
        Self {
            target: target.to_string(),
            ..self
        }
    }

    pub fn debug(self, debug: bool) -> Self {
        Self { debug, ..self }
    }

    pub fn keep_debug(self, keep_debug: bool) -> Self {
        Self { keep_debug, ..self }
    }

    pub fn demangle(self, demangle: bool) -> Self {
        Self { demangle, ..self }
    }

    pub fn remove_name_section(self, remove_name_section: bool) -> Self {
        Self {
            remove_name_section,
            ..self
        }
    }

    pub fn remove_producers_section(self, remove_producers_section: bool) -> Self {
        Self {
            remove_producers_section,
            ..self
        }
    }

    /// Run the bindgen command with the current settings
    pub async fn run(&self) -> Result<()> {
        let binary = self.get_binary_path().await?;

        let mut args = Vec::new();

        // Target
        args.push("--target");
        args.push(&self.target);

        // Options
        if self.debug {
            args.push("--debug");
        }

        if !self.demangle {
            args.push("--no-demangle");
        }

        if self.keep_debug {
            args.push("--keep-debug");
        }

        if self.remove_name_section {
            args.push("--remove-name-section");
        }

        if self.remove_producers_section {
            args.push("--remove-producers-section");
        }

        // Out name
        args.push("--out-name");
        args.push(&self.out_name);

        // wbg generates typescript bindnings by default - we don't want those
        args.push("--no-typescript");

        // Out dir
        let out_dir = self
            .out_dir
            .to_str()
            .expect("input_path should be valid utf8");

        args.push("--out-dir");
        args.push(out_dir);

        // Input path
        let input_path = self
            .input_path
            .to_str()
            .expect("input_path should be valid utf8");
        args.push(input_path);

        // Run bindgen
        Command::new(binary)
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await?;

        Ok(())
    }

    /// Verify the installed version of wasm-bindgen-cli
    ///
    /// For local installations, this will check that the installed version matches the specified version.
    /// For managed installations, this will check that the version managed by `dx` is the specified version.
    pub async fn verify_install(version: &str) -> anyhow::Result<()> {
        let settings = Self::new(version);
        if CliSettings::prefer_no_downloads() {
            settings.verify_local_install().await
        } else {
            settings.verify_managed_install().await
        }
    }

    /// Install the specified wasm-bingen version.
    ///
    /// This will overwrite any existing wasm-bindgen binaries of the same version.
    ///
    /// This will attempt to install wasm-bindgen from:
    /// 1. Direct GitHub release download.
    /// 2. `cargo binstall` if installed.
    /// 3. Compile from source with `cargo install`.
    async fn install(&self) -> anyhow::Result<()> {
        tracing::info!("Installing wasm-bindgen-cli@{}...", self.version);

        // Attempt installation from GitHub
        if let Err(e) = self.install_github().await {
            tracing::error!("Failed to install wasm-bindgen-cli@{}: {e}", self.version);
        } else {
            tracing::info!(
                "wasm-bindgen-cli@{} was successfully installed from GitHub.",
                self.version
            );
            return Ok(());
        }

        // Attempt installation from binstall.
        if let Err(e) = self.install_binstall().await {
            tracing::error!("Failed to install wasm-bindgen-cli@{}: {e}", self.version);
            tracing::info!("Failed to install prebuilt binary for wasm-bindgen-cli@{}. Compiling from source instead. This may take a while.", self.version);
        } else {
            tracing::info!(
                "wasm-bindgen-cli@{} was successfully installed from cargo-binstall.",
                self.version
            );
            return Ok(());
        }

        // Attempt installation from cargo.
        self.install_cargo()
            .await
            .context("failed to install wasm-bindgen-cli from cargo")?;

        tracing::info!(
            "wasm-bindgen-cli@{} was successfully installed from source.",
            self.version
        );

        Ok(())
    }

    async fn install_github(&self) -> anyhow::Result<()> {
        tracing::debug!(
            "Attempting to install wasm-bindgen-cli@{} from GitHub",
            self.version
        );

        let url = self.git_install_url().ok_or_else(|| {
            anyhow!(
                "no available GitHub binary for wasm-bindgen-cli@{}",
                self.version
            )
        })?;

        // Get the final binary location.
        let binary_path = self.get_binary_path().await?;

        // Download then extract wasm-bindgen-cli.
        let bytes = reqwest::get(url).await?.bytes().await?;

        // Unpack the first tar entry to the final binary location
        Archive::new(GzDecoder::new(bytes.as_ref()))
            .entries()?
            .find(|entry| {
                entry
                    .as_ref()
                    .map(|e| {
                        e.path_bytes()
                            .ends_with(self.downloaded_bin_name().as_bytes())
                    })
                    .unwrap_or(false)
            })
            .context("Failed to find entry")??
            .unpack(&binary_path)
            .context("failed to unpack wasm-bindgen-cli binary")?;

        Ok(())
    }

    async fn install_binstall(&self) -> anyhow::Result<()> {
        tracing::debug!(
            "Attempting to install wasm-bindgen-cli@{} from cargo-binstall",
            self.version
        );

        let package = self.cargo_bin_name();
        let tempdir = TempDir::new()?;

        // Run install command
        Command::new("cargo")
            .args([
                "binstall",
                &package,
                "--no-confirm",
                "--force",
                "--no-track",
                "--install-path",
            ])
            .arg(tempdir.path())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .await?;

        fs::copy(
            tempdir.path().join(self.downloaded_bin_name()),
            self.get_binary_path().await?,
        )
        .await?;

        Ok(())
    }

    async fn install_cargo(&self) -> anyhow::Result<()> {
        tracing::debug!(
            "Attempting to install wasm-bindgen-cli@{} from cargo-install",
            self.version
        );
        let package = self.cargo_bin_name();
        let tempdir = TempDir::new()?;

        // Run install command
        Command::new("cargo")
            .args([
                "install",
                &package,
                "--bin",
                "wasm-bindgen",
                "--no-track",
                "--force",
                "--root",
            ])
            .arg(tempdir.path())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .output()
            .await
            .context("failed to install wasm-bindgen-cli from cargo-install")?;

        tracing::info!("Copying into path: {}", tempdir.path().display());

        // copy the wasm-bindgen out of the tempdir to the final location
        fs::copy(
            tempdir.path().join("bin").join(self.downloaded_bin_name()),
            self.get_binary_path().await?,
        )
        .await
        .context("failed to copy wasm-bindgen binary")?;

        Ok(())
    }

    async fn verify_local_install(&self) -> anyhow::Result<()> {
        tracing::trace!(
            "Verifying wasm-bindgen-cli@{} is installed in the path",
            self.version
        );

        let binary = self.get_binary_path().await?;
        let output = Command::new(binary)
            .args(["--version"])
            .output()
            .await
            .context("Failed to check wasm-bindgen-cli version")?;

        let stdout = String::from_utf8(output.stdout)
            .context("Failed to extract wasm-bindgen-cli output")?;

        let installed_version = stdout.trim_start_matches("wasm-bindgen").trim();
        if installed_version != self.version {
            return Err(anyhow!(
                "Incorrect wasm-bindgen-cli version: project requires version {} but version {} is installed",
                self.version,
                installed_version,
            ));
        }

        Ok(())
    }

    async fn verify_managed_install(&self) -> anyhow::Result<()> {
        tracing::trace!(
            "Verifying wasm-bindgen-cli@{} is installed in the tool directory",
            self.version
        );

        let binary_name = self.installed_bin_name();
        let path = self.install_dir().await?.join(binary_name);

        if !path.exists() {
            self.install().await?;
        }

        Ok(())
    }

    async fn get_binary_path(&self) -> anyhow::Result<PathBuf> {
        if CliSettings::prefer_no_downloads() {
            which::which("wasm-bindgen")
                .map_err(|_| anyhow!("Missing wasm-bindgen-cli@{}", self.version))
        } else {
            let installed_name = self.installed_bin_name();
            let install_dir = self.install_dir().await?;
            Ok(install_dir.join(installed_name))
        }
    }

    async fn install_dir(&self) -> anyhow::Result<PathBuf> {
        let bindgen_dir = dirs::data_local_dir()
            .expect("user should be running on a compatible operating system")
            .join("dioxus/wasm-bindgen/");

        fs::create_dir_all(&bindgen_dir).await?;
        Ok(bindgen_dir)
    }

    fn installed_bin_name(&self) -> String {
        let mut name = format!("wasm-bindgen-{}", self.version);
        if cfg!(windows) {
            name = format!("{name}.exe");
        }
        name
    }

    fn cargo_bin_name(&self) -> String {
        format!("wasm-bindgen-cli@{}", self.version)
    }

    fn downloaded_bin_name(&self) -> &'static str {
        if cfg!(windows) {
            "wasm-bindgen.exe"
        } else {
            "wasm-bindgen"
        }
    }

    fn git_install_url(&self) -> Option<String> {
        let platform = if cfg!(all(target_os = "windows", target_arch = "x86_64")) {
            "x86_64-pc-windows-msvc"
        } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) {
            "x86_64-unknown-linux-musl"
        } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
            "aarch64-unknown-linux-gnu"
        } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) {
            "x86_64-apple-darwin"
        } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
            "aarch64-apple-darwin"
        } else {
            return None;
        };

        Some(format!(
            "https://github.com/rustwasm/wasm-bindgen/releases/download/{}/wasm-bindgen-{}-{}.tar.gz",
            self.version, self.version, platform
        ))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    const VERSION: &str = "0.2.99";

    /// Test the github installer.
    #[tokio::test]
    async fn test_github_install() {
        if std::env::var("TEST_INSTALLS").is_err() {
            return;
        }
        let binary = WasmBindgen::new(VERSION);
        reset_test().await;
        binary.install_github().await.unwrap();
        test_verify_install().await;
        verify_installation(&binary).await;
    }

    /// Test the cargo installer.
    #[tokio::test]
    async fn test_cargo_install() {
        if std::env::var("TEST_INSTALLS").is_err() {
            return;
        }
        let binary = WasmBindgen::new(VERSION);
        reset_test().await;
        binary.install_cargo().await.unwrap();
        test_verify_install().await;
        verify_installation(&binary).await;
    }

    // CI doesn't have binstall.
    // Test the binstall installer
    #[tokio::test]
    async fn test_binstall_install() {
        if std::env::var("TEST_INSTALLS").is_err() {
            return;
        }
        let binary = WasmBindgen::new(VERSION);
        reset_test().await;
        binary.install_binstall().await.unwrap();
        test_verify_install().await;
        verify_installation(&binary).await;
    }

    /// Helper to test `verify_install` after an installation.
    async fn test_verify_install() {
        WasmBindgen::verify_install(VERSION).await.unwrap();
    }

    /// Helper to test that the installed binary actually exists.
    async fn verify_installation(binary: &WasmBindgen) {
        let path = binary.install_dir().await.unwrap();
        let name = binary.installed_bin_name();
        let binary_path = path.join(name);
        assert!(
            binary_path.exists(),
            "wasm-bindgen binary doesn't exist after installation"
        );
    }

    /// Delete the installed binary. The temp folder should be automatically deleted.
    async fn reset_test() {
        let binary = WasmBindgen::new(VERSION);
        let path = binary.install_dir().await.unwrap();
        let name = binary.installed_bin_name();
        let binary_path = path.join(name);
        let _ = tokio::fs::remove_file(binary_path).await;
    }
}