forked from alexgorbatchev/run-when-changed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (43 loc) · 1.49 KB
/
index.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
import { Gaze } from 'gaze';
import { spawn } from 'child_process';
import { sep } from 'path';
import ansiBold from 'ansi-bold';
import minimatch from 'minimatch';
import formatCmd from './format-cmd';
function startWatching({ watch, match, exec }, options) {
const verbose = options.verbose;
const list = (key, values) => values.map(value => `--${key}=${ansiBold(value)}`).join(', ');
const log = msg => {
if (verbose) {
console.log(msg);
}
};
return new Promise(resolve => {
match = match || [ '**/*' ];
const prefix = [ list('watch', watch), list('match', match), list('exec', exec) ].join(' ');
const gaze = new Gaze(watch, options.gazeOptions);
gaze.on('ready', watcher => {
if (Object.keys(watcher.watched()).length) {
log(`${prefix}: ready!`);
} else {
log(`${prefix}: no matches :(`);
watcher.close();
}
});
gaze.on('changed', filepath => {
const relativeFilepath = filepath.replace(process.cwd() + sep, '');
exec.forEach(cmd => {
if (!match.reduce((last, match) => last && minimatch(relativeFilepath, match, { dot: true }), true)) {
return log(`${prefix}: skipping ${relativeFilepath}`);
}
formatCmd(cmd, filepath).then(cmd => {
log(`${prefix}: ${cmd}`);
spawn(cmd, [], { shell: true, stdio: 'inherit' });
});
});
});
})
}
export default function runWhenChanged(watches, opts) {
watches.forEach(set => startWatching(set, opts));
}