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
use std::{
    collections::{BTreeSet, HashSet},
    env,
    fs::{self, File},
    io::BufReader,
    path::Path,
    process::{Command, Stdio},
    time::Instant,
};

use serde::Deserialize;

use anyhow::{Context, Error, Ok};
use ignore::{overrides::OverrideBuilder, Walk, WalkBuilder};
use insta::Settings;
use wasmer_pack_cli::Language;

const JEST_CONFIG: &str = include_str!("./jest.config.js");

pub fn autodiscover(crate_dir: impl AsRef<Path>) -> Result<(), Error> {
    let start = Instant::now();

    let crate_dir = crate_dir.as_ref();
    tracing::info!(dir = %crate_dir.display(), "Looking for tests");

    let manifest_path = crate_dir.join("Cargo.toml");
    let temp = tempfile::tempdir().context("Unable to create a temporary directory")?;

    tracing::info!(?temp, "Compiling the crate and generating a WAPM package");
    let wapm_package = crate::compile_rust_to_wapm_package(&manifest_path, temp.path())?;

    let generated_bindings = crate_dir.join("generated_bindings");

    if generated_bindings.exists() {
        tracing::info!("Deleting bindings from a previous run");
        std::fs::remove_dir_all(&generated_bindings)
            .context("Unable to delete the old generated bindings")?;
    }

    for language in detected_languages(crate_dir) {
        let bindings = generated_bindings.join(language.name());
        tracing::info!(
            bindings_dir = %bindings.display(),
            language = language.name(),
            "Generating bindings",
        );
        crate::generate_bindings(&bindings, &wapm_package, language, None)?;

        match language {
            Language::JavaScript => {
                setup_javascript(crate_dir, &bindings)?;
                run_jest(crate_dir)?;
            }
            Language::Python => {
                setup_python(crate_dir, &bindings)?;
                run_pytest(crate_dir)?;
            }
        }

        snapshot_generated_bindings(crate_dir, &bindings, language)?;
    }

    tracing::info!(duration = ?start.elapsed(), "Testing complete");

    Ok(())
}

fn detected_languages(crate_dir: &Path) -> HashSet<Language> {
    let mut languages = HashSet::new();

    for entry in Walk::new(crate_dir).filter_map(|entry| entry.ok()) {
        match entry.path().extension().and_then(|s| s.to_str()) {
            Some("py") => {
                languages.insert(Language::Python);
            }
            Some("mjs") | Some("js") | Some("ts") => {
                languages.insert(Language::JavaScript);
            }
            _ => {}
        }
    }
    languages
}

fn snapshot_generated_bindings(
    crate_dir: &Path,
    package_dir: &Path,
    language: Language,
) -> Result<(), Error> {
    tracing::info!(
        package_dir=%package_dir.display(),
        language=language.name(),
        "Creating snapshot tests for the generated bindings",
    );

    let snapshot_files: BTreeSet<_> = language_specific_matches(package_dir, language)?
        .filter_map(|entry| entry.ok())
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.into_path())
        .collect();

    let mut settings = Settings::clone_current();
    settings.set_snapshot_path(crate_dir.join("snapshots").join(language.name()));
    settings.set_prepend_module_to_snapshot(false);
    settings.set_input_file(package_dir);
    settings.set_omit_expression(true);
    // We want to ignore version strings because it makes tests fail when you
    // make new versions
    settings.add_filter(r#""\d+\.\d+\.\d+""#, r#""x.y.z""#);
    // Also ignore the generator version comments
    settings.add_filter(r"wasmer-pack v\d+\.\d+\.\d+", "wasmer-pack vX.Y.Z");

    let _guard = settings.bind_to_scope();

    insta::assert_debug_snapshot!(
        "all files",
        snapshot_files
            .iter()
            .map(|path| path.strip_prefix(crate_dir).expect("unreachable"))
            .collect::<Vec<_>>()
    );

    for path in snapshot_files {
        let contents = std::fs::read_to_string(&path)
            .with_context(|| format!("Unable to read \"{}\"", path.display()))?;

        let mut settings = Settings::clone_current();
        let simplified_path = path.strip_prefix(package_dir)?;
        settings.set_input_file(&path);
        let _guard = settings.bind_to_scope();

        let snapshot_name = simplified_path.display().to_string();
        insta::assert_display_snapshot!(snapshot_name, &contents);
    }

    Ok(())
}

