refactor(scripts): cleanup & enforce code style (#1388)

This commit is contained in:
uncenter authored and GitHub committed 2024-10-27 15:32:00 -04:00
1 parent 7db9b234c1
commit 5d74d700a2
23 files changed
+290 -270

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
deno-version: v1.x
- name: Generate health files
run: deno task ci:generate
run: deno task generate
- name: Commit changes
uses: EndBug/add-and-commit@v9
+2 -2
View File
@@ -45,8 +45,8 @@ jobs:
with:
deno-version: v1.x
- name: Generate import file
run: deno task ci:generate-import
- name: Generate Stylus import file
run: deno task stylus-import
- name: Upload Release Artifacts
run: gh release upload --clobber all-userstyles-export ./dist/import.json
+1 -1
View File
@@ -23,6 +23,6 @@ jobs:
- name: Sync maintainers
if: ${{ github.repository == 'catppuccin/userstyles' && github.ref == 'refs/heads/main' }}
run: deno task ci:sync-maintainers
run: deno task sync-maintainers
env:
GITHUB_TOKEN: ${{ secrets.USERSTYLES_TOKEN }}
+15 -6
View File
@@ -11,7 +11,7 @@
"@std/path": "jsr:@std/path@^1.0.6",
"@std/yaml": "jsr:@std/yaml@^1.0.5",
"ajv": "npm:[email protected]",
"catppuccin-repo/": "https://raw.githubusercontent.com/catppuccin/catppuccin/d4f2666c2b04337f0a8632713de0889d9a7d332d/",
"@catppuccin/catppuccin/": "https://raw.githubusercontent.com/catppuccin/catppuccin/d4f2666c2b04337f0a8632713de0889d9a7d332d/",
"handlebars": "npm:[email protected]",
"json-schema-to-typescript": "npm:[email protected]",
"less": "npm:[email protected]",
@@ -25,13 +25,22 @@
"usercss-meta": "npm:[email protected]"
},
"tasks": {
"ci:generate": "deno run -A ./scripts/generate/main.ts",
"ci:generate-import": "deno run -A ./scripts/import-styles/main.ts",
"ci:sync-maintainers": "deno run -A ./scripts/sync-maintainers/main.ts",
"generate": "deno run -A ./scripts/generate/main.ts",
"stylus-import": "deno run -A ./scripts/stylus-import/main.ts",
"sync-maintainers": "deno run -A ./scripts/sync-maintainers/main.ts",
"lint": "deno run -A ./scripts/lint/main.ts",
"lint:fix": "deno task lint --fix",
"update-types": "deno run -A ./scripts/update-types.ts",
"update-types": "deno run -A ./scripts/types/update-types.ts",
"format": "deno run -A npm:[email protected] --write ."
},
"nodeModulesDir": true
"nodeModulesDir": true,
"fmt": {
"include": ["scripts/**/*.ts"]
},
"lint": {
"rules": {
"tags": ["recommended"],
"include": ["verbatim-module-syntax"]
}
}
}
-1
View File
@@ -1 +0,0 @@
import "npm:[email protected]";
+18
View File
@@ -0,0 +1,18 @@
import PORTS_SCHEMA from "@catppuccin/catppuccin/resources/ports.schema.json" with {
type: "json",
};
import USERSTYLES_SCHEMA from "@/userstyles.schema.json" with {
type: "json",
};
import * as path from "@std/path";
const ROOT = import.meta.dirname;
if (!ROOT) throw new Error("ROOT was not located.");
/**
* Absolute path to the repository.
*/
export const REPO_ROOT = path.join(ROOT, "..");
export { PORTS_SCHEMA, USERSTYLES_SCHEMA };
-20
View File
@@ -1,20 +0,0 @@
import portsSchema from "catppuccin-repo/resources/ports.schema.json" with {
type: "json",
};
import userStylesSchema from "@/userstyles.schema.json" with {
type: "json",
};
import { join } from "@std/path";
const ROOT = import.meta.dirname;
if (!ROOT) {
throw new Error("ROOT was not located.");
}
/**
* absolute path to the repository
*/
export const REPO_ROOT = join(ROOT, "..");
export { portsSchema, userStylesSchema };
+33 -30
View File
@@ -1,10 +1,11 @@
import { join } from "@std/path";
import type { UserstylesSchema } from "@/types/mod.ts";
import { REPO_ROOT } from "@/constants.ts";
import * as path from "@std/path";
import * as yaml from "@std/yaml";
import { REPO_ROOT } from "@/deps.ts";
import { updateFile } from "@/generate/utils.ts";
import { UserStylesSchema } from "@/types/mod.ts";
import { stringify } from "@std/yaml";
import { type ColorName, flavors } from "@catppuccin/palette";
import { writeWithPreamble } from "@/generate/utils.ts";
/**
* Macchiato color definitions as hex values.
@@ -17,12 +18,11 @@ const macchiatoHex = flavors.macchiato.colorEntries
const toIssueLabel = (slug: string | number) => `lbl:${slug}`;
export const syncIssueLabels = async (
userstyles: UserStylesSchema.Userstyles,
) => {
updateFile(
join(REPO_ROOT, ".github/issue-labeler.yml"),
stringify(
export async function syncIssueLabels(userstyles: UserstylesSchema.Userstyles) {
// .github/issue-labeler.yml
await writeWithPreamble(
path.join(REPO_ROOT, ".github/issue-labeler.yml"),
yaml.stringify(
Object.entries(userstyles)
.reduce((acc, [key]) => {
acc[key.toString()] = [`/${toIssueLabel(key)}(,.*)?$/gm`];
@@ -31,13 +31,14 @@ export const syncIssueLabels = async (
),
);
const userstyleIssueContent = Deno.readTextFileSync(join(
// .github/ISSUE_TEMPLATE/userstyle.yml
const userstyleIssueTemplate = Deno.readTextFileSync(path.join(
REPO_ROOT,
"scripts/generate/templates/userstyle-issue.yml",
));
Deno.writeTextFileSync(
join(REPO_ROOT, ".github/ISSUE_TEMPLATE/userstyle.yml"),
userstyleIssueContent.replace(
await Deno.writeTextFile(
path.join(REPO_ROOT, ".github/ISSUE_TEMPLATE/userstyle.yml"),
userstyleIssueTemplate.replace(
`"$LABELS"`,
`${
Object.entries(userstyles)
@@ -48,9 +49,9 @@ export const syncIssueLabels = async (
);
// .github/pr-labeler.yml
updateFile(
join(REPO_ROOT, ".github/pr-labeler.yml"),
stringify(
await writeWithPreamble(
path.join(REPO_ROOT, ".github/pr-labeler.yml"),
yaml.stringify(
Object.entries(userstyles)
.reduce((acc, [key]) => {
acc[`${key}`] = `styles/${key}/**/*`;
@@ -60,15 +61,17 @@ export const syncIssueLabels = async (
);
// .github/labels.yml
const syncLabelsContent = Object.entries(userstyles)
.map(([slug, style]) => {
return {
name: slug,
description: [style.name].flat().join(", "),
color: style.color ? macchiatoHex[style.color] : macchiatoHex.blue,
};
});
const syncLabels = join(REPO_ROOT, ".github/labels.yml");
// deno-lint-ignore no-explicit-any
await updateFile(syncLabels, stringify(syncLabelsContent as any));
};
await writeWithPreamble(
path.join(REPO_ROOT, ".github/labels.yml"),
yaml.stringify(
Object.entries(userstyles)
.map(([slug, style]) => {
return {
name: slug,
description: [style.name].flat().join(", "),
color: style.color ? macchiatoHex[style.color] : macchiatoHex.blue,
};
}),
),
);
}
+11 -31
View File
@@ -1,36 +1,14 @@
#!/usr/bin/env -S deno run -A
import { join } from "@std/path";
import { portsSchema, REPO_ROOT, userStylesSchema } from "@/deps.ts";
import type { PortsSchema, UserStylesSchema } from "@/types/mod.ts";
import * as path from "@std/path";
import { REPO_ROOT } from "@/constants.ts";
import { syncIssueLabels } from "@/generate/labels.ts";
import { generateMainReadme } from "@/generate/readme-repo.ts";
import { generateStyleReadmes } from "@/generate/readme-styles.ts";
import { updateFile } from "@/generate/utils.ts";
import { validateYaml } from "@/utils.ts";
import { writeWithPreamble } from "@/generate/utils.ts";
import { getPortsData, getUserstylesData } from "@/utils.ts";
const userstylesYaml = Deno.readTextFileSync(
join(REPO_ROOT, "scripts/userstyles.yml"),
);
const portsYaml = await fetch(
"https://raw.githubusercontent.com/catppuccin/catppuccin/main/resources/ports.yml",
).then((res) => res.text());
const [portsData, userstylesData] = await Promise.all([
await validateYaml<PortsSchema.PortsSchema>(
portsYaml,
portsSchema,
),
await validateYaml<UserStylesSchema.UserstylesSchema>(
userstylesYaml,
userStylesSchema,
),
]);
if (!userstylesData.userstyles) {
console.error("No userstyles found");
Deno.exit(1);
}
const userstylesData = getUserstylesData();
const portsData = await getPortsData();
/**
* Generate the main README.md, listing all ports as a table of contents
@@ -67,9 +45,11 @@ const maintainersCodeOwners = () => {
};
const userstylesStaffCodeOwners = () => {
const paths = ["/.github/", "/scripts/", "/template/"];
return paths.map((path) => `${path} @catppuccin/userstyles-staff`).join("\n");
return paths.map((path) => `${path} @catppuccin/userstyles-staff`).join(
"\n",
);
};
await updateFile(
join(REPO_ROOT, ".github/CODEOWNERS"),
await writeWithPreamble(
path.join(REPO_ROOT, ".github/CODEOWNERS"),
`${maintainersCodeOwners()}\n\n${userstylesStaffCodeOwners()}`,
);
+24 -14
View File
@@ -1,20 +1,21 @@
import { join } from "@std/path";
import type { PortsSchema, UserstylesSchema } from "@/types/mod.ts";
import { REPO_ROOT } from "@/constants.ts";
import * as path from "@std/path";
import Handlebars from "handlebars";
import { REPO_ROOT } from "@/deps.ts";
import { PortsSchema, UserStylesSchema } from "@/types/mod.ts";
import { updateFile, updateReadme } from "@/generate/utils.ts";
import { updateReadme } from "@/generate/utils.ts";
type MappedPorts = {
[k: string]: (
UserStylesSchema.Userstyle & { path: string }
UserstylesSchema.Userstyle & { path: string }
)[];
};
export const generateMainReadme = async (
userstyles: UserStylesSchema.Userstyles,
export async function generateMainReadme(
userstyles: UserstylesSchema.Userstyles,
portsData: PortsSchema.PortsSchema,
) => {
) {
if (!portsData.categories) throw ("Ports data is missing categories");
const categorized = Object.entries(userstyles)
@@ -23,7 +24,11 @@ export const generateMainReadme = async (
// only care about the first (primary) category in the categories array
acc[categories[0]] ??= [];
acc[categories[0]].push({ path: `styles/${slug}`, categories, ...port });
acc[categories[0]].push({
path: `styles/${slug}`,
categories,
...port,
});
// Sort by name, first array entry if necessary
acc[categories[0]].sort((a, b) =>
@@ -53,7 +58,13 @@ export const generateMainReadme = async (
emoji: meta.emoji,
name: meta.name,
ports: ports.map(
({ name, path, "current-maintainers": currentMaintainers }) => {
(
{
name,
path,
"current-maintainers": currentMaintainers,
},
) => {
return {
name: [name].flat(),
maintained: currentMaintainers.length > 0,
@@ -65,14 +76,13 @@ export const generateMainReadme = async (
}),
});
const readmePath = join(REPO_ROOT, "README.md");
await updateFile(
const readmePath = path.join(REPO_ROOT, "README.md");
await Deno.writeTextFile(
readmePath,
updateReadme({
readme: Deno.readTextFileSync(readmePath),
section: "userstyles",
newContent: portContent,
}),
false,
).catch((e) => console.error(e));
};
}
+15 -16
View File
@@ -1,6 +1,7 @@
import { UserStylesSchema } from "@/types/mod.ts";
import { join } from "@std/path";
import { REPO_ROOT } from "@/deps.ts";
import type { UserstylesSchema } from "@/types/mod.ts";
import { REPO_ROOT } from "@/constants.ts";
import * as path from "@std/path";
import Handlebars from "handlebars";
// we can have some nice things :)
@@ -14,8 +15,8 @@ Handlebars.registerHelper(
);
const heading = (
name: UserStylesSchema.Name,
link: UserStylesSchema.ApplicationLink,
name: UserstylesSchema.Name,
link: UserstylesSchema.ApplicationLink,
) => {
const [nameArray, linkArray] = [[name].flat(), [link].flat()];
@@ -30,11 +31,11 @@ const heading = (
});
};
const extractName = (
function extractName(
collaborators?:
| UserStylesSchema.CurrentMaintainers
| UserStylesSchema.PastMaintainers,
) => {
| UserstylesSchema.CurrentMaintainers
| UserstylesSchema.PastMaintainers,
) {
// no-op when undefined
if (!collaborators) return;
// set the name to the github.com/<name>
@@ -42,12 +43,10 @@ const extractName = (
c.name ??= c.url.split("/").pop();
return c;
});
};
}
export const generateStyleReadmes = (
userstyles: UserStylesSchema.Userstyles,
) => {
const stylesReadmePath = join(
export function generateStyleReadmes(userstyles: UserstylesSchema.Userstyles) {
const stylesReadmePath = path.join(
REPO_ROOT,
"scripts/generate/templates/userstyle.md",
);
@@ -77,9 +76,9 @@ export const generateStyleReadmes = (
},
});
Deno.writeTextFile(
join(REPO_ROOT, "styles", slug.toString(), "README.md"),
path.join(REPO_ROOT, "styles", slug.toString(), "README.md"),
readmeContent,
).catch((e) => console.error(e));
},
);
};
}
+11 -14
View File
@@ -1,15 +1,14 @@
export const updateFile = (
export function writeWithPreamble(
filePath: string,
fileContent: string,
comment = true,
) => {
const preamble = comment
? "# THIS FILE IS AUTOGENERATED. DO NOT EDIT IT BY HAND.\n"
: "";
return Deno.writeTextFile(filePath, preamble + fileContent);
};
) {
return Deno.writeTextFile(
filePath,
"# THIS FILE IS AUTOGENERATED. DO NOT EDIT IT BY HAND.\n" + fileContent,
);
}
export const updateReadme = ({
export function updateReadme({
readme,
section,
newContent,
@@ -17,20 +16,18 @@ export const updateReadme = ({
readme: string;
section: string;
newContent: string;
}): string => {
}): string {
const preamble =
"<!-- the following section is auto-generated, do not edit -->";
const startMarker = `<!-- AUTOGEN:${section.toUpperCase()} START -->`;
const endMarker = `<!-- AUTOGEN:${section.toUpperCase()} END -->`;
const wrapped = `${startMarker}\n${preamble}\n${newContent}\n${endMarker}`;
if (
!(readme.includes(startMarker) && readme.includes(endMarker))
) {
if (!(readme.includes(startMarker) && readme.includes(endMarker))) {
throw new Error("Markers not found in README.md");
}
const pre = readme.split(startMarker)[0];
const end = readme.split(endMarker)[1];
return pre + wrapped + end;
};
}
+14 -13
View File
@@ -1,8 +1,9 @@
import { exists } from "@std/fs";
import { join, relative } from "@std/path";
import { REPO_ROOT } from "@/constants.ts";
import * as fs from "@std/fs";
import * as path from "@std/path";
import core from "@actions/core";
import { REPO_ROOT } from "@/deps.ts";
import { log } from "@/logger.ts";
const requiredFiles = [
@@ -10,19 +11,19 @@ const requiredFiles = [
"preview.webp",
];
export const checkForMissingFiles = async () => {
const stylesRoot = join(REPO_ROOT, "styles");
export async function checkForMissingFiles() {
const stylesRoot = path.join(REPO_ROOT, "styles");
const missingFiles: string[] = [];
for await (const entry of Deno.readDir(stylesRoot)) {
if (!entry.isDirectory) continue;
const styleRoot = join(stylesRoot, entry.name);
const styleRoot = path.join(stylesRoot, entry.name);
await Promise.all(requiredFiles.map(async (f) => {
const fp = join(styleRoot, f);
const rfp = relative(REPO_ROOT, fp);
const fp = path.join(styleRoot, f);
const rfp = path.relative(REPO_ROOT, fp);
if (!(await exists(fp))) {
if (!(await fs.exists(fp))) {
missingFiles.push(rfp);
}
}));
@@ -35,10 +36,10 @@ export const checkForMissingFiles = async () => {
.addList(missingFiles)
.write();
} else {
missingFiles.map((f) => {
log.error(`File does not exist`, { file: f });
});
for (const file of missingFiles) {
log.error(`File does not exist`, { file });
}
}
return missingFiles.length === 0;
};
}
+7 -7
View File
@@ -1,11 +1,11 @@
#!/usr/bin/env -S deno run -A
import { walk } from "@std/fs";
import { REPO_ROOT } from "@/constants.ts";
import { parseArgs } from "@std/cli";
import { basename, dirname, join, relative } from "@std/path";
import * as fs from "@std/fs";
import * as path from "@std/path";
// @ts-types="npm:@types/less";
import less from "less";
import { REPO_ROOT } from "@/deps.ts";
import { checkForMissingFiles } from "@/lint/file-checker.ts";
import { log } from "@/logger.ts";
import { verifyMetadata } from "@/lint/metadata.ts";
@@ -15,7 +15,7 @@ import stylelintConfig from "../../.stylelintrc.js";
const args = parseArgs(Deno.args, { boolean: ["fix"] });
const subDir = args._[0]?.toString() ?? "";
const stylesheets = walk(join(REPO_ROOT, "styles", subDir), {
const stylesheets = fs.walk(path.join(REPO_ROOT, "styles", subDir), {
includeFiles: true,
includeDirs: false,
includeSymlinks: false,
@@ -26,8 +26,8 @@ const { userstyles } = getUserstylesData();
let failed = false;
for await (const entry of stylesheets) {
const dir = basename(dirname(entry.path));
const file = relative(REPO_ROOT, entry.path);
const dir = path.basename(path.dirname(entry.path));
const file = path.relative(REPO_ROOT, entry.path);
let content = await Deno.readTextFile(entry.path);
+25 -24
View File
@@ -1,27 +1,28 @@
import type { Userstyles } from "@/types/userstyles.d.ts";
import type { WalkEntry } from "@std/fs";
import { REPO_ROOT } from "@/constants.ts";
import * as color from "@std/fmt/colors";
import * as path from "@std/path";
import { sprintf } from "@std/fmt/printf";
// @ts-types="@/types/usercss-meta.d.ts";
import usercssMeta from "usercss-meta";
import * as color from "@std/fmt/colors";
import { sprintf } from "@std/fmt/printf";
import type { WalkEntry } from "@std/fs";
import { join, relative } from "@std/path";
import { REPO_ROOT } from "@/deps.ts";
import { log } from "@/logger.ts";
import { formatListOfItems } from "@/utils.ts";
import type { Userstyles } from "@/types/userstyles.d.ts";
export const verifyMetadata = async (
export async function verifyMetadata(
entry: WalkEntry,
content: string,
userstyle: string,
userstyles: Userstyles,
fix: boolean,
) => {
) {
// `usercss-meta` prohibits any '\r' characters, which seem to be present on Windows.
content = content.replaceAll("\r\n", "\n");
const assert = assertions(userstyle, userstyles);
const file = relative(REPO_ROOT, entry.path);
const assertions = generateAssertions(userstyle, userstyles);
const file = path.relative(REPO_ROOT, entry.path);
const { metadata, errors: parsingErrors } = usercssMeta.parse(content, {
allowErrors: true,
@@ -29,28 +30,28 @@ export const verifyMetadata = async (
const lines = content.split("\n");
// Pretty print / annotate the parsing errors.
parsingErrors.map((e) => {
for (const error of parsingErrors) {
let startLine;
if (e.index !== undefined && !Number.isNaN(e.index)) {
if (error.index !== undefined && !Number.isNaN(error.index)) {
startLine = 0;
for (const line of lines) {
startLine++;
e.index -= line.length + 1;
if (e.index < 0) break;
error.index -= line.length + 1;
if (error.index < 0) break;
}
}
// Skip "missing mandatory metadata property" ParseError, assertions checks below will cover.
if (e.code === "missingMandatory") return;
if (error.code === "missingMandatory") continue;
log.error(e.message, {
log.error(error.message, {
file,
startLine,
content,
});
});
}
for (const [key, expected] of Object.entries(assert)) {
for (const [key, expected] of Object.entries(assertions)) {
const current = metadata[key];
const atKey = "@" + key;
@@ -80,7 +81,7 @@ export const verifyMetadata = async (
}
const template = (await Deno.readTextFile(
join(REPO_ROOT, "template/catppuccin.user.css"),
path.join(REPO_ROOT, "template/catppuccin.user.css"),
))
.split("\n");
@@ -138,12 +139,12 @@ export const verifyMetadata = async (
return {
globalVars,
isLess: metadata.preprocessor === assert.preprocessor,
isLess: metadata.preprocessor === assertions.preprocessor,
fixed: content,
};
};
}
const assertions = (userstyle: string, userstyles: Userstyles) => {
function generateAssertions(userstyle: string, userstyles: Userstyles) {
const prefix = "https://github.com/catppuccin/userstyles";
if (!userstyles[userstyle]) {
@@ -175,4 +176,4 @@ const assertions = (userstyle: string, userstyles: Userstyles) => {
license: "MIT",
preprocessor: "less",
};
};
}
+35 -29
View File
@@ -1,44 +1,50 @@
import * as color from "@std/fmt/colors";
import type { WalkEntry } from "@std/fs";
import { relative } from "@std/path";
import { REPO_ROOT } from "@/constants.ts";
import * as color from "@std/fmt/colors";
import * as path from "@std/path";
import "postcss-less";
import stylelint from "stylelint";
import "stylelint-config-standard";
import "stylelint-config-recommended";
import { REPO_ROOT } from "@/deps.ts";
import { log } from "@/logger.ts";
export const lint = (
export async function lint(
entry: WalkEntry,
content: string,
fix: boolean,
config: stylelint.Config,
) =>
stylelint.lint({ code: content, config, fix })
.then(({ results, code }) => {
if (code) {
Deno.writeTextFileSync(entry.path, code);
}
results.map((result) => {
result.warnings.map((warning) => {
// Some cleanup for fancier logging - dims the rule name.
const message = warning.text?.replace(
new RegExp(`\\(?${warning.rule}\\)?`),
color.dim(`(${warning.rule})`),
) ?? "unspecified stylelint error";
) {
const { results, code } = await stylelint.lint({
code: content,
config,
fix,
});
log.log(message, {
file: relative(REPO_ROOT, entry.path),
startLine: warning.line,
endLine: warning.endLine,
startColumn: warning.column,
endColumn: warning.endColumn,
content,
}, warning.severity);
});
if (code) {
Deno.writeTextFileSync(entry.path, code);
}
if (result.warnings.length > 0) throw new Error("stylelint error");
});
});
for (const result of results) {
for (const warning of result.warnings) {
// Some cleanup for fancier logging - dims the rule name.
const message = warning.text?.replace(
new RegExp(`\\(?${warning.rule}\\)?`),
color.dim(`(${warning.rule})`),
) ?? "unspecified stylelint error";
log.log(message, {
file: path.relative(REPO_ROOT, entry.path),
startLine: warning.line,
endLine: warning.endLine,
startColumn: warning.column,
endColumn: warning.endColumn,
content,
}, warning.severity);
}
if (result.warnings.length > 0) throw new Error("stylelint error");
}
}
+3 -3
View File
@@ -7,11 +7,11 @@ export type LoggerProps = core.AnnotationProperties & {
content?: string;
};
const prettyPrint = (
function prettyPrint(
message: string,
props: LoggerProps,
severity: "error" | "warning" = "warning",
) => {
) {
const { file, startColumn, startLine } = props;
const lines = (props.content ?? "").split("\n");
@@ -73,7 +73,7 @@ const prettyPrint = (
);
console.log("\n" + logs.join("\n"));
};
}
export const log = {
failed: false,
@@ -1,11 +1,10 @@
#!/usr/bin/env -S deno run -A
import { REPO_ROOT } from "@/constants.ts";
import * as path from "@std/path";
import usercssMeta from "usercss-meta";
import { ensureDir, walk } from "@std/fs";
import { join } from "@std/path";
import { REPO_ROOT } from "@/deps.ts";
const stylesheets = walk(join(REPO_ROOT, "styles"), {
const stylesheets = walk(path.join(REPO_ROOT, "styles"), {
includeFiles: true,
includeDirs: false,
includeSymlinks: false,
+10 -8
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env -S deno run -A
import * as assert from "@std/assert";
import { Octokit } from "@octokit/rest";
import type { Userstyle } from "@/types/userstyles.d.ts";
import type { UserStylesSchema } from "@/types/mod.ts";
import * as assert from "@std/assert";
import { Octokit } from "@octokit/rest";
import { getUserstylesData } from "@/utils.ts";
const octokit = new Octokit({ auth: Deno.env.get("GITHUB_TOKEN") });
@@ -14,7 +14,7 @@ const { userstyles } = getUserstylesData();
const maintainers = [
...new Set(
Object.values(userstyles).flatMap((
style: UserStylesSchema.Userstyle,
style: Userstyle,
) =>
style["current-maintainers"].map((m) => {
const username = m.url.split("github.com/")?.pop();
@@ -34,7 +34,7 @@ const teamMembers = await octokit.teams
})
.then((res) => res.data.map((m) => m.login.toLowerCase()));
const syncMaintainers = async () => {
async function syncMaintainers() {
if (!maintainers) return;
if (assert.equal(maintainers, teamMembers)) {
console.log("Maintainers are in sync");
@@ -60,11 +60,13 @@ const syncMaintainers = async () => {
...team,
username: m,
});
console.log(`Removed ${m} from the ${team.org}/${team.team_slug} team.`);
console.log(
`Removed ${m} from the ${team.org}/${team.team_slug} team.`,
);
}
console.log(
`${toRemove.length} users removed from the ${team.org}/${team.team_slug} team.`,
);
};
}
await syncMaintainers();
+2 -9
View File
@@ -1,9 +1,2 @@
export * as UserStylesSchema from "@/types/userstyles.d.ts";
export * as PortsSchema from "catppuccin-repo/resources/types/ports.d.ts";
import { Entries } from "type-fest";
declare global {
interface ObjectConstructor {
entries<T extends object>(o: T): Entries<T>;
}
}
export * as UserstylesSchema from "@/types/userstyles.d.ts";
export * as PortsSchema from "@catppuccin/catppuccin/resources/types/ports.d.ts";
+15
View File
@@ -0,0 +1,15 @@
import { REPO_ROOT, USERSTYLES_SCHEMA } from "@/constants.ts";
import * as path from "@std/path";
import { compile, type JSONSchema } from "json-schema-to-typescript";
const TYPES_ROOT = path.join(REPO_ROOT, "scripts/types");
const types = await compile(
USERSTYLES_SCHEMA as JSONSchema,
"UserstylesSchema",
{
bannerComment: "// deno-fmt-ignore-file",
},
);
Deno.writeTextFileSync(path.join(TYPES_ROOT, "userstyles.d.ts"), types);
-16
View File
@@ -1,16 +0,0 @@
#!/usr/bin/env -S deno run -A
// deno-lint-ignore-file no-explicit-any
import { join } from "@std/path";
import { compile, Options } from "json-schema-to-typescript";
import { REPO_ROOT, userStylesSchema } from "@/deps.ts";
const options = {
bannerComment: "// deno-fmt-ignore-file",
} satisfies Partial<Options>;
const TYPES_ROOT = join(REPO_ROOT, "scripts/types");
compile(userStylesSchema as any, "UserstylesSchema", options)
.then((ts) =>
Deno.writeTextFileSync(join(TYPES_ROOT, "userstyles.d.ts"), ts)
);
+44 -20
View File
@@ -1,10 +1,11 @@
import Ajv, { Schema } from "ajv";
import { parse } from "@std/yaml";
import { join } from "@std/path";
import { SetRequired } from "type-fest/source/set-required.d.ts";
import type { PortsSchema, UserstylesSchema } from "@/types/mod.ts";
import type { SetRequired } from "type-fest/source/set-required.d.ts";
import { PORTS_SCHEMA, REPO_ROOT, USERSTYLES_SCHEMA } from "@/constants.ts";
import { REPO_ROOT, userStylesSchema } from "@/deps.ts";
import { UserstylesSchema } from "@/types/userstyles.d.ts";
import * as yaml from "@std/yaml";
import * as path from "@std/path";
import Ajv, { type Schema } from "ajv";
import { log } from "@/logger.ts";
import { sprintf } from "@std/fmt/printf";
@@ -13,13 +14,14 @@ import { sprintf } from "@std/fmt/printf";
* @param schema A JSON schema
* @returns A promise that resolves to the parsed YAML content, verified against the schema. Rejects if the content is invalid.
*/
export const validateYaml = <T>(
export function validateYaml<T>(
content: string,
schema: Schema,
): T => {
file: string,
): T {
const ajv = new Ajv.default();
const validate = ajv.compile<T>(schema);
const data = parse(content);
const data = yaml.parse(content);
if (!validate(data)) {
log.error(
@@ -34,28 +36,29 @@ export const validateYaml = <T>(
)
).join(" and "),
{
file: "scripts/userstyles.yml",
file,
},
);
Deno.exit(1);
}
return data as T;
};
}
/**
* Utility function that calls {@link validateYaml} on the userstyles.yml file.
* Fails when data.userstyles is undefined.
*/
export const getUserstylesData = (): Userstyles => {
export function getUserstylesData(): Userstyles {
const content = Deno.readTextFileSync(
join(REPO_ROOT, "scripts/userstyles.yml"),
path.join(REPO_ROOT, "scripts/userstyles.yml"),
);
try {
const data = validateYaml<UserstylesSchema>(
const data = validateYaml<UserstylesSchema.UserstylesSchema>(
content,
userStylesSchema,
USERSTYLES_SCHEMA,
"scripts/userstyles.yml",
);
for (const field of ["userstyles", "collaborators"] as const) {
@@ -69,7 +72,7 @@ export const getUserstylesData = (): Userstyles => {
return data as Userstyles;
} catch (err) {
if (err.name === "SyntaxError") {
if (err instanceof Error && err.name === "SyntaxError") {
const groups =
/(?<message>.*) at line (?<line>\d+), column (?<column>\d+):[\S\s]*/
.exec(err.message)?.groups;
@@ -87,7 +90,25 @@ export const getUserstylesData = (): Userstyles => {
Deno.exit(1);
}
};
}
/**
* Utility function that calls {@link validateYaml} on the ports.yml file.
* Fails when data.userstyles is undefined.
*/
export async function getPortsData(): Promise<PortsSchema.PortsSchema> {
const content = await fetch(
"https://raw.githubusercontent.com/catppuccin/catppuccin/main/resources/ports.yml",
).then((res) => res.text());
const data = validateYaml<PortsSchema.PortsSchema>(
content,
PORTS_SCHEMA,
"ports.yml",
);
return data;
}
/**
* Utility function that formats a list of items into the "x, y, ..., and z" format.
@@ -98,7 +119,7 @@ export const getUserstylesData = (): Userstyles => {
* @example
* formatListOfItems(['x', 'y', 'z']); // 'x, y, and z'
*/
export const formatListOfItems = (items: unknown[]): string => {
export function formatListOfItems(items: unknown[]): string {
// If there are two items, connect them with an "and".
if (items.length === 2) return items.join(" and ");
// Otherwise, there is either just one item or more than two items.
@@ -110,6 +131,9 @@ export const formatListOfItems = (items: unknown[]): string => {
// Otherwise, it is some item in the middle of the list and we can just add it as a comma followed by the item to the string.
return prev + `, ${curr}`;
}) as string;
};
}
type Userstyles = SetRequired<UserstylesSchema, "userstyles" | "collaborators">;
type Userstyles = SetRequired<
UserstylesSchema.UserstylesSchema,
"userstyles" | "collaborators"
>;