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