fn language_specific_matches(package_dir: &Path, language: Language) -> Result<Walk, Error> {
    let mut builder = OverrideBuilder::new(package_dir);

    let overrides = match language {
        Language::JavaScript => builder
            .add("!node_modules")?
            .add("*.ts")?
            .add("*.test.ts")?
            .add("*.mjs")?
            .add("*.test.mjs")?
            .add("*.js")?
            .add("*.test.js")?
            .build()?,
        Language::Python => builder
            .add("*.py")?
            .add("*.toml")?
            .add("*.in")?
            .add("py.typed")?
            .build()?,
    };

    let walk = WalkBuilder::new(package_dir)
        .parents(false)
        .overrides(overrides)
        .build();

    Ok(walk)
}

fn setup_python(crate_dir: &Path, generated_bindings: &Path) -> Result<(), Error> {
    let pyproject = crate_dir.join("pyproject.toml");

    if pyproject.exists() {
        // Assume everything has been set up correctly. Now, we just need to
        // make sure the dependencies are available.

        let mut cmd = Command::new("poetry");
        cmd.arg("install")
            .arg("--sync")
            .arg("--no-interaction")
            .arg("--no-root");
        tracing::info!(?cmd, "Installing dependencies");
        let status = cmd
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .current_dir(crate_dir)
            .status()
            .context("Unable to run poetry. Is it installed?")?;
        anyhow::ensure!(status.success(), "Unable to install Python dependencies");

        return Ok(());
    }

    tracing::info!("Initializing the python package");

    let mut cmd = Command::new("poetry");
    cmd.arg("init")
        .arg("--name=tests")
        .arg("--no-interaction")
        .arg("--description=Python integration tests")
        .arg("--dependency=pytest");
    tracing::info!(?cmd, "Initializing the Python package");
    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run poetry. Is it installed?")?;
    anyhow::ensure!(status.success(), "Unable to initialize the Python package");

    let mut cmd = Command::new("poetry");
    cmd.arg("add")
        .arg("--no-interaction")
        .arg("--editable")
        .arg(generated_bindings.strip_prefix(crate_dir)?);
    tracing::info!(?cmd, "Adding the generated bindings as a dependency");
    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run poetry. Is it installed?")?;
    anyhow::ensure!(
        status.success(),
        "Unable to add the generated bindings as a dependency"
    );

    Ok(())
}

fn run_pytest(crate_dir: &Path) -> Result<(), Error> {
    if cfg!(target_os = "macos") && cfg!(target_arch = "aarch64") {
        tracing::warn!("Skipping Pytest. Wasmer Python doesn't work on M1 MacOS. For more, see <https://github.com/wasmerio/wasmer-python/issues/680>");
        return Ok(());
    }

    let mut cmd = Command::new("poetry");
    cmd.arg("run").arg("pytest").arg("--verbose");
    tracing::info!(?cmd, "Running pytest");
    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run poetry. Is it installed?")?;
    anyhow::ensure!(status.success(), "pytest failed");

    Ok(())
}

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

