UNPKG

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