UNPKG

1.4 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3const { yellow, magenta } = require('chalk')
4const { spawnSync } = require('child_process')
5const { existsSync, readFileSync, writeFileSync } = require('fs')
6const { encoding } = require('./defaults')
7
8const {
9 getChecksum,
10 getChecksumFilePath,
11 hashFromFileContent,
12} = require('./checksum')
13
14const 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
33const getPastChecksum = path =>
34 existsSync(path) ? hashFromFileContent(readFileSync(path, encoding)) : null
35
36const checksum = getChecksum(readFileSync(argv.file, encoding))
37const checksumFilePath = getChecksumFilePath(argv.file)
38const pastChecksum = getPastChecksum(checksumFilePath)
39
40if (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}