diff options
Diffstat (limited to 'deno/tools')
-rw-r--r-- | deno/tools/main.ts | 14 | ||||
-rw-r--r-- | deno/tools/manage-service.ts | 42 | ||||
-rw-r--r-- | deno/tools/service.ts | 169 | ||||
-rw-r--r-- | deno/tools/template.ts | 124 | ||||
-rw-r--r-- | deno/tools/vm.ts (renamed from deno/tools/manage-vm.ts) | 64 | ||||
-rw-r--r-- | deno/tools/yargs.ts | 12 |
6 files changed, 227 insertions, 198 deletions
diff --git a/deno/tools/main.ts b/deno/tools/main.ts new file mode 100644 index 0000000..897350c --- /dev/null +++ b/deno/tools/main.ts @@ -0,0 +1,14 @@ +import yargs, { DEMAND_COMMAND_MESSAGE } from "./yargs.ts"; +import vm from "./vm.ts"; +import service from "./service.ts"; + +if (import.meta.main) { + await yargs(Deno.args) + .scriptName("crupest") + .command(vm) + .command(service) + .demandCommand(1, DEMAND_COMMAND_MESSAGE) + .help() + .strict() + .parse(); +} diff --git a/deno/tools/manage-service.ts b/deno/tools/manage-service.ts deleted file mode 100644 index 148f55a..0000000 --- a/deno/tools/manage-service.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { join } from "@std/path"; -// @ts-types="npm:@types/yargs" -import yargs from "yargs"; - -import { TemplateDir } from "./template.ts"; - -if (import.meta.main) { - await yargs(Deno.args) - .scriptName("manage-service") - .option("project-dir", { - type: "string", - }) - .demandOption("project-dir") - .command({ - command: "gen-tmpl", - describe: "generate files for templates", - builder: (builder) => { - return builder - .option("dry-run", { - type: "boolean", - default: true, - }) - .strict(); - }, - handler: (argv) => { - const { projectDir, dryRun } = argv; - new TemplateDir( - join(projectDir, "services/templates"), - ).generateWithVariableFiles( - [ - join(projectDir, "data/config"), - join(projectDir, "services/config.template"), - ], - dryRun ? undefined : join(projectDir, "services/generated"), - ); - }, - }) - .demandCommand(1, "One command must be specified.") - .help() - .strict() - .parse(); -} diff --git a/deno/tools/service.ts b/deno/tools/service.ts new file mode 100644 index 0000000..1172473 --- /dev/null +++ b/deno/tools/service.ts @@ -0,0 +1,169 @@ +import { dirname, join, relative } from "@std/path"; +import { copySync, existsSync, walkSync } from "@std/fs"; +import { parse } from "@std/dotenv"; +import { distinct } from "@std/collections"; +// @ts-types="npm:@types/mustache" +import Mustache from "mustache"; + +import { defineYargsModule, DEMAND_COMMAND_MESSAGE } from "./yargs.ts"; + +const MUSTACHE_RENDER_OPTIONS: Mustache.RenderOptions = { + tags: ["@@", "@@"], + escape: (value: unknown) => String(value), +}; + +function mustacheParse(template: string) { + return Mustache.parse(template, MUSTACHE_RENDER_OPTIONS.tags); +} + +function mustacheRender(template: string, view: Record<string, string>) { + return Mustache.render(template, view, {}, MUSTACHE_RENDER_OPTIONS); +} + +function getVariableKeysOfTemplate(template: string): string[] { + return distinct( + mustacheParse(template) + .filter((v) => v[0] === "name") + .map((v) => v[1]), + ); +} + +function loadTemplatedConfigFiles( + files: string[], +): Record<string, string> { + console.log("Scan config files ..."); + const config: Record<string, string> = {}; + for (const file of files) { + console.log(` from file ${file}`); + const text = Deno.readTextFileSync(file); + for (const [key, valueText] of Object.entries(parse(text))) { + // TODO: dotenv silently override old values, so everything will be new for now. + console.log(` (${key in config ? "override" : "new"}) ${key}`); + getVariableKeysOfTemplate(valueText).forEach((name) => { + if (!(name in config)) { + throw new Error( + `Variable ${name} is not defined yet, perhaps due to typos or wrong order.`, + ); + } + }); + config[key] = mustacheRender(valueText, config); + } + } + return config; +} + +const TEMPLATE_FILE_EXT = ".template"; + +class TemplateDir { + templates: { path: string; ext: string; text: string; vars: string[] }[] = []; + plains: { path: string }[] = []; + + constructor(public dir: string) { + console.log(`Scan template dir ${dir} ...`); + Array.from( + walkSync(dir, { includeDirs: false, followSymlinks: true }), + ).forEach(({ path }) => { + path = relative(this.dir, path); + if (path.endsWith(TEMPLATE_FILE_EXT)) { + console.log(` (template) ${path}`); + const text = Deno.readTextFileSync(join(dir, path)); + this.templates.push({ + path, + ext: TEMPLATE_FILE_EXT, + text, + vars: getVariableKeysOfTemplate(text), + }); + } else { + console.log(` (plain) ${path}`); + this.plains.push({ path }); + } + }); + } + + allNeededVars() { + return distinct(this.templates.flatMap((t) => t.vars)); + } + + generate(vars: Record<string, string>, generatedDir?: string) { + console.log( + `Generate to dir ${generatedDir ?? "[dry-run]"} ...`, + ); + + const undefinedVars = this.allNeededVars().filter((v) => !(v in vars)); + if (undefinedVars.length !== 0) { + throw new Error( + `Needed variables are not defined: ${undefinedVars.join(", ")}`, + ); + } + + if (generatedDir != null) { + if (existsSync(generatedDir)) { + console.log(` delete old generated dir`); + Deno.removeSync(generatedDir, { recursive: true }); + } + + for (const file of this.plains) { + const [source, destination] = [ + join(this.dir, file.path), + join(generatedDir, file.path), + ]; + console.log(` copy ${file.path}`); + Deno.mkdirSync(dirname(destination), { recursive: true }); + copySync(source, destination); + } + for (const file of this.templates) { + const path = file.path.slice(0, -file.ext.length); + const destination = join(generatedDir, path); + console.log(` generate ${path}`); + const rendered = mustacheRender(file.text, vars); + Deno.mkdirSync(dirname(destination), { recursive: true }); + Deno.writeTextFileSync(destination, rendered); + } + } + } +} + +export default defineYargsModule({ + command: "service", + aliases: ["sv"], + describe: "Manage services.", + builder: (builder) => { + return builder + .option("project-dir", { + type: "string", + }) + .demandOption("project-dir") + .command({ + command: "gen-tmpl", + describe: "Generate files from templates", + builder: (builder) => { + return builder + .option("dry-run", { + type: "boolean", + default: true, + }) + .strict(); + }, + handler: (argv) => { + const { projectDir, dryRun } = argv; + + const config = loadTemplatedConfigFiles( + [ + join(projectDir, "data/config"), + join(projectDir, "services/config.template"), + ], + ); + + new TemplateDir( + join(projectDir, "services/templates"), + ).generate( + config, + dryRun ? undefined : join(projectDir, "services/generated"), + ); + console.log("Done!"); + }, + }) + .demandCommand(1, DEMAND_COMMAND_MESSAGE); + }, + handler: () => {}, +}); diff --git a/deno/tools/template.ts b/deno/tools/template.ts deleted file mode 100644 index 1b67eb8..0000000 --- a/deno/tools/template.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { dirname, join, relative } from "@std/path"; -import { copySync, existsSync, walkSync } from "@std/fs"; -import { parse } from "@std/dotenv"; -import { distinct } from "@std/collections"; -// @ts-types="npm:@types/mustache" -import Mustache from "mustache"; - -Mustache.tags = ["@@", "@@"]; -Mustache.escape = (value) => String(value); - -function getVariableKeys(original: string): string[] { - return distinct( - Mustache.parse(original) - .filter(function (v) { - return v[0] === "name"; - }) - .map(function (v) { - return v[1]; - }), - ); -} - -export function loadVariables(files: string[]): Record<string, string> { - const vars: Record<string, string> = {}; - for (const file of files) { - const text = Deno.readTextFileSync(file); - for (const [key, valueText] of Object.entries(parse(text))) { - getVariableKeys(valueText).forEach((name) => { - if (!(name in vars)) { - throw new Error( - `Variable ${name} is not defined yet, perhaps due to typos or wrong order.`, - ); - } - }); - vars[key] = Mustache.render(valueText, vars); - } - } - return vars; -} - -const TEMPLATE_FILE_EXT = ".template"; - -export class TemplateDir { - templates: { path: string; ext: string; text: string; vars: string[] }[] = []; - plains: { path: string }[] = []; - - constructor(public dir: string) { - console.log("Scanning template dir:"); - Array.from( - walkSync(dir, { includeDirs: false, followSymlinks: true }), - ).forEach(({ path }) => { - path = relative(this.dir, path); - if (path.endsWith(TEMPLATE_FILE_EXT)) { - console.log(` (template) ${path}`); - const text = Deno.readTextFileSync(join(dir, path)); - this.templates.push({ - path, - ext: TEMPLATE_FILE_EXT, - text, - vars: getVariableKeys(text), - }); - } else { - console.log(` (plain) ${path}`); - this.plains.push({ path }); - } - }); - console.log("Done scanning template dir."); - } - - allNeededVars() { - return distinct(this.templates.flatMap((t) => t.vars)); - } - - generate(vars: Record<string, string>, generatedDir?: string) { - console.log( - `Generating, template dir: ${this.dir}, generated dir: ${ - generatedDir ?? "[dry-run]" - }:`, - ); - - const undefinedVars = this.allNeededVars().filter((v) => !(v in vars)); - if (undefinedVars.length !== 0) { - throw new Error( - `Needed variables are not defined: ${undefinedVars.join(", ")}`, - ); - } - - if (generatedDir != null) { - if (existsSync(generatedDir)) { - console.log(` delete old generated dir ${generatedDir}`); - Deno.removeSync(generatedDir, { recursive: true }); - } - - for (const file of this.plains) { - const [source, destination] = [ - join(this.dir, file.path), - join(generatedDir, file.path), - ]; - console.log(` copy ${source} to ${destination} ...`); - Deno.mkdirSync(dirname(destination), { recursive: true }); - copySync(source, destination); - } - for (const file of this.templates) { - const [source, destination] = [ - join(this.dir, file.path), - join(generatedDir, file.path.slice(0, -file.ext.length)), - ]; - console.log(` generate ${source} to ${destination} ...`); - const rendered = Mustache.render(file.text, vars); - Deno.mkdirSync(dirname(destination), { recursive: true }); - Deno.writeTextFileSync(destination, rendered); - } - } - console.log(`Done generating.`); - } - - generateWithVariableFiles(varFiles: string[], generatedDir?: string) { - console.log("Scanning defined vars:"); - const vars = loadVariables(varFiles); - Object.keys(vars).forEach((name) => console.log(` ${name}`)); - console.log("Done scanning defined vars."); - this.generate(vars, generatedDir); - } -} diff --git a/deno/tools/manage-vm.ts b/deno/tools/vm.ts index bb985ce..17e8125 100644 --- a/deno/tools/manage-vm.ts +++ b/deno/tools/vm.ts @@ -1,7 +1,6 @@ import os from "node:os"; import { join } from "@std/path"; -// @ts-types="npm:@types/yargs" -import yargs from "yargs"; +import { defineYargsModule, DEMAND_COMMAND_MESSAGE } from "./yargs.ts"; type ArchAliasMap = { [name: string]: string[] }; const arches = { @@ -112,33 +111,34 @@ function createQemuArgs(setup: VmSetup): string[] { ]; } -if (import.meta.main) { - await yargs(Deno.args) - .scriptName("manage-vm") - .command({ - command: "gen <name>", - describe: "generate cli command to run the vm", - builder: (builder) => { - return builder - .positional("name", { - describe: "name of the vm to run", - type: "string", - }) - .demandOption("name") - .strict(); - }, - handler: (argv) => { - const vm = resolveVmSetup(argv.name, MY_VMS); - if (vm == null) { - console.error(`No vm called ${argv.name} is found.`); - Deno.exit(-1); - } - const cli = createQemuArgs(vm); - console.log(`${cli.join(" ")}`); - }, - }) - .demandCommand(1, "One command must be specified.") - .help() - .strict() - .parse(); -} +const gen = defineYargsModule({ + command: "gen <name>", + describe: "generate cli command to run the vm", + builder: (builder) => { + return builder + .positional("name", { + describe: "name of the vm to run", + type: "string", + }) + .demandOption("name") + .strict(); + }, + handler: (argv) => { + const vm = resolveVmSetup(argv.name, MY_VMS); + if (vm == null) { + console.error(`No vm called ${argv.name} is found.`); + Deno.exit(-1); + } + const cli = createQemuArgs(vm); + console.log(`${cli.join(" ")}`); + }, +}); + +export default defineYargsModule({ + command: "vm", + describe: "Manage (qemu) virtual machines.", + builder: (builder) => { + return builder.command(gen).demandCommand(1, DEMAND_COMMAND_MESSAGE); + }, + handler: () => {}, +}); diff --git a/deno/tools/yargs.ts b/deno/tools/yargs.ts new file mode 100644 index 0000000..eaa7803 --- /dev/null +++ b/deno/tools/yargs.ts @@ -0,0 +1,12 @@ +// @ts-types="npm:@types/yargs" +export { default } from "yargs"; +export * from "yargs"; + +import { CommandModule } from "yargs"; +export function defineYargsModule<T, U>( + module: CommandModule<T, U>, +): CommandModule<T, U> { + return module; +} + +export const DEMAND_COMMAND_MESSAGE = "No command is specified"; |