mirror of
https://github.com/lucide-icons/lucide.git
synced 2026-12-02 16:49:06 +00:00
* ci: show icon previews in the PR description Replace the icon-preview comment action with a workflow that writes a preview image per added or changed icon into the PR description, between the "Icon preview" markers from the PR template. The images are served by review.lucide.dev, so the workflow no longer needs dependencies or the PR's SVGs. - scripts/updatePullRequestDescriptionPreview.mts renders the markup and replaces it between the markers (idempotent, keeps CRLF bodies and the surrounding text as is), and updates the body through the REST API. - .github/workflows/pull-request-description-preview.yml runs it on pull_request_target from the base branch only. - Add the "Icon preview" section with the markers to the PR template. - Remove the pull-request-icon-preview workflow and the icon-preview action. Co-Authored-By: Claude <noreply@anthropic.com> * ci: move the PR description preview into the icon-preview action Move the description preview script and its tests from scripts/ into .github/actions/icon-preview, a composite action like the old one, with a package.json (start, debug, test) and an .env.example for local runs. The workflow now calls the action with the PR number, head SHA, changed files and token as inputs. Co-Authored-By: Claude <noreply@anthropic.com> * ci: adjust the icon-preview action instead of adding a new workflow Restore the icon-preview action and its workflow from main and adjust them in place: the action now runs updatePullRequestDescriptionPreview.mts (Node built-ins only, so no dependencies or install step) to write the previews into the PR description, and the workflow calls it with the PR number, head SHA, changed files and token. The separate pull-request-description-preview workflow is removed. Co-Authored-By: Claude <noreply@anthropic.com> * fix(icon-preview): remove a lone marker before adding a fresh pair When only the start or the end marker is left in the description, remove it (with its line break) before prepending a new marker pair, so the body never keeps an orphan marker. Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
209 lines
7.9 KiB
TypeScript
209 lines
7.9 KiB
TypeScript
/**
|
|
* Writes a preview image for every added or changed icon into the description
|
|
* of a pull request, between the "Icon preview" markers from the PR template.
|
|
*
|
|
* The images are rendered by review.lucide.dev, so this script only writes
|
|
* markup that points to them. Like `scripts/updateSponsors.mts`, it replaces
|
|
* whatever is between the markers and leaves the rest of the description
|
|
* untouched.
|
|
*
|
|
* The markup is built by pure functions, and the CLI wrapper at the bottom
|
|
* reads its input from the environment (see `action.yml` and `.env.example`).
|
|
* It only imports Node built-ins, so the action runs it natively as an `.mts`
|
|
* file without a `pnpm install` step.
|
|
*
|
|
* Env input (CLI wrapper at the bottom):
|
|
* - `PR_NUMBER`: the pull request number.
|
|
* - `HEAD_SHA`: the head commit of the pull request, used to bust GitHub's image cache.
|
|
* - `ADDED_FILES`: a space-separated list of added files.
|
|
* - `CHANGED_FILES`: a space-separated list of added, modified and renamed files.
|
|
* - `GITHUB_REPOSITORY`: the `owner/name` of the repository.
|
|
*
|
|
* Writes the description with the `gh` CLI, which needs `GH_TOKEN`.
|
|
*/
|
|
|
|
import { execFileSync } from 'node:child_process';
|
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
|
|
export const startMarker = '[//]: <> (Icon preview start)';
|
|
export const endMarker = '[//]: <> (Icon preview end)';
|
|
|
|
const REVIEW_URL = 'https://review.lucide.dev';
|
|
|
|
// How many icons to show before linking to the review site for the rest.
|
|
export const MAX_ICONS = 40;
|
|
|
|
const VALID_NAME = /^[a-z0-9-]+$/;
|
|
|
|
export type IconStatus = 'added' | 'changed';
|
|
|
|
export type Icon = {
|
|
name: string;
|
|
status: IconStatus;
|
|
};
|
|
|
|
type IconPreviewInput = {
|
|
pr: number;
|
|
sha: string;
|
|
icons: Icon[];
|
|
};
|
|
|
|
const escapeHtml = (value: string) =>
|
|
value
|
|
.replaceAll('&', '&')
|
|
.replaceAll('"', '"')
|
|
.replaceAll('<', '<')
|
|
.replaceAll('>', '>');
|
|
|
|
/**
|
|
* One linked `<picture>` per icon. The `<picture>` has to be on its own line
|
|
* inside the `<a>`, otherwise GitHub doesn't render the link around it.
|
|
* The sources switch to a larger preview on wider screens.
|
|
*/
|
|
const renderIcon = (pr: number, sha: string, { name, status }: Icon) => {
|
|
const imageUrl = (view?: string) => {
|
|
const params = new URLSearchParams();
|
|
if (view) params.set('view', view);
|
|
params.set('v', sha);
|
|
return `${REVIEW_URL}/api/pr/${pr}/${name}/preview.svg?${params}`;
|
|
};
|
|
const href = `${REVIEW_URL}/pr/${pr}?icon=${name}`;
|
|
|
|
return [
|
|
`<a href="${escapeHtml(href)}" target="_blank">`,
|
|
`<picture>`,
|
|
` <source media="(min-width: 1280px)" srcset="${escapeHtml(imageUrl('full'))}" />`,
|
|
` <source media="(min-width: 768px)" srcset="${escapeHtml(imageUrl('medium'))}" />`,
|
|
` <img alt="${escapeHtml(`${name} (${status})`)}" src="${escapeHtml(imageUrl())}" />`,
|
|
`</picture>`,
|
|
`</a>`,
|
|
].join('\n');
|
|
};
|
|
|
|
/**
|
|
* Pure markup function: renders the preview of the given icons, sorted by name.
|
|
* Names that are not valid icon names are dropped. Returns an empty string when
|
|
* there are no icons.
|
|
*/
|
|
export const renderIconPreview = ({ pr, sha, icons }: IconPreviewInput): string => {
|
|
const shortSha = sha.slice(0, 7);
|
|
const validIcons = icons
|
|
.filter(({ name }) => VALID_NAME.test(name))
|
|
.filter((icon, index, all) => all.findIndex(({ name }) => name === icon.name) === index)
|
|
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
|
|
if (validIcons.length === 0) return '';
|
|
|
|
const blocks = validIcons.slice(0, MAX_ICONS).map((icon) => renderIcon(pr, shortSha, icon));
|
|
|
|
const remaining = validIcons.length - MAX_ICONS;
|
|
if (remaining > 0) {
|
|
blocks.push(
|
|
`…and ${remaining} more ${remaining === 1 ? 'icon' : 'icons'}, see all on [review.lucide.dev](${REVIEW_URL}/pr/${pr}).`,
|
|
);
|
|
}
|
|
|
|
return blocks.join('\n\n');
|
|
};
|
|
|
|
/**
|
|
* Removes every occurrence of `marker` together with the line break after it
|
|
* (or before it, when it's on the last line), so no empty line is left behind.
|
|
*/
|
|
const removeMarker = (body: string, marker: string): string => {
|
|
const escaped = marker.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
return body.replaceAll(new RegExp(`${escaped}\\r?\\n|\\r?\\n${escaped}$|${escaped}`, 'g'), '');
|
|
};
|
|
|
|
/**
|
|
* Replaces everything between the markers with `markup`, like
|
|
* `scripts/updateSponsors.mts` does for the README. The text around the
|
|
* markers is kept as is. When the markers are missing they are added, with the
|
|
* markup, at the start of the body; a lone start or end marker is removed
|
|
* first. CRLF bodies (as written by the GitHub web editor) keep their line
|
|
* endings.
|
|
*/
|
|
export const replaceBetweenMarkers = (body: string, markup: string): string => {
|
|
const eol = body.includes('\r\n') ? '\r\n' : '\n';
|
|
const separator = `${eol}${eol}`;
|
|
const content = markup.replaceAll(/\r?\n/g, eol);
|
|
|
|
const startIndex = body.indexOf(startMarker);
|
|
const endIndex = body.indexOf(endMarker);
|
|
|
|
if (startIndex === -1 || endIndex === -1) {
|
|
// A lone marker is removed, so the body ends up with exactly one pair.
|
|
const orphan = startIndex !== -1 ? startMarker : endIndex !== -1 ? endMarker : null;
|
|
const rest = orphan == null ? body : removeMarker(body, orphan);
|
|
const block = [startMarker, content, endMarker].filter(Boolean).join(separator);
|
|
return rest === '' ? block : `${block}${separator}${rest}`;
|
|
}
|
|
|
|
if (endIndex < startIndex) {
|
|
throw new Error(`"${endMarker}" comes before "${startMarker}" in the description`);
|
|
}
|
|
|
|
return [body.slice(0, startIndex + startMarker.length), content, body.slice(endIndex)]
|
|
.filter(Boolean)
|
|
.join(separator);
|
|
};
|
|
|
|
// --- CLI wrapper -----------------------------------------------------------
|
|
// Only runs when executed directly, keeping the functions above unit-testable.
|
|
|
|
const iconNames = (list: string | undefined): string[] =>
|
|
(list ?? '')
|
|
.split(/\s+/)
|
|
.map((file) => /^icons\/([^/]+)\.svg$/.exec(file.trim())?.[1])
|
|
.filter((name) => name != null);
|
|
|
|
if (import.meta.main) {
|
|
const { PR_NUMBER, HEAD_SHA, ADDED_FILES, CHANGED_FILES, GITHUB_REPOSITORY } = process.env;
|
|
|
|
const pr = Number(PR_NUMBER);
|
|
if (!Number.isInteger(pr) || pr <= 0) throw new Error(`Invalid PR_NUMBER: ${PR_NUMBER}`);
|
|
if (!HEAD_SHA) throw new Error('HEAD_SHA is required');
|
|
if (!GITHUB_REPOSITORY) throw new Error('GITHUB_REPOSITORY is required');
|
|
|
|
const added = iconNames(ADDED_FILES);
|
|
const changed = iconNames(CHANGED_FILES).filter((name) => !added.includes(name));
|
|
const icons: Icon[] = [
|
|
...added.map((name) => ({ name, status: 'added' as const })),
|
|
...changed.map((name) => ({ name, status: 'changed' as const })),
|
|
];
|
|
|
|
const markup = renderIconPreview({ pr, sha: HEAD_SHA, icons });
|
|
const endpoint = `repos/${GITHUB_REPOSITORY}/pulls/${pr}`;
|
|
|
|
// Fetch the current body right before writing, so edits made since the
|
|
// workflow was triggered are not overwritten.
|
|
const pullRequest = JSON.parse(execFileSync('gh', ['api', endpoint], { encoding: 'utf-8' }));
|
|
const body: string = pullRequest.body ?? '';
|
|
|
|
const hasMarkers = body.includes(startMarker) || body.includes(endMarker);
|
|
if (markup === '' && !hasMarkers) {
|
|
console.log('No icon previews and no markers, leaving the description alone.');
|
|
} else {
|
|
const newBody = replaceBetweenMarkers(body, markup);
|
|
|
|
if (newBody === body) {
|
|
console.log('Icon preview is up to date.');
|
|
} else {
|
|
// The body goes through a file, so it never ends up in a shell argument.
|
|
const tempDir = mkdtempSync(join(tmpdir(), 'pr-description-'));
|
|
const bodyPath = join(tempDir, 'body.md');
|
|
try {
|
|
writeFileSync(bodyPath, newBody);
|
|
execFileSync('gh', ['api', '-X', 'PATCH', endpoint, '-F', `body=@${bodyPath}`], {
|
|
stdio: ['ignore', 'ignore', 'inherit'],
|
|
});
|
|
} finally {
|
|
rmSync(tempDir, { recursive: true, force: true });
|
|
}
|
|
console.log(`Updated the icon preview of #${pr} with ${icons.length} icon(s).`);
|
|
}
|
|
}
|
|
}
|