1 | 'use strict';
|
2 |
|
3 | const buntstift = require('buntstift').default,
|
4 | chokidar = require('chokidar');
|
5 |
|
6 | const noop = require('./noop');
|
7 |
|
8 | let isCurrentlyExecuting = false;
|
9 |
|
10 | const 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 |
|
35 |
|
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 |
|
60 | module.exports = watchFilesAndExecute;
|