hackmud-script-manager
Version:
Script manager for game hackmud, with minification, TypeScript support, and player script type definition generation.
44 lines (43 loc) • 1.51 kB
JavaScript
import { readDirectoryWithStats } from "@samual/lib/readDirectoryWithStats"
import { readFile, stat, writeFile } from "fs/promises"
import { extname, basename, resolve } from "path"
async function syncMacros(hackmudPath) {
const files = await readDirectoryWithStats(hackmudPath),
macros = new Map(),
users = []
await Promise.all(
files.map(async file => {
if (file.stats.isFile())
switch (extname(file.name)) {
case ".macros":
{
const [lines, date] = await Promise.all([
readFile(resolve(hackmudPath, file.name), { encoding: "utf8" }).then(file =>
file.split("\n")
),
stat(resolve(hackmudPath, file.name)).then(({ mtime }) => mtime)
])
for (let index = 0; index < lines.length / 2 - 1; index++) {
const macroName = lines[2 * index],
currentMacro = macros.get(macroName)
;(!currentMacro || date > currentMacro.date) &&
macros.set(macroName, { date, macro: lines[2 * index + 1] })
}
}
break
case ".key":
users.push(basename(file.name, ".key"))
}
})
)
let macroFile = "",
macrosSynced = 0
for (const [name, { macro }] of [...macros].sort(([a], [b]) => (a > b) - (a < b)))
if (macro[0] == macro[0].toLowerCase()) {
macroFile += `${name}\n${macro}\n`
macrosSynced++
}
await Promise.all(users.map(async user => writeFile(resolve(hackmudPath, user + ".macros"), macroFile)))
return { macrosSynced, usersSynced: users.length }
}
export { syncMacros }