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 { CalVer } from "@/bump-version/calver.ts";
import { parseArgs } from "@std/cli";
import { getUserstylesFiles } from "@/utils.ts";
const args = parseArgs(Deno.args, { boolean: ["all"] });
@@ -15,10 +16,7 @@ if (!Deno.env.get("CI") && !args.all) {
let files = [];
if (args.all) {
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"));
}
files = getUserstylesFiles();
} else {
files = args._.filter((val) => typeof val == "string").map((p: string) =>
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 { generateStyleReadmes } from "@/generate/readme-styles.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 portsData = await getPortsData();
@@ -30,7 +35,7 @@ await syncIssueLabels(userstylesData.userstyles);
/**
* Keep `.github/CODEOWNERS` in sync with the userstyle metadata.
*/
const maintainersCodeOwners = () => {
function maintainersCodeOwners() {
return Object.entries(userstylesData.userstyles!)
.filter(([_, { "current-maintainers": currentMaintainers }]) =>
currentMaintainers.length > 0
@@ -42,14 +47,22 @@ const maintainersCodeOwners = () => {
return `/styles/${slug} ${codeOwners}`;
})
.join("\n");
};
const userstylesStaffCodeOwners = () => {
}
async function userstylesStaffCodeOwners() {
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",
);
};
}
await writeWithPreamble(
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)({
heading: heading(name, readme["app-link"]),
slug,
+1 -1
View File
@@ -18,7 +18,7 @@ export function updateReadme({
newContent: string;
}): string {
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 endMarker = `<!-- AUTOGEN:${section.toUpperCase()} END -->`;
const wrapped = `${startMarker}\n${preamble}\n${newContent}\n${endMarker}`;
+20 -21
View File
@@ -1,7 +1,6 @@
import { REPO_ROOT } from "@/constants.ts";
import { parseArgs } from "@std/cli";
import * as fs from "@std/fs";
import * as path from "@std/path";
// @ts-types="npm:@types/less";
import less from "less";
@@ -9,31 +8,31 @@ import less from "less";
import { checkForMissingFiles } from "@/lint/file-checker.ts";
import { log } from "@/logger.ts";
import { verifyMetadata } from "@/lint/metadata.ts";
import { lint } from "@/lint/stylelint.ts";
import { getUserstylesData } from "@/utils.ts";
import { runStylelint } from "@/lint/stylelint.ts";
import { getUserstylesData, getUserstylesFiles } from "@/utils.ts";
import stylelintConfig from "../../.stylelintrc.js";
const args = parseArgs(Deno.args, { boolean: ["fix"] });
const subDir = args._[0]?.toString() ?? "";
const stylesheets = fs.walk(path.join(REPO_ROOT, "styles", subDir), {
includeFiles: true,
includeDirs: false,
includeSymlinks: false,
match: [/\.user.css$/],
});
const userstyle = args._[0]?.toString().match(
/(?<base>styles\/)?(?<userstyle>[a-z0-9_\.]+)(?<trailing>\/)?(?<file>catppuccin\.user\.css)?/,
)?.groups?.userstyle;
const stylesheets = userstyle
? [path.join(REPO_ROOT, "styles", userstyle, "catppuccin.user.css")]
: getUserstylesFiles();
const { userstyles } = getUserstylesData();
let failed = false;
let didLintFail = false;
for await (const entry of stylesheets) {
const dir = path.basename(path.dirname(entry.path));
const file = path.relative(REPO_ROOT, entry.path);
for (const style of stylesheets) {
const dir = path.basename(path.dirname(style));
const file = path.relative(REPO_ROOT, style);
let content = await Deno.readTextFile(entry.path);
let content = await Deno.readTextFile(style);
// Verify the UserCSS metadata.
const { globalVars, isLess, fixed } = await verifyMetadata(
entry,
file,
content,
dir,
userstyles,
@@ -48,7 +47,7 @@ for await (const entry of stylesheets) {
// Try to compile the LESS file, report any errors.
less.render(content, { lint: true, globalVars: globalVars }).catch(
(err: Less.RenderError) => {
failed = true;
didLintFail = true;
log.error(
err.message,
{ file, startLine: err.line, endLine: err.line, content },
@@ -57,12 +56,12 @@ for await (const entry of stylesheets) {
);
// Lint with Stylelint.
await lint(entry, content, args.fix, stylelintConfig).catch(() =>
failed = true
await runStylelint(style, content, args.fix, stylelintConfig).catch(() =>
didLintFail = true
);
}
if (await checkForMissingFiles() === false) failed = true;
if (await checkForMissingFiles() === false) didLintFail = true;
// 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 { WalkEntry } from "@std/fs";
import { REPO_ROOT } from "@/constants.ts";
import * as color from "@std/fmt/colors";
@@ -12,7 +11,7 @@ import { log } from "@/logger.ts";
import { formatListOfItems } from "@/utils.ts";
export async function verifyMetadata(
entry: WalkEntry,
file: string,
content: string,
userstyle: string,
userstyles: Userstyles,
@@ -22,7 +21,6 @@ export async function verifyMetadata(
content = content.replaceAll("\r\n", "\n");
const assertions = generateAssertions(userstyle, userstyles);
const file = path.relative(REPO_ROOT, entry.path);
const { metadata, errors: parsingErrors } = usercssMeta.parse(content, {
allowErrors: true,
+4 -5
View File
@@ -1,4 +1,3 @@
import type { WalkEntry } from "@std/fs";
import { REPO_ROOT } from "@/constants.ts";
import * as color from "@std/fmt/colors";
@@ -11,8 +10,8 @@ import "stylelint-config-recommended";
import { log } from "@/logger.ts";
export async function lint(
entry: WalkEntry,
export async function runStylelint(
file: string,
content: string,
fix: boolean,
config: stylelint.Config,
@@ -24,7 +23,7 @@ export async function lint(
});
if (code) {
Deno.writeTextFileSync(entry.path, code);
Deno.writeTextFileSync(path.join(REPO_ROOT, file), code);
}
for (const result of results) {
@@ -36,7 +35,7 @@ export async function lint(
) ?? "unspecified stylelint error";
log.log(message, {
file: path.relative(REPO_ROOT, entry.path),
file,
startLine: warning.line,
endLine: warning.endLine,
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 { 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";
const stylesheets = walk(path.join(REPO_ROOT, "styles"), {
includeFiles: true,
includeDirs: false,
includeSymlinks: false,
match: [/\.user.css$/],
});
import { getUserstylesFiles } from "@/utils.ts";
// Recommended settings.
const settings = {
@@ -24,8 +15,8 @@ const settings = {
const data: Record<string, unknown>[] = [settings];
for await (const entry of stylesheets) {
const content = await Deno.readTextFile(entry.path);
for (const file of getUserstylesFiles()) {
const content = await Deno.readTextFile(file);
const { metadata } = usercssMeta.parse(content);
const userstyle = {
@@ -45,4 +36,4 @@ for await (const entry of stylesheets) {
}
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 { Octokit } from "@octokit/rest";
import { getUserstylesData } from "@/utils.ts";
const octokit = new Octokit({ auth: Deno.env.get("GITHUB_TOKEN") });
const team = { org: "catppuccin", team_slug: "userstyles-maintainers" };
import {
addUserstylesTeamMember,
getAuthenticatedOctokit,
getUserstylesData,
getUserstylesTeamMembers,
removeUserstylesTeamMember,
} from "@/utils.ts";
const { userstyles } = getUserstylesData();
@@ -26,47 +28,41 @@ const maintainers = [
),
];
// Lowercase usernames of all maintainers in the current GitHub team.
const teamMembers = await octokit.teams
.listMembersInOrg({
...team,
per_page: 100,
})
.then((res) => res.data.map((m) => m.login.toLowerCase()));
assert.assertExists(maintainers);
assert.assert(Array.isArray(maintainers));
assert.assertGreater(maintainers.length, 0);
async function syncMaintainers() {
if (!maintainers) return;
if (assert.equal(maintainers, teamMembers)) {
console.log("Maintainers are in sync");
return;
}
const octokit = getAuthenticatedOctokit();
const team = "userstyles-maintainers";
const maintainersTeamMembers = await getUserstylesTeamMembers(
octokit,
team,
);
const toAdd = maintainers.filter((m) => !teamMembers.includes(m));
const toRemove = teamMembers.filter((m) => !maintainers.includes(m));
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.`,
);
if (assert.equal(maintainers, maintainersTeamMembers)) {
console.log("Maintainers are in sync.");
Deno.exit(0);
}
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 { log } from "@/logger.ts";
import { sprintf } from "@std/fmt/printf";
import { Octokit } from "@octokit/rest";
/**
* @param content A string of YAML content
@@ -137,3 +138,55 @@ type Userstyles = SetRequired<
UserstylesSchema.UserstylesSchema,
"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,
});
}