-
Notifications
You must be signed in to change notification settings - Fork 47
/
index.js
204 lines (166 loc) · 5.65 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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
const treeKill = require('tree-kill')
const { resolve } = require('path')
const { exec } = require('child_process')
const { spawn } = require('cross-spawn')
const chokidar = require('chokidar')
const arrify = require('arrify')
const { Deque } = require('@blakeembrey/deque')
const ECHO_CMD = `${process.execPath} ${resolve(__dirname, 'echo.js')}`
/**
* Export `onchange` function.
*/
module.exports = onchange
/**
* Execute a "job" on each change event.
*/
class Job {
constructor (command, args, outpipe, options) {
this.command = command
this.args = args
this.outpipe = outpipe
this.options = options
}
start (cwd, log, stdout, stderr, onexit) {
if (this.outpipe) {
const cmd = this.outpipe(opts)
log(`executing outpipe "${cmd}"`)
this.childOutpipe = exec(cmd, { cwd })
// Must pipe stdout and stderr.
this.childOutpipe.stdout.pipe(stdout)
this.childOutpipe.stderr.pipe(stderr)
this.childOutpipe.on('exit', (code, signal) => {
log(`outpipe ${exitmsg(code, signal)}`)
this.childOutpipe = undefined
if (!this.childCommand) return onexit()
})
}
if (this.command) {
// Generate argument strings from templates.
const cmd = this.args.map(tmpl => tmpl(this.options))
const stdio = ['ignore', this.childOutpipe ? this.childOutpipe.stdin : stdout, stderr]
log(`executing command "${[this.command].concat(cmd).join(' ')}"`)
// Spawn child command. If `outpipe`, pipe `stdout` through `outpipe`.
this.childCommand = spawn(this.command, cmd, { cwd, stdio })
this.childCommand.on('exit', function (code, signal) {
log(`command ${exitmsg(code, signal)}`)
this.childCommand = undefined
if (!this.childOutpipe) return onexit()
})
} else {
// No data to write to `outpipe`.
childOutpipe.stdin.end()
}
}
kill (log, killSignal) {
if (this.childOutpipe) {
log(`killing outpipe ${this.childOutpipe.pid}`)
treeKill(this.childOutpipe.pid, killSignal)
}
if (this.childCommand) {
log(`killing command ${this.childOutpipe.pid}`)
treeKill(this.childCommand.pid, killSignal)
}
}
}
function onchange (match, command, rawargs, opts = {}) {
const matches = arrify(match)
const ready = opts.ready || (() => undefined)
const initial = !!opts.initial
const kill = !!opts.kill
const cwd = opts.cwd ? resolve(opts.cwd) : process.cwd()
const stdout = opts.stdout || process.stdout
const stderr = opts.stderr || process.stderr
const delay = Math.max(opts.delay | 0, 0)
const jobs = Math.max(opts.jobs | 0, 1)
const killSignal = opts.killSignal || 'SIGTERM'
const args = rawargs ? rawargs.map(tmpl) : []
const outpipe = typeof opts.outpipe === 'string' ? outpipetmpl(opts.outpipe) : undefined
const filter = opts.filter || []
const awaitWriteFinish = !!opts.awaitWriteFinish
const running = new Set()
const queue = new Deque()
// Logging.
const log = opts.verbose ? function log (message) {
stdout.write('onchange: ' + message + '\n')
} : function () {}
// Invalid, nothing to run on change.
if (!command && !outpipe) {
throw new TypeError('Expected "command" and/or "outpipe" to be specified')
}
// Create the "watcher" instance for file system changes.
const watcher = chokidar.watch(matches, {
cwd: cwd,
ignored: opts.exclude || [],
usePolling: opts.poll === true || typeof opts.poll === 'number',
interval: typeof opts.poll === 'number' ? opts.poll : undefined,
awaitWriteFinish: awaitWriteFinish
})
/**
* Try and dequeue the next job to run.
*/
function dequeue () {
// Nothing to process.
if (queue.size === 0) return
// Too many jobs running already.
if (running.size >= jobs) return
// Remove first job from queue (FIFO).
const job = queue.popLeft()
// Add job to running set.
running.add(job)
// Start the process and remove when finished.
job.start(cwd, log, stdout, stderr, () => {
running.delete(job)
if (delay > 0) return setTimeout(dequeue, delay)
return dequeue()
})
}
/**
* Enqueue the next change event to run.
*/
function enqueue (event, changed) {
// Kill all existing tasks on `enqueue`.
if (kill) {
queue.clear() // Remove pending ("killed") tasks.
running.forEach(child => child.kill(killSignal)) // Kill running tasks.
}
// Log the event and the file affected.
log(`"${changed}" -> ${event}`)
// Add item to job queue.
queue.push(new Job(command, args, outpipe, { event, changed }))
// Try to immediately run the enqueued job.
return dequeue()
}
watcher.on('ready', () => {
log(`watching ${matches.join(', ')}`)
// Execute initial event without any changes.
if (initial) enqueue('', '')
// For any change, creation or deletion, try to run.
watcher.on('all', (event, changed) => {
if (filter.length && filter.indexOf(event) === -1) return
return enqueue(event, changed)
})
// Notify external listener of "ready" event.
ready()
})
watcher.on('error', (error) => log(`watcher error: ${error}`))
}
// Double mustache template generator.
function tmpl (str) {
return function (data) {
return str.replace(/{{([^{}]+)}}/g, function (_, key) {
return data[key]
})
}
}
// Template generator for `outpipe` option.
function outpipetmpl (str) {
var value = str.trim()
if (value.charAt(0) === '|' || value.charAt(0) === '>') {
return tmpl(`${ECHO_CMD} ${value}`)
}
return tmpl(value)
}
// Simple exit message generator.
function exitmsg (code, signal) {
return code == null ? `exited with ${signal}` : `completed with ${code}`
}