Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ You can pass the following options via CLI arguments. You can also use `--config
| Ignore changes to the specified files or directories when watch is enabled. (e.g. `--ignore-watch='node_modules .git logs/error.log'` ) | | `--ignore-watch` | `FASTIFY_IGNORE_WATCH` |
| Watch changes only into the specified files or directories when watch is enabled. (e.g. `--follow-watch='plugins/'` ) | | `--follow-watch` | `FASTIFY_FOLLOW_WATCH` |
| Prints events triggered by watch listener (useful to debug unexpected reload when using `--watch` ) | `-V` | `--verbose-watch` | `FASTIFY_VERBOSE_WATCH` |
| Run a shell command on every watched change, before the process reloads (e.g. `--on-watch='npm run lint'` ). Add files the command writes to `--ignore-watch` | | `--on-watch` | `FASTIFY_ON_WATCH` |
| Use custom options | `-o` | `--options` | `FASTIFY_OPTIONS` |
| Set the prefix | `-x` | `--prefix` | `FASTIFY_PREFIX` |
| Set the plugin timeout | `-T` | `--plugin-timeout` | `FASTIFY_PLUGIN_TIMEOUT` |
Expand Down
2 changes: 2 additions & 0 deletions args.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ const CLI_OPTIONS = {
method: { type: 'string' },
'trust-proxy-ips': { type: 'string' },
'follow-watch': { type: 'string' },
'on-watch': { type: 'string' },
'pretty-logs': { type: 'boolean', short: 'P' },
options: { type: 'boolean', short: 'o' },
watch: { type: 'boolean', short: 'w' },
Expand Down Expand Up @@ -116,6 +117,7 @@ module.exports = function parseCliArgs (args) {
commonPrefix: parsedArgs.commonPrefix,
includeHooks: parsedArgs.includeHooks,
followWatch: followWatchArg,
onWatch: parsedArgs.onWatch,
trustProxy
}
}
5 changes: 5 additions & 0 deletions help/start.txt
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ OPTS
[env: FASTIFY_VERBOSE_WATCH]
Print all watch events to the console

--on-watch
[env: FASTIFY_ON_WATCH]
Run a shell command on every watched change, before the process reloads (e.g. --on-watch='npm run lint').
Add files the command writes to --ignore-watch, otherwise each run triggers the next one.

-x, --prefix
[env: FASTIFY_PREFIX]
Set the prefix
Expand Down
41 changes: 34 additions & 7 deletions lib/watch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ const chokidar = require('chokidar')
const { loadEnvQuitely } = require('../../env-loader.js')
const forkPath = path.join(__dirname, './fork.js')

const watch = function (args, ignoreWatch, verboseWatch, followWatch) {
const watch = function (args, ignoreWatch, verboseWatch, followWatch, onWatch) {
const emitter = new EventEmitter()
let allStop = false
let childs = []
// The running on-watch command, if any
let onWatchProc = null
const stop = (watcher = null, err = null) => {
childs.forEach(function (child) {
child.kill()
Expand All @@ -26,6 +28,9 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch) {
}
if (watcher) {
allStop = true
if (onWatchProc) {
onWatchProc.kill()
}
return watcher.close()
}
}
Expand Down Expand Up @@ -81,18 +86,40 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch) {
const ignoredPattern = arrayToRegExp(ignoredArr)
const watchDir = followWatch || process.cwd()
const watcher = chokidar.watch(watchDir, { ignored: ignoredPattern })
const restart = () => {
try {
const child = childs.shift()
child.send(GRACEFUL_SHUT)
} catch (err) {
// the previous child already exited: start a new one
childs.push(run('restart'))
}
}
watcher.on('ready', function () {
watcher.on('all', function (event, filepath) {
if (verboseWatch) {
logWatchVerbose(event, filepath)
}
try {
const child = childs.shift()
child.send(GRACEFUL_SHUT)
} catch (err) {
// the previous child already exited: start a new one
childs.push(run('restart'))
if (!onWatch) {
return restart()
}
// Changes made while the command runs are picked up by the restart that
// follows it, so they don't start another run.
if (onWatchProc) {
return
}
onWatchProc = cp.spawn(onWatch, { shell: true, stdio: 'inherit' })
onWatchProc
.on('error', (err) => console.log(chalk.red(err)))
.on('close', (code) => {
onWatchProc = null
if (code !== 0) {
console.log(chalk.red(`[fastify-cli] on-watch command exited with code ${code}`))
}
if (!allStop) {
restart()
}
})
})
})

Expand Down
2 changes: 1 addition & 1 deletion start.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ async function start (args) {
loadModules(opts)

if (opts.watch) {
return watch(args, opts.ignoreWatch, opts.verboseWatch, opts.followWatch)
return watch(args, opts.ignoreWatch, opts.verboseWatch, opts.followWatch, opts.onWatch)
}

return runFastify(args)
Expand Down
9 changes: 9 additions & 0 deletions test/args.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ test('should parse args correctly', t => {
'--ignore-watch', 'ignoreme.js',
'--follow-watch', 'watchme.js',
'--verbose-watch', 'true',
'--on-watch', 'npm run lint',
'--options', 'true',
'--prefix', 'FASTIFY_',
'--plugin-timeout', '500',
Expand All @@ -41,6 +42,7 @@ test('should parse args correctly', t => {
watch: true,
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js',
followWatch: 'watchme.js',
onWatch: 'npm run lint',
verboseWatch: true,
port: 7777,
address: 'fastify.dev:9999',
Expand Down Expand Up @@ -103,6 +105,7 @@ test('should parse args with = assignment correctly', t => {
watch: true,
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js',
followWatch: 'watchme.js',
onWatch: undefined,
verboseWatch: true,
port: 7777,
address: 'fastify.dev:9999',
Expand Down Expand Up @@ -186,6 +189,7 @@ test('should parse env vars correctly', t => {
watch: true,
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js',
followWatch: 'plugin/',
onWatch: undefined,
verboseWatch: true,
address: 'fastify.dev:9999',
bodyLimit: 5242880,
Expand Down Expand Up @@ -291,6 +295,7 @@ test('should parse custom plugin options', t => {
watch: true,
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js',
followWatch: 'watchme.js',
onWatch: undefined,
verboseWatch: true,
port: 7777,
address: 'fastify.dev:9999',
Expand Down Expand Up @@ -346,6 +351,7 @@ test('should parse config file correctly and prefer config values over default o
debugHost: '1.1.1.1',
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output',
followWatch: '',
onWatch: undefined,
verboseWatch: false,
logLevel: 'fatal',
address: 'fastify.dev:9999',
Expand Down Expand Up @@ -392,6 +398,7 @@ test('should prefer command line args over config file options', t => {
debugHost: '1.1.1.1',
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output',
followWatch: '',
onWatch: undefined,
verboseWatch: false,
logLevel: 'fatal',
address: 'fastify.dev:9999',
Expand Down Expand Up @@ -440,6 +447,7 @@ test('should favor trust proxy enabled over trust proxy ips and trust proxy hop'
debugHost: '1.1.1.1',
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output',
followWatch: '',
onWatch: undefined,
verboseWatch: false,
logLevel: 'fatal',
address: undefined,
Expand Down Expand Up @@ -487,6 +495,7 @@ test('should favor trust proxy ips over trust proxy hop', t => {
debugHost: '1.1.1.1',
ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output',
followWatch: '',
onWatch: undefined,
verboseWatch: false,
logLevel: 'fatal',
address: undefined,
Expand Down
69 changes: 68 additions & 1 deletion test/watch-unit.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@ const { GRACEFUL_SHUT } = require('../lib/watch/constants')
// so the restart logic can be driven synchronously.
function setup (t) {
const forks = []
const spawns = []
const childProcessMock = {
spawn (command, options) {
const proc = new EventEmitter()
proc.kill = t.mock.fn()
spawns.push({ command, options, proc })
return proc
},
fork () {
const child = new EventEmitter()
child.kill = t.mock.fn()
Expand All @@ -35,7 +42,7 @@ function setup (t) {
'node:child_process': childProcessMock
})

return { watch, forks, watcher, uncaught }
return { watch, forks, spawns, watcher, uncaught }
}

test('should restart the child when a watched file changes', t => {
Expand Down Expand Up @@ -120,6 +127,66 @@ test('should restart the child on an uncaught exception', t => {
t.assert.strictEqual(forks.length, 2)
})

test('should run the on-watch command before restarting the child', t => {
const { watch, forks, spawns, watcher } = setup(t)
watch(['app.js'], 'node_modules', false, undefined, 'npm run lint')

watcher.emit('ready')
watcher.emit('all', 'change', 'app.js')

t.assert.strictEqual(spawns.length, 1)
t.assert.strictEqual(spawns[0].command, 'npm run lint')
t.assert.deepStrictEqual(spawns[0].options, { shell: true, stdio: 'inherit' })
t.assert.strictEqual(forks[0].send.mock.callCount(), 0, 'no restart while the command runs')

spawns[0].proc.emit('close', 0)
t.assert.strictEqual(forks[0].send.mock.calls[0].arguments[0], GRACEFUL_SHUT)
t.assert.strictEqual(console.log.mock.callCount(), 0)
})

test('should not start another on-watch run for changes made while one is running', t => {
const { watch, forks, spawns, watcher } = setup(t)
watch(['app.js'], 'node_modules', false, undefined, 'npm run lint')

watcher.emit('ready')
watcher.emit('all', 'change', 'app.js')
watcher.emit('all', 'change', 'lib/a.js')
t.assert.strictEqual(spawns.length, 1)

spawns[0].proc.emit('close', 0)
t.assert.strictEqual(forks[0].send.mock.callCount(), 1)

watcher.emit('all', 'change', 'app.js')
t.assert.strictEqual(spawns.length, 2, 'a later change runs the command again')
})

test('should log a failing on-watch command and still restart the child', t => {
const { watch, forks, spawns, watcher } = setup(t)
watch(['app.js'], 'node_modules', false, undefined, 'npm run lint')

watcher.emit('ready')
watcher.emit('all', 'change', 'app.js')
spawns[0].proc.emit('error', new Error('spawn failed'))
spawns[0].proc.emit('close', 1)

t.assert.match(console.log.mock.calls[0].arguments[0], /spawn failed/)
t.assert.match(console.log.mock.calls[1].arguments[0], /on-watch command exited with code 1/)
t.assert.strictEqual(forks[0].send.mock.calls[0].arguments[0], GRACEFUL_SHUT)
})

test('should kill a running on-watch command on stop and not restart', t => {
const { watch, forks, spawns, watcher } = setup(t)
const emitter = watch(['app.js'], 'node_modules', false, undefined, 'npm run lint')

watcher.emit('ready')
watcher.emit('all', 'change', 'app.js')
emitter.stop()
t.assert.strictEqual(spawns[0].proc.kill.mock.callCount(), 1)
spawns[0].proc.emit('close', null)

t.assert.strictEqual(forks.length, 1)
})

test('logWatchVerbose should print the relative path', t => {
t.mock.method(console, 'log', () => {})
logWatchVerbose('add', `${process.cwd()}/lib/a.js`)
Expand Down
Loading