ci(lint): catch yaml errors (#659)

This commit is contained in:
uncenter authored and GitHub committed 2024-03-13 16:32:45 -04:00
1 parent 7a351386d8
commit 7139901985
3 files changed
+73 -28

No files matched your search

+60 -19
View File
@@ -5,6 +5,9 @@ import { SetRequired } from "type-fest/source/set-required.d.ts";
import { REPO_ROOT, userStylesSchema } from "@/deps.ts";
import { UserstylesSchema } from "@/types/userstyles.d.ts";
import { YAMLError } from "std/yaml/_error.ts";
import { log } from "@/lint/logger.ts";
import { sprintf } from "std/fmt/printf.ts";
/**
* @param content A string of YAML content
@@ -14,34 +17,72 @@ import { UserstylesSchema } from "@/types/userstyles.d.ts";
export const validateYaml = <T>(
content: string,
schema: Schema,
): Promise<T> => {
return new Promise((resolve, reject) => {
const ajv = new Ajv.default();
const validate = ajv.compile<T>(schema);
const data = parse(content);
): T => {
const ajv = new Ajv.default();
const validate = ajv.compile<T>(schema);
const data = parse(content);
if (!validate(data)) return reject(validate.errors);
if (!validate(data)) {
console.log(
"Found schema errors in scripts/userstyles.yml: " +
validate.errors?.map((err) =>
sprintf(
"%s %s%s",
err.instancePath.slice(1).replaceAll("/", "."),
err.message,
err.params.allowedValues
? ` (${JSON.stringify(err.params.allowedValues, undefined)})`
: "",
)
).join(" and "),
);
Deno.exit(1);
}
return resolve(data);
});
return data as T;
};
/**
* Utility function that calls {@link validateYaml} on the userstyles.yml file.
* Fails when data.userstyles is undefined.
*/
export const getUserstylesData = (): Promise<Userstyles> => {
return new Promise((resolve, reject) => {
validateYaml<UserstylesSchema>(
Deno.readTextFileSync(join(REPO_ROOT, "scripts/userstyles.yml")),
export const getUserstylesData = (): Userstyles => {
const content = Deno.readTextFileSync(
join(REPO_ROOT, "scripts/userstyles.yml"),
);
try {
const data = validateYaml<UserstylesSchema>(
content,
userStylesSchema,
).then((data) => {
if (data.userstyles === undefined || data.collaborators === undefined) {
return reject("userstyles.yml is missing required fields");
}
return resolve(data as Userstyles);
});
});
);
if (data.userstyles === undefined || data.collaborators === undefined) {
console.log("userstyles.yml is missing required fields");
Deno.exit(1);
}
return data as Userstyles;
} catch (err) {
if (err instanceof YAMLError) {
const groups =
/(?<message>.*) at line (?<line>\d+), column (?<column>\d+):[\S\s]*/
.exec(err.message)?.groups;
log(
groups!.message,
{
file: "scripts/userstyles.yml",
startLine: Number(groups!.line),
content: content,
},
"error",
);
} else {
console.log(err);
}
Deno.exit(1);
}
};
/**