diff --git a/README.md b/README.md index 7525bd3..68f04c6 100644 --- a/README.md +++ b/README.md @@ -33,4 +33,4 @@ To update your Netscript Definitions, run `npm run defs` in a terminal Press F1 and Select `Bitburner: Enable File Watcher` to enable auto uploading to the game ## Todo -Create a bitburner script which detects updates to files and restarts the running script automatically \ No newline at end of file +~~Create a bitburner script which detects updates to files and restarts the running script automatically~~ \ No newline at end of file diff --git a/src/watcher.ts b/src/watcher.ts new file mode 100644 index 0000000..32ce33e --- /dev/null +++ b/src/watcher.ts @@ -0,0 +1,42 @@ +import { NS, ProcessInfo } from "../NetscriptDefinitions" + +export async function main(ns : NS) : Promise { + const hashes : any = {} + + const files = ns.ls('home', '.js') + for ( const file of files ) { + const contents = ns.read(file) + hashes[file] = getHash(contents) + } + + while(true) { + const files = ns.ls('home', '.js') + + for(const file of files ) { + const contents = ns.read(file) + const hash = getHash(contents) + + if(hash != hashes[file]) { + ns.tprint(`INFO: Detected change in ${file}`) + + const processes = ns.ps().filter((p : ProcessInfo) => { + return p.filename == file + }) + + for(const process of processes) { + ns.tprint(`INFO: Restarting ${process.filename} ${process.args} -t ${process.threads}`) + ns.kill(process.pid, ns.getHostname()) + ns.run(process.filename, process.threads, ...process.args) + } + + hashes[file] = hash + } + } + + await ns.sleep(1000) + } +} + +function getHash(input : string) : number { + return input.split("").reduce( (a, b) => ((a << 5) - 1) + b.charCodeAt(0)|0, 0) +} \ No newline at end of file