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
mod bundle;
mod guarded_command;
pub mod output;

pub use bundle::Bundle;

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 std::{env, io};

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;

// Run the underlying {wranglerjs} executable.

// In Rust we create a virtual file, pass it to {wranglerjs}, run the
// executable and wait for completion. The file will receive a serialized
// {WranglerjsOutput} struct.
// Note that the ability to pass a fd is platform-specific
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);

    // Turbofish the result of the closure so we can use ?
    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");
                        // skip the first change event
                        // so we don't do a refresh immediately
                        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(())
}

//setup a build to run wranglerjs, return the command, the ipc temp file, and the bundle
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);

    // create a temp file for IPC with the wranglerjs process
    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 webpack_config is not configured in the manifest
    // we infer the entry based on {package.json} and pass it to {wranglerjs}
    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(())
}

// Run {npm install} in the specified directory. Skips the install if a
// {node_modules} is found in the directory.
fn run_npm_install(dir: &PathBuf) -> Result<(), failure::Error> {
    let flock_path = dir.join(&".install.lock");
    let flock = File::create(&flock_path)?;
    // avoid running multiple {npm install} at the same time (eg. in tests)
    flock.lock_exclusive()?;

    if !dir.join("node_modules").exists() {
        // no dir in current path, search for closest
        match find_closest_dir("node_modules", dir.as_path()) {
            Ok(result) => match result {
                Some(_) => {
                    log::info!("skipping npm install because node_modules exists in parent dir")
                }
                None => {
                    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)
                    }
                }
            },
            Err(error) => failure::bail!(
                "failed to find closest node_modules due to error: {:?}",
                error
            ),
        }
    } else {
        log::info!("skipping npm install because node_modules exists");
    }

    // TODO: (sven) figure out why the file doesn't exist in some cases
    if flock_path.exists() {
        fs::remove_file(&flock_path)?;
    }
    flock.unlock()?;

    Ok(())
}

// find closest (bottom-up traversal) location of a file or dir
fn find_closest_dir<'a>(name: &str, path: &'a Path) -> Result<Option<&'a Path>, io::Error> {
    match has_dir(name, path) {
        Ok(result) => {
            if result {
                return Ok(Option::from(path));
            }
            // If has parent lets check it
            match path.parent() {
                Some(parent_path) => find_closest_dir(name, parent_path),
                None => Ok(None),
            }
        }
        Err(e) => Err(e),
    }
}

// check if dir has file with provided name
fn has_dir(name: &str, path: &Path) -> Result<bool, io::Error> {
    for entry in fs::read_dir(path)? {
        let dir = entry?;
        if dir.file_name() == name {
            return Ok(true);
        }
    }

    Ok(false)
}

// build a Command for npm
//
// Here's the deal: on Windows, `npm` isn't a binary, it's a shell script.
// This means that we can't invoke it via `Command` directly on Windows,
// we need to invoke `cmd /C npm`, to run it within the cmd environment.
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")
    }
}

// Ensures the specified tool is available in our env.
fn env_dep_installed(tool: &str) -> Result<(), failure::Error> {
    if which::which(tool).is_err() {
        failure::bail!("You need to install {}", tool)
    }
    Ok(())
}

// Use the env-provided source directory and remove the quotes
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()
}

// Install {wranglerjs} from our GitHub releases
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()
}