diff --git a/README.md b/README.md index a18971cd..b1543ea0 100644 --- a/README.md +++ b/README.md @@ -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` | diff --git a/args.js b/args.js index 452d603a..30f93c65 100644 --- a/args.js +++ b/args.js @@ -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' }, @@ -116,6 +117,7 @@ module.exports = function parseCliArgs (args) { commonPrefix: parsedArgs.commonPrefix, includeHooks: parsedArgs.includeHooks, followWatch: followWatchArg, + onWatch: parsedArgs.onWatch, trustProxy } } diff --git a/help/start.txt b/help/start.txt index 330da629..62dc158a 100644 --- a/help/start.txt +++ b/help/start.txt @@ -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 diff --git a/lib/watch/index.js b/lib/watch/index.js index db58786f..970baf1a 100644 --- a/lib/watch/index.js +++ b/lib/watch/index.js @@ -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() @@ -26,6 +28,9 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch) { } if (watcher) { allStop = true + if (onWatchProc) { + onWatchProc.kill() + } return watcher.close() } } @@ -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() + } + }) }) }) diff --git a/start.js b/start.js index 28442fbb..566ad992 100755 --- a/start.js +++ b/start.js @@ -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) diff --git a/test/args.test.js b/test/args.test.js index ef73b07f..f7085ad3 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -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', @@ -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', @@ -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', @@ -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, @@ -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', @@ -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', @@ -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', @@ -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, @@ -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, diff --git a/test/watch-unit.test.js b/test/watch-unit.test.js index 31d65545..8c7251ef 100644 --- a/test/watch-unit.test.js +++ b/test/watch-unit.test.js @@ -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() @@ -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 => { @@ -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`)