ci: move src/ -> scripts/, deno.json to repo root (#332)

This commit is contained in:
winston authored and GitHub committed 2023-11-18 07:18:08 +01:00
1 parent f977c5a64c
commit 790e7cb83c
21 files changed
+21 -26

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import { exists } from "std/fs/mod.ts";
import { join, relative } from "std/path/mod.ts";
import core from "@actions/core";
import { REPO_ROOT } from "@/deps.ts";
import { log } from "./logger.ts";
import chalk from "chalk";
const requiredFiles = [
"catppuccin.user.css",
...["latte", "frappe", "macchiato", "mocha", "catwalk"].map((f) =>
join("assets", `${f}.webp`)
),
];
export const checkForMissingFiles = async () => {
const stylesRoot = 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);
await Promise.all(requiredFiles.map(async (f) => {
const fp = join(styleRoot, f);
const rfp = relative(REPO_ROOT, fp);
if (!(await exists(fp))) {
missingFiles.push(rfp);
}
}));
}
// only write summary if running in github actions
if (Deno.env.has("GITHUB_ACTIONS")) {
await core.summary
.addHeading("Missing files")
.addList(missingFiles)
.write();
} else {
missingFiles.map((f) => {
log(chalk.red(`Missing file:`) + ` ${f}`, { file: f }, "error");
});
}
return missingFiles.length === 0;
};
+82
View File
@@ -0,0 +1,82 @@
import { sprintf } from "std/fmt/printf.ts";
import chalk from "chalk";
import core from "@actions/core";
export type LoggerProps = core.AnnotationProperties & { content?: string };
const pretty_print = (
message: string,
props: LoggerProps,
severity: "error" | "warning" = "warning",
) => {
const { file, startColumn, startLine } = props;
if (!startLine) return console.log(message);
const lines = (props.content ?? "").split("\n");
const error = [
chalk[severity === "error" ? "red" : "yellow"](severity),
message,
].join(" ");
const line = lines[startLine - 1].split("").map((char, i) => {
const startCol = (props.startColumn ?? 0) - 1;
const endCol = (props.endColumn ?? Infinity) - 1;
if (i >= startCol && i <= endCol) {
return chalk[severity === "error" ? "red" : "yellow"](char);
} else {
return char;
}
}).join("");
const pad = startLine.toString().length;
console.log(
[
chalk.underline(
sprintf(
"%s%s%d%s%d",
file,
startLine ? ":" : "",
startLine ?? "",
startColumn ? ":" : "",
startColumn ?? "",
),
),
sprintf(
"%*s│ %s",
pad,
chalk.dim(startLine - 1),
chalk.dim(lines[startLine - 2]),
),
sprintf("%*s│ %s", pad, chalk.bold(startLine), line),
sprintf(
"%*s│ %s",
pad,
chalk.dim(startLine + 1),
chalk.dim(lines[startLine]),
),
sprintf("%*s╰─► %s", pad, "", error),
undefined,
].join("\n"),
);
};
export const log = (
message: string,
props: LoggerProps,
severity: "error" | "warning" = "warning",
) => {
if (Deno.env.has("CI")) {
switch (severity) {
case "error":
core.error(message, props);
break;
case "warning":
core.warning(message, props);
break;
}
} else {
pretty_print(message, props, severity);
}
};
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env -S deno run -A
import { walk } from "std/fs/mod.ts";
import { parse as parseFlags } from "std/flags/mod.ts";
import { basename, dirname, join, relative } from "std/path/mod.ts";
// @deno-types="npm:@types/less";
import less from "less";
import { REPO_ROOT } from "@/deps.ts";
import { checkForMissingFiles } from "./file-checker.ts";
import { log } from "./logger.ts";
import { verifyMetadata } from "./metadata.ts";
import { lint } from "./stylelint.ts";
const flags = parseFlags(Deno.args, { boolean: ["fix"] });
const stylesheets = walk(join(REPO_ROOT, "styles"), {
includeFiles: true,
includeDirs: false,
includeSymlinks: false,
match: [/\.user.css$/],
});
for await (const entry of stylesheets) {
const repodir = dirname(entry.path);
const repo = basename(repodir);
const file = relative(REPO_ROOT, entry.path);
const content = await Deno.readTextFile(entry.path);
// verify the usercss metadata
const { globalVars, isLess } = await verifyMetadata(entry, content, repo)
.catch((e) => {
const lines = content.split("\n");
let startLine = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (e.index >= line.length) {
e.index -= line.length;
startLine++;
} else break;
}
log(e.message, { file, startLine, content }, "error");
throw e;
});
// don't attempt to compile or lint non-less files
if (!isLess) continue;
// try to compile the less file, report any errors
less.render(content, { lint: true, globalVars }).then().catch(
(err) => {
log(
err.message,
{ file, startLine: err.line, endLine: err.line, content },
"error",
);
},
);
// advanced linting with stylelint
lint(entry, content, flags.fix);
}
// if any files are missing, cause the workflow to fail
if (await checkForMissingFiles() === false) {
Deno.exit(1);
}
+81
View File
@@ -0,0 +1,81 @@
// TODO: remove this once types for usercss-meta are available
// deno-lint-ignore-file no-explicit-any
import chalk from "chalk";
import usercssMeta from "usercss-meta";
import { log } from "./logger.ts";
import { sprintf } from "std/fmt/printf.ts";
import type { WalkEntry } from "std/fs/mod.ts";
import { relative } from "std/path/mod.ts";
import { REPO_ROOT } from "@/deps.ts";
export const verifyMetadata = (
entry: WalkEntry,
content: string,
repo: string,
): Promise<{
globalVars: Record<string, string>;
isLess: boolean;
}> => {
return new Promise((resolve, reject) => {
const assert = assertions(repo);
const file = relative(REPO_ROOT, entry.path);
let metadata: Record<string, any> = {};
try {
metadata = usercssMeta.parse(content).metadata;
} catch (err) {
log(err, { file }, "error");
reject(err);
}
Object.entries(assert).forEach(([k, v]) => {
const defacto = metadata[k];
if (defacto !== v) {
const line = content
.split("\n")
.findIndex((line) => line.includes(k)) + 1;
const message = sprintf(
"Metadata %s should be %s but is %s",
chalk.bold(k),
chalk.green(v),
chalk.red(defacto),
);
log(message, {
file,
startLine: line !== 0 ? line : undefined,
content,
}, "warning");
}
});
// parse the usercss variables to less global variables, e.g.
// `@var select lightFlavor "Light Flavor" ["latte:Latte*", "frappe:Frappé", "macchiato:Macchiato", "mocha:Mocha"]`
// gets parsed as
// `lightFlavor: "latte"`
const globalVars = Object.entries<{ default: string }>(metadata.vars)
.reduce((acc, [k, v]) => {
return { ...acc, [k]: v.default };
}, {});
resolve({
globalVars,
isLess: metadata.preprocessor === assert.preprocessor,
});
});
};
const assertions = (repo: string) => {
const prefix = "https://github.com/catppuccin/userstyles";
return {
namespace: `github.com/catppuccin/userstyles/styles/${repo}`,
author: "Catppuccin",
license: "MIT",
preprocessor: "less",
homepageURL: `${prefix}/tree/main/styles/${repo}`,
updateURL: `${prefix}/raw/main/styles/${repo}/catppuccin.user.css`,
};
};
+199
View File
@@ -0,0 +1,199 @@
import { deepMerge } from "std/collections/mod.ts";
import chalk from "chalk";
import stylelint from "npm:stylelint";
import stylelintConfigStandard from "npm:stylelint-config-standard";
import stylelintConfigRecommended from "npm:stylelint-config-recommended";
import postcssLess from "npm:postcss-less";
import { log } from "./logger.ts";
import { relative } from "https://deno.land/[email protected]/path/mod.ts";
import { REPO_ROOT } from "@/deps.ts";
import { WalkEntry } from "std/fs/walk.ts";
const config: stylelint.Config = {
customSyntax: postcssLess,
rules: {
"selector-class-pattern": null,
"custom-property-pattern": null,
"selector-id-pattern": null,
"rule-empty-line-before": null,
"comment-empty-line-before": null,
"custom-property-empty-line-before": null,
"at-rule-empty-line-before": null,
"declaration-empty-line-before": null,
"property-no-vendor-prefix": null,
"alpha-value-notation": null,
"color-function-notation": null,
"hue-degree-notation": null,
// less doesn't care about these
"no-invalid-position-at-import-rule": null,
"no-invalid-double-slash-comments": null,
"at-rule-disallowed-list": [[
"/^font.*/",
], {
message: (atRule: string) =>
`At-rule ${atRule} is not allowed in Catppuccin userstyles`,
}],
"property-disallowed-list": [[
// disallow setting fonts
"/font.*/",
// ideally we could disallow these, but CSS continues to be gross
// "/animation.*/",
// "/transition.*/",
// prefer `border-color` over `border`, `outline-color` over `outline`, etc.
"border",
"outline",
], {
message: (prop: string) => {
if (["border", "outline"].includes(prop)) {
return `Use \`${prop}-color\` instead of \`${prop}\``;
} else {
return `Property \`${prop}\` is not allowed in Catppuccin userstyles`;
}
},
}],
"function-no-unknown": [
true,
{
ignoreFunctions: [
// generated from https://lesscss.org/functions/
// via `Array.from(document.querySelectorAll('.section-content h3.docs-heading'), heading => heading.textContent.replace('\n', ''))`
"%",
"abs",
"acos",
"alpha",
"argb",
"asin",
"atan",
"average",
"blue",
"boolean",
"ceil",
"color",
"contrast",
"convert",
"cos",
"darken",
"data-uri",
"default",
"desaturate",
"difference",
"e",
"each",
"escape",
"exclusion",
"extract",
"fade",
"fadein",
"fadeout",
"floor",
"get-unit",
"green",
"greyscale",
"hardlight",
"hsl",
"hsla",
"hsv",
"hsva",
"hsvhue",
"hsvsaturation",
"hsvvalue",
"hue",
"if",
"image-height",
"image-size",
"image-width",
"iscolor",
"isdefined",
"isem",
"iskeyword",
"isnumber",
"ispercentage",
"ispixel",
"isruleset",
"isstring",
"isunit",
"isurl",
"length",
"lighten",
"lightness",
"luma",
"luminance",
"max",
"min",
"mix",
"mod",
"multiply",
"negation",
"overlay",
"percentage",
"pi",
"pow",
"range",
"red",
"replace",
"rgb",
"rgba",
"round",
"saturate",
"saturation",
"screen",
"shade",
"sin",
"softlight",
"spin",
"sqrt",
"svg-gradient",
"tan",
"tint",
"unit",
],
},
],
"function-name-case": null,
"no-descending-specificity": null,
},
};
const base = deepMerge(
stylelintConfigRecommended,
{ ...stylelintConfigStandard, extends: {} },
);
export const lint = (entry: WalkEntry, content: string, fix: boolean) => {
const file = relative(REPO_ROOT, entry.path);
stylelint.lint({
config: deepMerge(base, config),
files: entry.path,
fix,
})
.then(({ results }) => {
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}\\)?`),
chalk.dim(`(${warning.rule})`),
) ?? "unspecified stylelint error";
log(message, {
file,
startLine: warning.line,
endLine: warning.endLine,
startColumn: warning.column,
endColumn: warning.endColumn,
content,
}, warning.severity);
});
});
});
};