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 | getChecksum,
|
9 | getChecksumFilePath,
|
10 | hashFromFileContent,
|
11 | } = require('./checksum')
|
12 |
|
13 | const argv = require('yargs')
|
14 | .scriptName('on-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 | .option('color', {
|
27 | default: false,
|
28 | describe: 'Force color, default auto',
|
29 | type: 'boolean',
|
30 | })
|
31 | .option('no-color', {
|
32 | default: false,
|
33 | describe: 'Disable color output',
|
34 | type: 'boolean',
|
35 | })
|
36 | .demandCommand(1).argv
|
37 |
|
38 | const UTF = 'utf8'
|
39 |
|
40 | const getPastChecksum = path =>
|
41 | existsSync(path) ? hashFromFileContent(readFileSync(path, UTF)) : null
|
42 |
|
43 | const checksum = getChecksum(readFileSync(argv.file, UTF))
|
44 | const checksumFilePath = getChecksumFilePath(argv.file)
|
45 | const pastChecksum = getPastChecksum(checksumFilePath)
|
46 |
|
47 | if (checksum !== pastChecksum) {
|
48 | console.log(
|
49 | `File "${magenta(argv.file)}" has changed.`,
|
50 | `Running "${yellow(argv._.join(' '))}"...`,
|
51 | )
|
52 |
|
53 | const [command, ...args] = argv._
|
54 | spawnSync(command, args, { encoding: UTF, stdio: 'inherit' })
|
55 | writeFileSync(checksumFilePath, `${checksum} ${argv.file}`)
|
56 | }
|