feat(scripts): misc (#1542)

This commit is contained in:
uncenter authored and GitHub committed 2024-12-29 11:03:53 -05:00
1 parent 2c4eefa877
commit d0c973e9c9
10 files changed
+148 -101

No files matched your search

+2 -4
View File
@@ -3,6 +3,7 @@ import * as path from "@std/path";
import { REPO_ROOT } from "@/constants.ts"; import { REPO_ROOT } from "@/constants.ts";
import { CalVer } from "@/bump-version/calver.ts"; import { CalVer } from "@/bump-version/calver.ts";
import { parseArgs } from "@std/cli"; import { parseArgs } from "@std/cli";
import { getUserstylesFiles } from "@/utils.ts";
const args = parseArgs(Deno.args, { boolean: ["all"] }); const args = parseArgs(Deno.args, { boolean: ["all"] });
@@ -15,10 +16,7 @@ if (!Deno.env.get("CI") && !args.all) {
let files = []; let files = [];
if (args.all) { if (args.all) {
for (const dir of Deno.readDirSync(path.join(REPO_ROOT, "styles"))) { files = getUserstylesFiles();
if (!dir.isDirectory) continue;
files.push(path.join(REPO_ROOT, "styles", dir.name, "catppuccin.user.css"));
}
} else { } else {
files = args._.filter((val) => typeof val == "string").map((p: string) => files = args._.filter((val) => typeof val == "string").map((p: string) =>
path.join(REPO_ROOT, p) path.join(REPO_ROOT, p)
+20 -7
View File
@@ -5,7 +5,12 @@ 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 { writeWithPreamble } from "@/generate/utils.ts"; import { writeWithPreamble } from "@/generate/utils.ts";
import { getPortsData, getUserstylesData } from "@/utils.ts"; import {
getAuthenticatedOctokit,
getPortsData,
getUserstylesData,
getUserstylesTeamMembers,
} from "@/utils.ts";
const userstylesData = getUserstylesData(); const userstylesData = getUserstylesData();
const portsData = await getPortsData(); const portsData = await getPortsData();
@@ -30,7 +35,7 @@ await syncIssueLabels(userstylesData.userstyles);
/** /**
* Keep `.github/CODEOWNERS` in sync with the userstyle metadata. * Keep `.github/CODEOWNERS` in sync with the userstyle metadata.
*/ */
const maintainersCodeOwners = () => { function maintainersCodeOwners() {
return Object.entries(userstylesData.userstyles!) return Object.entries(userstylesData.userstyles!)
.filter(([_, { "current-maintainers": currentMaintainers }]) => .filter(([_, { "current-maintainers": currentMaintainers }]) =>
currentMaintainers.length > 0 currentMaintainers.length > 0
@@ -42,14 +47,22 @@ const maintainersCodeOwners = () => {
return `/styles/${slug} ${codeOwners}`; return `/styles/${slug} ${codeOwners}`;
}) })
.join("\n"); .join("\n");
}; }
const userstylesStaffCodeOwners = () => { async function userstylesStaffCodeOwners() {
const paths = ["/.github/", "/scripts/", "/template/"]; const paths = ["/.github/", "/scripts/", "/template/"];
return paths.map((path) => `${path} @catppuccin/userstyles-staff`).join(
const octokit = getAuthenticatedOctokit();
const staffMembers = await getUserstylesTeamMembers(
octokit,
"userstyles-staff",
);
return paths.map((path) =>
`${path} ${staffMembers.map((member) => "@" + member).join(" ")}`
).join(
"\n", "\n",
); );
}; }
await writeWithPreamble( await writeWithPreamble(
path.join(REPO_ROOT, ".github/CODEOWNERS"), path.join(REPO_ROOT, ".github/CODEOWNERS"),
`${maintainersCodeOwners()}\n\n${userstylesStaffCodeOwners()}`, `${maintainersCodeOwners()}\n\n${await userstylesStaffCodeOwners()}`,
); );
+1 -1
View File
@@ -64,7 +64,7 @@ export function generateStyleReadmes(userstyles: UserstylesSchema.Userstyles) {
}, },
], ],
) => { ) => {
console.log(`Generating README for ${slug}`); console.log(`Generating README for styles/${slug}...`);
const readmeContent = Handlebars.compile(stylesReadmeContent)({ const readmeContent = Handlebars.compile(stylesReadmeContent)({
heading: heading(name, readme["app-link"]), heading: heading(name, readme["app-link"]),
slug, slug,
+1 -1
View File
@@ -18,7 +18,7 @@ export function updateReadme({
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}`;
+20 -21
View File
@@ -1,7 +1,6 @@
import { REPO_ROOT } from "@/constants.ts"; import { REPO_ROOT } from "@/constants.ts";
import { parseArgs } from "@std/cli"; import { parseArgs } from "@std/cli";
import * as fs from "@std/fs";
import * as path from "@std/path"; import * as path from "@std/path";
// @ts-types="npm:@types/less"; // @ts-types="npm:@types/less";
import less from "less"; import less from "less";
@@ -9,31 +8,31 @@ import less from "less";
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";
import { lint } from "@/lint/stylelint.ts"; import { runStylelint } from "@/lint/stylelint.ts";
import { getUserstylesData } from "@/utils.ts"; import { getUserstylesData, getUserstylesFiles } from "@/utils.ts";
import stylelintConfig from "../../.stylelintrc.js"; 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 userstyle = args._[0]?.toString().match(
const stylesheets = fs.walk(path.join(REPO_ROOT, "styles", subDir), { /(?<base>styles\/)?(?<userstyle>[a-z0-9_\.]+)(?<trailing>\/)?(?<file>catppuccin\.user\.css)?/,
includeFiles: true, )?.groups?.userstyle;
includeDirs: false, const stylesheets = userstyle
includeSymlinks: false, ? [path.join(REPO_ROOT, "styles", userstyle, "catppuccin.user.css")]
match: [/\.user.css$/], : getUserstylesFiles();
});
const { userstyles } = getUserstylesData(); const { userstyles } = getUserstylesData();
let failed = false; let didLintFail = false;
for await (const entry of stylesheets) { for (const style of stylesheets) {
const dir = path.basename(path.dirname(entry.path)); const dir = path.basename(path.dirname(style));
const file = path.relative(REPO_ROOT, entry.path); const file = path.relative(REPO_ROOT, style);
let content = await Deno.readTextFile(entry.path); let content = await Deno.readTextFile(style);
// Verify the UserCSS metadata. // Verify the UserCSS metadata.
const { globalVars, isLess, fixed } = await verifyMetadata( const { globalVars, isLess, fixed } = await verifyMetadata(
entry, file,
content, content,
dir, dir,
userstyles, userstyles,
@@ -48,7 +47,7 @@ for await (const entry of stylesheets) {
// Try to compile the LESS file, report any errors. // Try to compile the LESS file, report any errors.
less.render(content, { lint: true, globalVars: globalVars }).catch( less.render(content, { lint: true, globalVars: globalVars }).catch(
(err: Less.RenderError) => { (err: Less.RenderError) => {
failed = true; didLintFail = true;
log.error( log.error(
err.message, err.message,
{ file, startLine: err.line, endLine: err.line, content }, { file, startLine: err.line, endLine: err.line, content },
@@ -57,12 +56,12 @@ for await (const entry of stylesheets) {
); );
// Lint with Stylelint. // Lint with Stylelint.
await lint(entry, content, args.fix, stylelintConfig).catch(() => await runStylelint(style, content, args.fix, stylelintConfig).catch(() =>
failed = true didLintFail = true
); );
} }
if (await checkForMissingFiles() === false) failed = true; if (await checkForMissingFiles() === false) didLintFail = true;
// Cause the workflow to fail if any issues were found. // Cause the workflow to fail if any issues were found.
if (failed || log.failed) Deno.exit(1); if (didLintFail || log.failed) Deno.exit(1);
+1 -3
View File
@@ -1,5 +1,4 @@
import type { Userstyles } from "@/types/userstyles.d.ts"; import type { Userstyles } from "@/types/userstyles.d.ts";
import type { WalkEntry } from "@std/fs";
import { REPO_ROOT } from "@/constants.ts"; import { REPO_ROOT } from "@/constants.ts";
import * as color from "@std/fmt/colors"; import * as color from "@std/fmt/colors";
@@ -12,7 +11,7 @@ import { log } from "@/logger.ts";
import { formatListOfItems } from "@/utils.ts"; import { formatListOfItems } from "@/utils.ts";
export async function verifyMetadata( export async function verifyMetadata(
entry: WalkEntry, file: string,
content: string, content: string,
userstyle: string, userstyle: string,
userstyles: Userstyles, userstyles: Userstyles,
@@ -22,7 +21,6 @@ export async function verifyMetadata(
content = content.replaceAll("\r\n", "\n"); content = content.replaceAll("\r\n", "\n");
const assertions = generateAssertions(userstyle, userstyles); const assertions = generateAssertions(userstyle, userstyles);
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,
+4 -5
View File
@@ -1,4 +1,3 @@
import type { WalkEntry } from "@std/fs";
import { REPO_ROOT } from "@/constants.ts"; import { REPO_ROOT } from "@/constants.ts";
import * as color from "@std/fmt/colors"; import * as color from "@std/fmt/colors";
@@ -11,8 +10,8 @@ import "stylelint-config-recommended";
import { log } from "@/logger.ts"; import { log } from "@/logger.ts";
export async function lint( export async function runStylelint(
entry: WalkEntry, file: string,
content: string, content: string,
fix: boolean, fix: boolean,
config: stylelint.Config, config: stylelint.Config,
@@ -24,7 +23,7 @@ export async function lint(
}); });
if (code) { if (code) {
Deno.writeTextFileSync(entry.path, code); Deno.writeTextFileSync(path.join(REPO_ROOT, file), code);
} }
for (const result of results) { for (const result of results) {
@@ -36,7 +35,7 @@ export async function lint(
) ?? "unspecified stylelint error"; ) ?? "unspecified stylelint error";
log.log(message, { log.log(message, {
file: path.relative(REPO_ROOT, entry.path), file,
startLine: warning.line, startLine: warning.line,
endLine: warning.endLine, endLine: warning.endLine,
startColumn: warning.column, startColumn: warning.column,
+5 -14
View File
@@ -1,16 +1,7 @@
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 } from "@std/fs";
import { calcStyleDigest } from "https://github.com/openstyles/stylus/raw/8fe35a4b90d85fb911bd7aa1deab4e4733c31150/src/js/sections-util.js"; import { calcStyleDigest } from "https://github.com/openstyles/stylus/raw/8fe35a4b90d85fb911bd7aa1deab4e4733c31150/src/js/sections-util.js";
import { getUserstylesFiles } from "@/utils.ts";
const stylesheets = walk(path.join(REPO_ROOT, "styles"), {
includeFiles: true,
includeDirs: false,
includeSymlinks: false,
match: [/\.user.css$/],
});
// Recommended settings. // Recommended settings.
const settings = { const settings = {
@@ -24,8 +15,8 @@ const settings = {
const data: Record<string, unknown>[] = [settings]; const data: Record<string, unknown>[] = [settings];
for await (const entry of stylesheets) { for (const file of getUserstylesFiles()) {
const content = await Deno.readTextFile(entry.path); const content = await Deno.readTextFile(file);
const { metadata } = usercssMeta.parse(content); const { metadata } = usercssMeta.parse(content);
const userstyle = { const userstyle = {
@@ -45,4 +36,4 @@ for await (const entry of stylesheets) {
} }
await ensureDir("dist"); await ensureDir("dist");
Deno.writeTextFile("dist/import.json", JSON.stringify(data)); await Deno.writeTextFile("dist/import.json", JSON.stringify(data));
+41 -45
View File
@@ -2,11 +2,13 @@ import type { Userstyle } from "@/types/userstyles.d.ts";
import * as assert from "@std/assert"; import * as assert from "@std/assert";
import { Octokit } from "@octokit/rest"; import {
import { getUserstylesData } from "@/utils.ts"; addUserstylesTeamMember,
getAuthenticatedOctokit,
const octokit = new Octokit({ auth: Deno.env.get("GITHUB_TOKEN") }); getUserstylesData,
const team = { org: "catppuccin", team_slug: "userstyles-maintainers" }; getUserstylesTeamMembers,
removeUserstylesTeamMember,
} from "@/utils.ts";
const { userstyles } = getUserstylesData(); const { userstyles } = getUserstylesData();
@@ -26,47 +28,41 @@ const maintainers = [
), ),
]; ];
// Lowercase usernames of all maintainers in the current GitHub team. assert.assertExists(maintainers);
const teamMembers = await octokit.teams assert.assert(Array.isArray(maintainers));
.listMembersInOrg({ assert.assertGreater(maintainers.length, 0);
...team,
per_page: 100,
})
.then((res) => res.data.map((m) => m.login.toLowerCase()));
async function syncMaintainers() { const octokit = getAuthenticatedOctokit();
if (!maintainers) return; const team = "userstyles-maintainers";
if (assert.equal(maintainers, teamMembers)) { const maintainersTeamMembers = await getUserstylesTeamMembers(
console.log("Maintainers are in sync"); octokit,
return; team,
} );
const toAdd = maintainers.filter((m) => !teamMembers.includes(m)); if (assert.equal(maintainers, maintainersTeamMembers)) {
const toRemove = teamMembers.filter((m) => !maintainers.includes(m)); console.log("Maintainers are in sync.");
Deno.exit(0);
for (const m of toAdd) {
await octokit.teams.addOrUpdateMembershipForUserInOrg({
...team,
username: m,
});
console.log(`Added ${m} to the ${team.org}/${team.team_slug} team.`);
}
console.log(
`${toAdd.length} users added to the ${team.org}/${team.team_slug} team.`,
);
for (const m of toRemove) {
await octokit.teams.removeMembershipForUserInOrg({
...team,
username: m,
});
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(); const toAdd = maintainers.filter((m) => !maintainersTeamMembers.includes(m));
const toRemove = maintainersTeamMembers.filter((m) => !maintainers.includes(m));
for (const maintainer of toAdd) {
await addUserstylesTeamMember(octokit, team, maintainer);
console.log(
`Added ${maintainer} to the catppuccin/${team} team.`,
);
}
console.log(
`${toAdd.length} users added to the catppuccin/${team} team.`,
);
for (const member of toRemove) {
await removeUserstylesTeamMember(octokit, team, member);
console.log(
`Removed ${member} from the catppuccin/${team} team.`,
);
}
console.log(
`${toRemove.length} users removed from the catppuccin/${team} team.`,
);
+53
View File
@@ -8,6 +8,7 @@ import * as path from "@std/path";
import Ajv, { type Schema } from "ajv"; 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";
import { Octokit } from "@octokit/rest";
/** /**
* @param content A string of YAML content * @param content A string of YAML content
@@ -137,3 +138,55 @@ type Userstyles = SetRequired<
UserstylesSchema.UserstylesSchema, UserstylesSchema.UserstylesSchema,
"userstyles" | "collaborators" "userstyles" | "collaborators"
>; >;
export function getUserstylesFiles(): string[] {
const files: string[] = [];
for (const dir of Deno.readDirSync(path.join(REPO_ROOT, "styles"))) {
if (!dir.isDirectory) continue;
files.push(path.join(REPO_ROOT, "styles", dir.name, "catppuccin.user.css"));
}
return files;
}
export function getAuthenticatedOctokit() {
return new Octokit({ auth: Deno.env.get("GITHUB_TOKEN") });
}
export type UserstylesTeam = "userstyles-staff" | "userstyles-maintainers";
export async function getUserstylesTeamMembers(
octokit: Octokit,
team: UserstylesTeam,
): Promise<string[]> {
const members = await octokit.teams
.listMembersInOrg({
org: "catppuccin",
team_slug: team,
per_page: 100,
});
return members.data.map(({ login }) => login.toLowerCase());
}
export async function addUserstylesTeamMember(
octokit: Octokit,
team: UserstylesTeam,
username: string,
) {
await octokit.teams.addOrUpdateMembershipForUserInOrg({
org: "catppuccin",
team_slug: team,
username,
});
}
export async function removeUserstylesTeamMember(
octokit: Octokit,
team: UserstylesTeam,
username: string,
) {
await octokit.teams.removeMembershipForUserInOrg({
org: "catppuccin",
team_slug: team,
username,
});
}