|
| 1 | +import { spawn, type ChildProcess } from "node:child_process"; |
| 2 | +import { watch } from "node:fs"; |
| 3 | + |
| 4 | +const args = process.argv.slice(2); |
| 5 | +if (args.length === 0) { |
| 6 | + console.error("Usage: node dist/watch.js COMMAND [ARGS...]"); |
| 7 | + process.exit(1); |
| 8 | +} |
| 9 | + |
| 10 | +type State = |
| 11 | + | { |
| 12 | + readonly tag: "waiting"; |
| 13 | + } |
| 14 | + | { |
| 15 | + readonly tag: "delaying"; |
| 16 | + } |
| 17 | + | { |
| 18 | + readonly tag: "running-clean"; |
| 19 | + readonly child: ChildProcess; |
| 20 | + } |
| 21 | + | { |
| 22 | + readonly tag: "running-dirty"; |
| 23 | + readonly child: ChildProcess; |
| 24 | + }; |
| 25 | + |
| 26 | +const cmdAndArgs = args; |
| 27 | +let state: State = { tag: "waiting" }; |
| 28 | + |
| 29 | +const markAsDirty = () => { |
| 30 | + if (state.tag === "waiting") { |
| 31 | + setTimeout(startRun, 200); |
| 32 | + state = { tag: "delaying" }; |
| 33 | + } else if (state.tag === "running-clean") { |
| 34 | + state = { |
| 35 | + ...state, |
| 36 | + tag: "running-dirty", |
| 37 | + }; |
| 38 | + } else if (state.tag === "running-dirty") { |
| 39 | + // |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +const startRun = () => { |
| 44 | + console.log("Spawning child process"); |
| 45 | + const child = spawn(cmdAndArgs[0], cmdAndArgs.slice(1), { |
| 46 | + stdio: ["ignore", "inherit", "inherit"], |
| 47 | + }); |
| 48 | + |
| 49 | + child.on("close", (code, signal) => { |
| 50 | + if (code) { |
| 51 | + console.log(`Child process failed: exited with code ${code}`); |
| 52 | + } else if (signal) { |
| 53 | + console.log(`Child process failed: killed by ${signal}`); |
| 54 | + } else { |
| 55 | + console.log(`Child process succeeded`); |
| 56 | + } |
| 57 | + |
| 58 | + if (state.tag === "running-clean") { |
| 59 | + console.log("Waiting..."); |
| 60 | + state = { tag: "waiting" }; |
| 61 | + } else if (state.tag === "running-dirty") { |
| 62 | + startRun(); |
| 63 | + } |
| 64 | + }); |
| 65 | + |
| 66 | + state = { |
| 67 | + tag: "running-clean", |
| 68 | + child, |
| 69 | + }; |
| 70 | +}; |
| 71 | + |
| 72 | +const listener = (event: string, filename: string | null) => { |
| 73 | + console.log(`Watcher event: ${event} ${filename}`); |
| 74 | + if (filename?.startsWith(".git/")) return; |
| 75 | + if (filename?.startsWith("node_modules/")) return; |
| 76 | + markAsDirty(); |
| 77 | +}; |
| 78 | + |
| 79 | +watch(".", { recursive: true, encoding: "binary" }, listener); |
| 80 | +console.log("Initiating first run"); |
| 81 | +startRun(); |
0 commit comments