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