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
use std::{env, fs, path::PathBuf, process::Command};
use anyhow::{bail, Context, Result};
use sha1::{Digest, Sha1};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct JsExecOptions {
pub cache: bool,
pub module: bool,
}
fn cargo_manifest_dir() -> PathBuf {
env::var("CARGO_MANIFEST_DIR").unwrap().into()
}
fn cargo_cache_root() -> PathBuf {
env::var("SWC_ECMA_TESTING_CACHE_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| {
env::var("TARGET").map(PathBuf::from).unwrap_or_else(|_| {
let mut target_dir = cargo_manifest_dir();
target_dir.push("target");
target_dir
})
})
}
pub fn exec_node_js(js_code: &str, opts: JsExecOptions) -> Result<String> {
if opts.cache {
let hash = calc_hash(js_code);
let cache_dir = cargo_cache_root().join(".swc-node-exec-cache");
let cache_path = cache_dir.join(format!("{}.stdout", hash));
if let Ok(s) = fs::read_to_string(&cache_path) {
return Ok(s);
}
let output = exec_node_js(
js_code,
JsExecOptions {
cache: false,
..opts
},
)?;
fs::create_dir_all(&cache_dir).context("failed to create cache directory")?;
fs::write(&cache_path, output.as_bytes()).context("failed to write cache")?;
return Ok(output);
}
let mut c = Command::new("node");
if opts.module {
c.arg("--input-type=module");
} else {
c.arg("--input-type=commonjs");
}
let output = c
.arg("-e")
.arg(js_code)
.output()
.context("failed to execute output of minifier")?;
if !output.status.success() {
bail!(
"failed to execute:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)
}
String::from_utf8(output.stdout).context("output is not utf8")
}
fn calc_hash(s: &str) -> String {
let mut hasher = Sha1::default();
hasher.update(s.as_bytes());
let sum = hasher.finalize();
hex::encode(sum)
}