-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatch.js
81 lines (68 loc) · 1.96 KB
/
watch.js
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
const chokidar = require('chokidar');
const fs = require('fs')
const Queue = require('better-queue');
const { spawnSync } = require('child_process');
DEFAULT_WATCHER_CONFIG = {
'test': {
'cmd': 'truffle',
'args': ['test'],
'files': ['contracts/', 'test/']
}
}
function loadWatcherConfig(configFile) {
let rawdata = fs.readFileSync(configFile);
return JSON.parse(rawdata);
}
// Object that keeps track of which names have active processes
nameToActiveProcess = {}
// Queue for synchronously running each logging command
processQueue = new Queue((procDef, cb) => {
const [name, cmd, args] = procDef;
spawnSync(cmd, args, {
cwd: process.cwd(),
env: process.env,
stdio: [process.stdin, process.stdout, process.stderr],
encoding: 'utf-8'
})
nameToActiveProcess[name] = false;
cb(null);
});
/**
* Setup a watcher for a single command/regex
*/
function setupWatcher(name, regexes, cmd, args) {
chokidar.watch(regexes).on('change', async (event, path) => {
// Don't allow multiple processes of the same name be added to the queue simultaneously!
if (!nameToActiveProcess[name]) {
nameToActiveProcess[name] = true;
processQueue.push([name, cmd, args]);
}
});
}
async function delay(ms) {
return new Promise((resolve) => {
setTimeout(() => resolve(), ms)
})
}
module.exports = async (config) => {
if (config.help) {
console.log('Usage: truffle run watch [options]');
console.log('');
console.log('Options:');
console.log(' --config [CONFIG_FILE] Use the specified CONFIG_FILE to determine watchers');
return;
}
watcherConfig = config.config ? loadWatcherConfig(config.config) : DEFAULT_WATCHER_CONFIG;
for (var name in watcherConfig) {
setupWatcher(
name,
watcherConfig[name]['files'],
watcherConfig[name]['cmd'],
watcherConfig[name]['args']
)
}
// NOTE: not the cleanest way to avoid exiting, but it works
while (true) {
await delay(2000);
}
}