chronocat/scripts/runOnChanged.cts

63 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-03-09 17:14:56 +00:00
import * as cp from 'node:child_process'
import * as crypto from 'node:crypto'
2024-03-09 17:14:56 +00:00
import * as fs from 'node:fs'
const watchFolder = process.argv[2]
if (!watchFolder) {
2024-03-09 17:14:56 +00:00
console.error(
'Usage: node -r esbuild-register runOnChanged <folder> <command>',
)
process.exit(1)
}
const command = process.argv.slice(3).join(' ')
// create or compare hash of files in the folder
let hasChanged = false
2024-03-09 17:14:56 +00:00
let hashes = new Map<string, string>()
2024-03-09 17:14:56 +00:00
const sha1 = (data: string) =>
crypto.createHash('sha1').update(data).digest('hex')
const hashFile = (file: string) => {
const hash = sha1(fs.readFileSync(file, 'utf8'))
if (hashes.get(file) !== hash) {
hashes.set(file, hash)
hasChanged = true
}
}
const hashFilepath = `${watchFolder}/.runOnChanged.hashes.json`
const hashFolder = (folder: string) => {
const files = fs.readdirSync(folder)
2024-03-09 17:14:56 +00:00
files.forEach((file) => {
const path = `${folder}/${file}`
if (file.endsWith('.runOnChanged.hashes.json')) return
if (fs.statSync(path).isDirectory()) {
hashFolder(path)
} else {
hashFile(path)
}
})
}
if (fs.existsSync(hashFilepath)) {
2024-03-09 17:14:56 +00:00
const oldHashes = JSON.parse(fs.readFileSync(hashFilepath, 'utf8')) as Record<
string,
string
>
hashes = new Map(Object.entries(oldHashes))
}
hashFolder(watchFolder)
if (hasChanged) {
console.log('[+] Files have changed, rebuilding...')
fs.writeFileSync(hashFilepath, JSON.stringify(Object.fromEntries(hashes)))
2024-03-09 17:14:56 +00:00
cp.execSync(command, { stdio: 'inherit' })
} else {
console.log('[-] Files not changed :)')
}