UNPKG

2.76 kBJavaScriptView Raw
1"use strict";
2var path = require("path");
3var chokidar = require("chokidar");
4var fableLib = require("./lib");
5var bundle_1 = require("./bundle");
6function tooClose(opts, filename, prev) {
7 var d = new Date();
8 return opts.watching !== "BUILDING" &&
9 prev != null &&
10 filename == prev[0] &&
11 new Date().getTime() - prev[1].getTime() < 2000;
12}
13/** Watches for file changes. Requires chokidar */
14function watch(opts, buildResult, fableProc, parallelProc, continuation) {
15 if (opts.watching) {
16 if (buildResult === "NEEDS_FULL_REBUILD") {
17 fableLib.stdoutLog("Triggering full rebuild...");
18 fableProc.stdin.write("[SIGFAIL]\n");
19 }
20 else {
21 // Reset opts.watching
22 opts.watching = "WATCHING";
23 }
24 return;
25 }
26 var next = null, prev = null;
27 fableProc.stdin.setEncoding("utf-8");
28 var dirs = null;
29 if (typeof opts.watch === "string") {
30 dirs = [fableLib.pathJoin(opts.workingDir, opts.watch)];
31 }
32 else if (Array.isArray(opts.watch) && opts.watch.length > 0) {
33 dirs = opts.watch.map(function (dir) { return fableLib.pathJoin(opts.workingDir, dir); });
34 }
35 else {
36 dirs = opts.projFile.map(function (dir) { return path.dirname(fableLib.pathJoin(opts.workingDir, dir)); });
37 }
38 fableLib.stdoutLog("Watching " + dirs.join('\n\t'));
39 fableLib.stdoutLog("Press Enter to terminate process.");
40 opts.watching = "WATCHING";
41 var ready = false;
42 var watcher = chokidar
43 .watch(dirs, { ignored: /node_modules/, persistent: true })
44 .on("ready", function () { ready = true; })
45 .on("all", function (ev, filePath) {
46 if (ready) {
47 if (fableLib.isFSharpFile(filePath)) {
48 prev = next;
49 next = [filePath, new Date()];
50 if (!tooClose(opts, filePath, prev)) {
51 fableLib.stdoutLog(ev + ": " + filePath + " at " + next[1].toLocaleTimeString());
52 opts.watching = "BUILDING";
53 fableProc.stdin.write(filePath + "\n");
54 }
55 }
56 }
57 });
58 process.stdin.on('data', function (buf) {
59 var data = buf.toString();
60 if (data.length > 0 && data[data.length - 1] == '\n') {
61 if (parallelProc) {
62 parallelProc.kill();
63 }
64 fableProc.stdin.write("[SIGTERM]\n");
65 watcher.close();
66 bundle_1.clearBundleCache(); // Clean bundle cache just in case
67 fableLib.stdoutLog("Process terminated.");
68 fableLib.finish(0, continuation);
69 }
70 });
71}
72exports.watch = watch;