41 lines
1.3 KiB
TypeScript
41 lines
1.3 KiB
TypeScript
import {Command, ParseContext, processPath, StrTerm} from "./command.js";
|
|
import {LexInput} from "../lexer.js";
|
|
import {StrVM} from "../vm.js";
|
|
import {Awaitable} from "../../util/types.js";
|
|
import os from "node:os";
|
|
import fs from "node:fs/promises";
|
|
import {isSaveData} from "./save.js";
|
|
|
|
export class Load extends Command<{ path?: StrTerm }> {
|
|
isParseCandidate(token: LexInput): boolean {
|
|
return this.isKeyword(token, 'load')
|
|
}
|
|
|
|
async attemptParse(context: ParseContext): Promise<{ path?: StrTerm }> {
|
|
return { path: await context.popOptionalTerm() }
|
|
}
|
|
|
|
getDisplayName(): string {
|
|
return 'load'
|
|
}
|
|
|
|
execute(vm: StrVM, data: { path?: StrTerm }): Awaitable<StrVM> {
|
|
return vm.replaceContextMatchingTerm(ctx => ({
|
|
override: async () => {
|
|
const path = processPath(
|
|
data.path
|
|
? ctx.resolveString(data.path)
|
|
: `~/.str.json`)
|
|
|
|
const content = await fs.readFile(path, 'utf8')
|
|
const saveData = JSON.parse(content)
|
|
if ( !isSaveData(saveData) ) {
|
|
throw new Error('Cannot load: invalid save data')
|
|
}
|
|
|
|
return saveData.subject
|
|
}
|
|
}))
|
|
}
|
|
}
|