Created
October 3, 2025 08:48
-
-
Save penkin/1488fbc798a9c8fd21227d50d728440f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const fs = require("fs").promises; | |
| const glob = require("fast-glob"); | |
| const crypto = require("crypto"); | |
| const path = require("path"); | |
| const HASHES_FILE = ".if-changes.hashes.json"; | |
| const packageJson = require(path.join(process.cwd(), "package.json")); | |
| const packageConfig = packageJson.onlyIfChanged; | |
| async function getFileHash(globs) { | |
| const hash = crypto.createHash("sha1"); | |
| const files = await glob(globs, { dot: true }); | |
| files.sort(); | |
| for (const file of files) { | |
| try { | |
| const fileHash = crypto.createHash("sha1"); | |
| const content = await fs.readFile(file); | |
| fileHash.update(content); | |
| const hashStr = `${file}:${fileHash.digest("hex")}`; | |
| hash.update(hashStr); | |
| } catch (error) { | |
| console.warn(`Could not read file ${file}:`, error); | |
| } | |
| } | |
| return hash.digest("hex"); | |
| } | |
| async function loadStoredHashes() { | |
| try { | |
| return JSON.parse(await fs.readFile(HASHES_FILE, "utf8")); | |
| } catch { | |
| return {}; | |
| } | |
| } | |
| async function saveHashes(hashes) { | |
| await fs.writeFile(HASHES_FILE, JSON.stringify(hashes, null, 2)); | |
| } | |
| function runCommand(command) { | |
| const { spawnSync } = require("child_process"); | |
| const result = spawnSync(command, { | |
| stdio: "inherit", | |
| shell: true, | |
| }); | |
| return result.status === 0; | |
| } | |
| function hasChanges(oldHashes, newHashes) { | |
| // Compare number of files first | |
| if (Object.keys(oldHashes).length !== Object.keys(newHashes).length) { | |
| return true; | |
| } | |
| return Object.entries(newHashes).some(([file, hash]) => oldHashes[file] !== hash); | |
| } | |
| async function checkAndRun() { | |
| const storedHashes = await loadStoredHashes(); | |
| let anyChanges = false; | |
| for (const config of packageConfig) { | |
| const currentHashes = await getFileHash(config.globs); | |
| if (hasChanges(storedHashes[config.name] || {}, currentHashes)) { | |
| console.log(`Changes detected in ${config.name}`); | |
| if (runCommand(config.command)) { | |
| anyChanges = true; | |
| storedHashes[config.name] = currentHashes; | |
| } | |
| } else { | |
| console.log(`No changes detected in ${config.name}`); | |
| } | |
| } | |
| if (anyChanges) { | |
| await saveHashes(storedHashes); | |
| } | |
| } | |
| checkAndRun().catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment