1 | #!/usr/bin/env node
|
2 |
|
3 | const { yellow, magenta } = require('chalk')
|
4 | const { spawnSync } = require('child_process')
|
5 | const { existsSync, readFileSync, writeFileSync } = require('fs')
|
6 | const { encoding } = require('./defaults')
|
7 |
|
8 | const {
|
9 | getChecksum,
|
10 | getChecksumFilePath,
|
11 | hashFromFileContent,
|
12 | } = require('./checksum')
|
13 |
|
14 | const argv = require('yargs')
|
15 | .scriptName('on-change')
|
16 | .usage('Usage: $0 --file [file] [command]')
|
17 | .example(
|
18 | '$0 --file package-lock.json npm ci',
|
19 | 'Reinstall dependencies on changed package-lock.json',
|
20 | )
|
21 | .option('file', {
|
22 | alias: 'f',
|
23 | demandOption: true,
|
24 | describe: 'Path to file to check for changes',
|
25 | type: 'string',
|
26 | })
|
27 | .option('color', {
|
28 | describe: 'Force color or disable with --no-color',
|
29 | type: 'boolean',
|
30 | })
|
31 | .demandCommand(1).argv
|
32 |
|
33 | const getPastChecksum = path =>
|
34 | existsSync(path) ? hashFromFileContent(readFileSync(path, encoding)) : null
|
35 |
|
36 | const checksum = getChecksum(readFileSync(argv.file, encoding))
|
37 | const checksumFilePath = getChecksumFilePath(argv.file)
|
38 | const pastChecksum = getPastChecksum(checksumFilePath)
|
39 |
|
40 | if (checksum !== pastChecksum) {
|
41 | console.log(
|
42 | `File "${magenta(argv.file)}" has changed.`,
|
43 | `Running "${yellow(argv._.join(' '))}"...`,
|
44 | )
|
45 |
|
46 | const [command, ...args] = argv._
|
47 | spawnSync(command, args, { encoding, stdio: 'inherit' })
|
48 | writeFileSync(checksumFilePath, `${checksum} ${argv.file}`)
|
49 | }
|