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
mod bundle;
mod guarded_command;
pub mod output;
pub use bundle::Bundle;
use std::env;
use std::fs;
use std::fs::File;
use std::iter;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::mpsc::{channel, Sender};
use std::thread;
use std::time::Duration;
use fs2::FileExt;
use notify::{self, RecursiveMode, Watcher};
use output::WranglerjsOutput;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use semver::Version;
use crate::install;
use crate::settings::toml::Target;
use crate::terminal::message::{Message, StdErr, StdOut};
use crate::upload::package::Package;
use crate::watch::{wait_for_changes, COOLDOWN_PERIOD};
use guarded_command::GuardedCommand;
pub fn run_build(target: &Target) -> Result<WranglerjsOutput, failure::Error> {
let (mut command, temp_file, bundle) = setup_build(target)?;
log::info!("Running {:?}", command);
let status = command.status()?;
if status.success() {
let output = fs::read_to_string(&temp_file).expect("could not retrieve output");
fs::remove_file(temp_file)?;
let wranglerjs_output: WranglerjsOutput =
serde_json::from_str(&output).expect("could not parse wranglerjs output");
let custom_webpack = target.webpack_config.is_some();
write_wranglerjs_output(&bundle, &wranglerjs_output, custom_webpack)?;
Ok(wranglerjs_output)
} else {
failure::bail!("failed to execute `{:?}`: exited with {}", command, status)
}
}
pub fn run_build_and_watch(target: &Target, tx: Option<Sender<()>>) -> Result<(), failure::Error> {
let (mut command, temp_file, bundle) = setup_build(target)?;
command.arg("--watch=1");
let is_site = target.site.clone();
let custom_webpack = target.webpack_config.is_some();
log::info!("Running {:?} in watch mode", command);
thread::spawn::<_, Result<(), failure::Error>>(move || {
let _command_guard = GuardedCommand::spawn(command);
let (watcher_tx, watcher_rx) = channel();
let mut watcher = notify::watcher(watcher_tx, Duration::from_secs(1))?;
watcher.watch(&temp_file, RecursiveMode::Recursive)?;
log::info!("watching temp file {:?}", &temp_file);
if let Some(site) = is_site {
let bucket = site.bucket;
if Path::new(&bucket).exists() {
watcher.watch(&bucket, RecursiveMode::Recursive)?;
log::info!("watching static sites asset file {:?}", &bucket);
} else {
failure::bail!(
"Attempting to watch static assets bucket \"{}\" which doesn't exist",
bucket.display()
);
}
}
let mut is_first = true;
loop {
match wait_for_changes(&watcher_rx, COOLDOWN_PERIOD) {
Ok(_) => {
if is_first {
is_first = false;
StdOut::info("Ignoring stale first change");
continue;
}
let output = fs::read_to_string(&temp_file).expect("could not retrieve output");
let wranglerjs_output: WranglerjsOutput =
serde_json::from_str(&output).expect("could not parse wranglerjs output");
if write_wranglerjs_output(&bundle, &wranglerjs_output, custom_webpack).is_ok()
{
if let Some(tx) = tx.clone() {
tx.send(()).expect("--watch change message failed to send");
}
}
}
Err(_) => StdOut::user_error("Something went wrong while watching."),
}
}
});
Ok(())
}
fn write_wranglerjs_output(
bundle: &Bundle,
output: &WranglerjsOutput,
custom_webpack: bool,
) -> Result<(), failure::Error> {
if output.has_errors() {
StdErr::user_error(output.get_errors().as_str());
if custom_webpack {
failure::bail!(
"webpack returned an error. Try configuring `entry` in your webpack config relative to the current working directory, or setting `context = __dirname` in your webpack config."
);
} else {
failure::bail!(
"webpack returned an error. You may be able to resolve this issue by running npm install."
);
}
}
bundle.write(output)?;
log::info!(
"Built successfully, built project size is {}",
output.project_size()
);
Ok(())
}
fn setup_build(target: &Target) -> Result<(Command, PathBuf, Bundle), failure::Error> {
for tool in &["node", "npm"] {
env_dep_installed(tool)?;
}
let build_dir = target.build_dir()?;
if let Some(site) = &target.site {
site.scaffold_worker()?;
}
run_npm_install(&build_dir).expect("could not run `npm install`");
let node = which::which("node").unwrap();
let mut command = Command::new(node);
let wranglerjs_path = install().expect("could not install wranglerjs");
command.arg(wranglerjs_path);
let mut temp_file = env::temp_dir();
temp_file.push(format!(".wranglerjs_output{}", random_chars(5)));
File::create(temp_file.clone())?;
command.arg(format!(
"--output-file={}",
temp_file.to_str().unwrap().to_string()
));
let bundle = Bundle::new(&build_dir);
command.arg(format!("--wasm-binding={}", bundle.get_wasm_binding()));
let custom_webpack_config_path = match &target.webpack_config {
Some(webpack_config) => Some(PathBuf::from(&webpack_config)),
None => {
let config_path = PathBuf::from("webpack.config.js".to_string());
if config_path.exists() {
StdOut::warn("If you would like to use your own custom webpack configuration, you will need to add this to your configuration file:\nwebpack_config = \"webpack.config.js\"");
}
None
}
};
if let Some(webpack_config_path) = custom_webpack_config_path {
build_with_custom_webpack(&mut command, &webpack_config_path);
} else {
build_with_default_webpack(&mut command, &build_dir)?;
}
Ok((command, temp_file, bundle))
}
fn build_with_custom_webpack(command: &mut Command, webpack_config_path: &PathBuf) {
command.arg(format!(
"--webpack-config={}",
&webpack_config_path.to_str().unwrap().to_string()
));
}
fn build_with_default_webpack(
command: &mut Command,
build_dir: &PathBuf,
) -> Result<(), failure::Error> {
let package = Package::new(&build_dir)?;
let package_main = build_dir
.join(package.main(&build_dir)?)
.to_str()
.unwrap()
.to_string();
command.arg("--no-webpack-config=1");
command.arg(format!("--use-entry={}", package_main));
Ok(())
}
fn run_npm_install(dir: &PathBuf) -> Result<(), failure::Error> {
let flock_path = dir.join(&".install.lock");
let flock = File::create(&flock_path)?;
flock.lock_exclusive()?;
if !dir.join("node_modules").exists() {
let mut command = build_npm_command();
command.current_dir(dir.clone());
command.arg("install");
log::info!("Running {:?} in directory {:?}", command, dir);
let status = command.status()?;
if !status.success() {
failure::bail!("failed to execute `{:?}`: exited with {}", command, status)
}
} else {
log::info!("skipping npm install because node_modules exists");
}
if flock_path.exists() {
fs::remove_file(&flock_path)?;
}
flock.unlock()?;
Ok(())
}
fn build_npm_command() -> Command {
if install::target::WINDOWS {
let mut command = Command::new("cmd");
command.arg("/C");
command.arg("npm");
command
} else {
Command::new("npm")
}
}
fn env_dep_installed(tool: &str) -> Result<(), failure::Error> {
if which::which(tool).is_err() {
failure::bail!("You need to install {}", tool)
}
Ok(())
}
fn get_source_dir() -> PathBuf {
let mut dir = install::target::SOURCE_DIR.to_string();
dir.remove(0);
dir.remove(dir.len() - 1);
Path::new(&dir).to_path_buf()
}
fn install() -> Result<PathBuf, failure::Error> {
let wranglerjs_path = if install::target::DEBUG {
let source_path = get_source_dir();
let wranglerjs_path = source_path.join("wranglerjs");
log::info!("wranglerjs at: {:?}", wranglerjs_path);
wranglerjs_path
} else {
let tool_name = "wranglerjs";
let tool_author = "cloudflare";
let is_binary = false;
let version = Version::parse(env!("CARGO_PKG_VERSION"))?;
let wranglerjs_path = install::install(tool_name, tool_author, is_binary, version)?;
log::info!("wranglerjs downloaded at: {:?}", wranglerjs_path.path());
wranglerjs_path.path()
};
run_npm_install(&wranglerjs_path).expect("could not install wranglerjs dependencies");
Ok(wranglerjs_path)
}
fn random_chars(n: usize) -> String {
let mut rng = thread_rng();
iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.take(n)
.collect()
}