my-bitburner/src/watcher.ts

53 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-12-26 07:15:57 +09:00
import { NS, ProcessInfo } from '../NetscriptDefinitions'
2021-12-26 07:15:57 +09:00
export async function main(ns: NS): Promise<void> {
const hashes: any = {}
2021-12-26 07:15:57 +09:00
const files = ns.ls('home', '.js')
for (const file of files) {
const contents = ns.read(file)
hashes[file] = getHash(contents)
}
2021-12-26 07:15:57 +09:00
while (true) {
const files = ns.ls('home', '.js')
2021-12-26 07:15:57 +09:00
for (const file of files) {
const contents = ns.read(file)
const hash = getHash(contents)
2021-12-26 07:15:57 +09:00
if (hash != hashes[file]) {
ns.tprint(`INFO: Detected change in ${file}`)
2021-12-26 07:15:57 +09:00
const processes = ns.ps().filter((p: ProcessInfo) => {
return p.filename == file
})
2021-12-26 07:15:57 +09:00
for (const process of processes) {
ns.tprint(`INFO: Restarting ${process.filename} ${process.args} -t ${process.threads}`)
if (process.filename != ns.getScriptName()) {
2021-12-24 04:59:01 +09:00
ns.kill(process.pid, ns.getHostname())
ns.run(process.filename, process.threads, ...process.args)
} else {
ns.spawn(process.filename, process.threads, ...process.args)
}
}
hashes[file] = hash
}
}
await ns.sleep(1000)
}
}
2021-12-26 07:15:57 +09:00
const getHash = (input: string): number => {
let hash = 0, i, chr
if (input.length === 0) return hash
for (i = 0; i < input.length; i++) {
chr = input.charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0 // Convert to 32bit integer
}
return hash
}