Skip to content

Commit

Permalink
feat: use ajv for defaultconfig command (#117)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `defaultconfig` command now uses ajv to generate default value. A config schema that are not object will throw an error. A config schema with top level default will now throw an error.
  • Loading branch information
Hoishin committed Dec 26, 2024
1 parent 15d3992 commit 6f2c19d
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 52 deletions.
115 changes: 74 additions & 41 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@
},
"prettier": {},
"dependencies": {
"ajv": "^8.17.1",
"chalk": "^5.4.1",
"commander": "^12.1.0",
"hosted-git-info": "^8.0.2",
"inquirer": "^12.3.0",
"json-schema-defaults": "0.4.0",
"json-schema-to-typescript": "^15.0.3",
"npm-package-arg": "^12.0.1",
"semver": "^7.6.3",
Expand Down
22 changes: 12 additions & 10 deletions src/commands/defaultconfig.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import fs from "node:fs";
import path from "node:path";

import { Ajv, type JSONSchemaType } from "ajv";
import chalk from "chalk";
import { Command } from "commander";
import defaults from "json-schema-defaults";

import util from "../lib/util.js";

const ajv = new Ajv({ useDefaults: true, strict: true });

export function defaultconfigCommand(program: Command) {
program
.command("defaultconfig [bundle]")
Expand Down Expand Up @@ -58,7 +60,9 @@ function action(bundleName?: string) {
fs.mkdirSync(cfgPath);
}

const schema = JSON.parse(fs.readFileSync(schemaPath, "utf8"));
const schema: JSONSchemaType<unknown> = JSON.parse(
fs.readFileSync(schemaPath, "utf8"),
);
const configPath = path.join(nodecgPath, "cfg/", bundleName + ".json");
if (fs.existsSync(configPath)) {
console.error(
Expand All @@ -67,15 +71,13 @@ function action(bundleName?: string) {
);
} else {
try {
fs.writeFileSync(
configPath,
JSON.stringify(defaults(schema), null, " "),
);
const validate = ajv.compile(schema);
const data = {};
validate(data);

fs.writeFileSync(configPath, JSON.stringify(data, null, 2));
console.log(
chalk.green("Success:") +
" Created %s's default config from schema\n\n" +
JSON.stringify(defaults(schema), null, " "),
bundleName,
chalk`{green Success:} Created {bold ${bundleName}}'s default config from schema\n`,
);
} catch (e) {
console.error(chalk.red("Error: ") + String(e));
Expand Down

0 comments on commit 6f2c19d

Please sign in to comment.