#[derive(Deserialize, Debug)]
struct PackageJson {
    name: String,
}
fn setup_javascript(crate_dir: &Path, generated_bindings: &Path) -> Result<(), Error> {
    // reading the package and getting the namespace and name of the javascript created package
    let package_path = generated_bindings.join("package");
    let generated_package_name = get_package_name(&package_path)?;
    let yarn_lock = crate_dir.join("yarn.lock");

    if yarn_lock.exists() {
        //need to install dependencies for generated package as yarn link doesn't resolves the dependencies on it own

        let mut cmd = shell();
        cmd.arg("yarn").current_dir(&package_path);
        tracing::info!(
            ?cmd,
            "Installing the Javascript Dependencies for generated package"
        );

        let status = cmd
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .current_dir(&package_path)
            .status()
            .context("Unable to run yarn. Is it installed?")?;
        anyhow::ensure!(
            status.success(),
            "Unable to install JavaScript Dependencies for generated package"
        );

        let mut cmd = shell();
        cmd.arg("yarn").current_dir(crate_dir);
        tracing::info!(
            ?cmd,
            "Found `yarn-lock`. Installing the Javascript Dependencies"
        );

        let status = cmd
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .current_dir(crate_dir)
            .status()
            .context("Unable to run yarn. Is it installed?")?;
        anyhow::ensure!(
            status.success(),
            "Unable to install JavaScript Dependencies"
        );
        return Ok(());
    }

    let mut cmd = shell();
    cmd.arg("yarn")
        .arg("init")
        .arg("--yes")
        .current_dir(crate_dir);
    tracing::info!(?cmd, "Initializing the Javascript package");

    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run yarn. Is it installed?")?;
    anyhow::ensure!(
        status.success(),
        "Unable to initialize the JavaScript package"
    );

    // install jest to crate dir

    let mut cmd = shell();
    cmd.arg("yarn")
        .arg("add")
        .arg("--dev")
        .arg("jest")
        .current_dir(crate_dir);
    tracing::info!(?cmd, "Installing the Jest testing library");

    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run yarn. Is it installed?")?;
    anyhow::ensure!(status.success(), "Unable to install jest testing library");

    let jest_file_name = "jest.config.js";
    let jest_config_file = crate_dir.join(jest_file_name);

    fs::write(&jest_config_file, JEST_CONFIG)?;
    anyhow::ensure!(crate_dir.join(&jest_config_file).exists());

    let mut cmd = shell();
    cmd.arg("yarn").current_dir(&package_path);

    tracing::info!(?cmd, "Installing dependencies for generated bindings");
    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(&package_path)
        .status()
        .context("Unable to run yarn. Is it installed?")?;
    anyhow::ensure!(
        status.success(),
        "Unable to install dependencies for generated bindings"
    );

    let mut cmd = shell();
    cmd.arg("yarn").arg("link").current_dir(&package_path);

    tracing::info!(?cmd, "Linking the generated bindings as a `Yarn link`");
    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(&package_path)
        .status()
        .context("Unable to run yarn. Is it installed?")?;
    anyhow::ensure!(
        status.success(),
        "Unable to perform yarn link on generated bindings"
    );

    let mut cmd = shell();
    cmd.arg("yarn")
        .arg("link")
        .arg(&generated_package_name)
        .current_dir(crate_dir);

    tracing::info!(?cmd, "Linking the testing package to generated bindings");
    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run yarn. Is it installed?")?;
    anyhow::ensure!(
        status.success(),
        "Unable to initialize a link to the generated bindings from testing crate"
    );
    Ok(())
}

fn run_jest(crate_dir: &Path) -> Result<(), Error> {
    let mut cmd = shell();

    cmd.current_dir(crate_dir).arg("yarn").arg("jest");
    tracing::info!(?cmd, "Running the jest tests");

    let status = cmd
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .current_dir(crate_dir)
        .status()
        .context("Unable to run yarn. Is it installed?")?;
    anyhow::ensure!(
        status.success(),
        "Unable to install JavaScript Dependencies for generated package"
    );

    Ok(())
}

fn get_package_name(package_path: &Path) -> Result<String, Error> {
    let package_json_path = package_path.join("package.json");

    anyhow::ensure!(
        package_json_path.is_file(),
        "Package Json file for generated package not found"
    );

    let file = File::open(package_json_path).unwrap();
    let reader = BufReader::new(file);
    let package_json: PackageJson = serde_json::from_reader(reader).unwrap();
    Ok(package_json.name)
}