UNPKG

1.31 kBJavaScriptView Raw
1'use strict';
2
3const buntstift = require('buntstift'),
4 chokidar = require('chokidar');
5
6const noop = require('./noop');
7
8let isCurrentlyExecuting = false;
9
10const watchFilesAndExecute = async function ({ message, files, execute, executeOnStart = false }) {
11 if (!message) {
12 throw new Error('Message is missing.');
13 }
14 if (!files) {
15 throw new Error('Files are missing.');
16 }
17 if (!execute) {
18 throw new Error('Execute is missing.');
19 }
20
21 buntstift.line();
22 buntstift.info(message, { prefix: '▸' });
23
24 const handleChange = () => {
25 if (isCurrentlyExecuting) {
26 return;
27 }
28 isCurrentlyExecuting = true;
29
30 (async () => {
31 try {
32 await execute();
33 } catch (ex) {
34 // In watch mode, we ignore any errors (since we do not have an
35 // exit code anyway).
36
37 buntstift.verbose(ex.message);
38 } finally {
39 isCurrentlyExecuting = false;
40 }
41 })();
42 };
43
44 chokidar.watch(files, { ignoreInitial: true }).
45 on('ready', () => {
46 if (executeOnStart) {
47 handleChange();
48 }
49 }).
50 on('all', () => {
51 buntstift.line();
52 buntstift.warn('Changes detected, running again...', { prefix: '▸' });
53
54 handleChange();
55 });
56
57 await new Promise(noop);
58};
59
60module.exports = watchFilesAndExecute;