diff --git a/.github/actions/icon-preview/.env.example b/.github/actions/icon-preview/.env.example index 4eebd9822..0f3a9c6dd 100644 --- a/.github/actions/icon-preview/.env.example +++ b/.github/actions/icon-preview/.env.example @@ -1,7 +1,18 @@ # Local testing for the icon-preview action. # Copy to `.env` in this folder and run `pnpm --filter @lucide/icon-preview-action debug`. -# The comment markup is printed to stdout. +# This edits the description of a real pull request, so point it at a test PR. # Required -# Space-separated list of changed icon files, relative to the repo root +# The pull request to update +PR_NUMBER= +# Head commit SHA of the pull request, used to bust GitHub's image cache +HEAD_SHA= +# Space-separated list of added icon files, relative to the repo root +ADDED_FILES=icons/heart.svg +# Space-separated list of added, modified and renamed icon files, relative to the repo root CHANGED_FILES=icons/heart.svg icons/star.svg +# The `owner/name` of the repository (set by the runner in GitHub Actions) +GITHUB_REPOSITORY=lucide-icons/lucide +# A token with write access to pull requests, used by the `gh` CLI +# (can be left out when `gh auth login` was used) +GH_TOKEN= diff --git a/.github/actions/icon-preview/action.yml b/.github/actions/icon-preview/action.yml index b3b3c4ec8..a95474e59 100644 --- a/.github/actions/icon-preview/action.yml +++ b/.github/actions/icon-preview/action.yml @@ -1,67 +1,34 @@ name: Icon preview -description: Generates the icon preview comment markup for changed icons in a pull request. +description: Writes a preview image for every added or changed icon into the pull request description, between the "Icon preview" markers. inputs: - changed-files: - description: Space-separated list of changed icon files, relative to the repository root. + pr-number: + description: Number of the pull request to update. required: true - ref: + head-sha: + description: Head commit SHA of the pull request, used to bust GitHub's image cache. + required: true + added-files: + description: Space-separated list of added icon files, relative to the repository root. + required: true + changed-files: description: >- - Commit to read the changed icons from, e.g. the pull request head SHA. Only the changed SVG - files are taken from it with `git show`, nothing is checked out. Defaults to the working tree. - required: false - default: '' - output-file: - description: File the comment markup is written to. - required: false - default: comment-markup.md - -outputs: - has-changes: - description: Whether any changed icons were found. When `false`, no output file is written. - value: ${{ steps.generate.outputs.has-changes }} + Space-separated list of added, modified and renamed icon files, relative to the repository + root. Deleted files should be left out. + required: true + github-token: + description: 'GitHub token with `pull-requests: write` permission to edit the description.' + required: true runs: using: composite steps: - - name: Read changed icons from ref - id: read-ref - if: inputs.ref != '' + - name: Update PR description shell: bash - run: | - git fetch --no-tags --depth=1 origin "$REF" - - for file in $CHANGED_FILES; do - # Only plain icon file names, so nothing from the pull request ends up in a path or the markup - if [[ ! "$file" =~ ^icons/[a-z0-9-]+\.svg$ ]]; then - echo "::error::Unexpected changed file: $file" - exit 1 - fi - - mkdir -p "$RUNNER_TEMP/icon-preview/icons" - git show "$REF:$file" > "$RUNNER_TEMP/icon-preview/$file" - done - - echo "dir=$RUNNER_TEMP/icon-preview" >> "$GITHUB_OUTPUT" + run: node "$GITHUB_ACTION_PATH/updatePullRequestDescriptionPreview.mts" env: + GH_TOKEN: ${{ inputs.github-token }} + PR_NUMBER: ${{ inputs.pr-number }} + HEAD_SHA: ${{ inputs.head-sha }} + ADDED_FILES: ${{ inputs.added-files }} CHANGED_FILES: ${{ inputs.changed-files }} - REF: ${{ inputs.ref }} - - - name: Generate comment markup - id: generate - shell: bash - run: | - markup="$(node "$GITHUB_ACTION_PATH/generateChangedIconsCommentMarkup.mts")" - - if [ -z "$markup" ]; then - echo "has-changes=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - mkdir -p "$(dirname "$OUTPUT_FILE")" - printf '%s\n' "$markup" > "$OUTPUT_FILE" - echo "has-changes=true" >> "$GITHUB_OUTPUT" - env: - CHANGED_FILES: ${{ inputs.changed-files }} - CHANGED_FILES_DIR: ${{ steps.read-ref.outputs.dir }} - OUTPUT_FILE: ${{ inputs.output-file }} diff --git a/.github/actions/icon-preview/generateChangedIconsCommentMarkup.mts b/.github/actions/icon-preview/generateChangedIconsCommentMarkup.mts deleted file mode 100644 index afeacb5e2..000000000 --- a/.github/actions/icon-preview/generateChangedIconsCommentMarkup.mts +++ /dev/null @@ -1,232 +0,0 @@ -import fs from 'fs'; -import path from 'path'; -import { parseSync } from 'svgson'; -import { - shuffleArray, - readSvgDirectory, - getCurrentDirPath, - minifySvg, - toPascalCase, -} from '@lucide/helpers'; - -// The script lives in `.github/actions/icon-preview`, three levels below the repo root. -const REPO_ROOT = path.resolve(getCurrentDirPath(import.meta.url), '../../..'); -const ICONS_DIR = path.join(REPO_ROOT, 'icons'); -// The changed SVGs can be read from another directory, e.g. files taken from the pull request head -const CHANGED_FILES_DIR = process.env.CHANGED_FILES_DIR || REPO_ROOT; -const BASE_URL = 'https://lucide.dev/api/gh-icon'; - -const changedFilesPathString = process.env.CHANGED_FILES; - -if (changedFilesPathString == null) { - console.error('CHANGED_FILES env variable is not set'); - process.exit(1); -} - -const changedFiles = changedFilesPathString - .split(' ') - .filter((file) => file.includes('.svg')) - .filter((file, idx, arr) => arr.indexOf(file) === idx) - .map((file) => path.join(CHANGED_FILES_DIR, file)); - -// Print nothing to stdout, so the action writes no comment markup -if (changedFiles.length === 0) { - console.error('No changed icons found'); - process.exit(0); -} - -const getImageTagsByFiles = ( - files: string[], - getBaseUrl: (file: string) => string, - width?: number, - linkToLucideStudio = false, -) => - files.map((file) => { - const svgContent = fs.readFileSync(file, 'utf-8'); - const strippedAttrsSVG = svgContent.replace(/]*>/, ''); - const minifiedSvg = minifySvg(strippedAttrsSVG); - const name = path.basename(file, '.svg'); - - const base64 = Buffer.from(minifiedSvg).toString('base64'); - const url = getBaseUrl(file); - const widthAttr = width ? `width="${width}"` : ''; - - return `${linkToLucideStudio ? `` : ''}${name}${linkToLucideStudio ? '' : ''}`; - }); - -const svgFiles = await readSvgDirectory(ICONS_DIR); -const svgFilePaths = svgFiles.map((file) => path.join(ICONS_DIR, file)); - -const iconsFilteredByName = (search: string) => - svgFilePaths.filter((file) => path.basename(file).includes(search)); - -const cohesionRandomImageTags = getImageTagsByFiles( - shuffleArray(svgFilePaths).slice(0, changedFiles.length), - () => `${BASE_URL}/stroke-width/2`, -).join(''); - -const cohesionSquaresImageTags = getImageTagsByFiles( - shuffleArray(iconsFilteredByName('square')).slice(0, changedFiles.length), - () => `${BASE_URL}/stroke-width/2`, -).join(''); - -const changeFiles1pxStrokeImageTags = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/stroke-width/1`, -).join(''); - -const changeFiles2pxStrokeImageTags = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/stroke-width/2`, -).join(''); - -const changeFiles3pxStrokeImageTags = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/stroke-width/3`, -).join(''); - -const changeFilesLowDPIImageTags16 = getImageTagsByFiles(changedFiles, (file) => { - const iconName = path.basename(file, '.svg'); - return `${BASE_URL}/dpi/${iconName}/16`; -}).join(' '); - -const changeFilesLowDPIImageTags24 = getImageTagsByFiles(changedFiles, (file) => { - const iconName = path.basename(file, '.svg'); - return `${BASE_URL}/dpi/${iconName}/24`; -}).join(' '); - -const changeFilesLowDPIImageTags32 = getImageTagsByFiles(changedFiles, (file) => { - const iconName = path.basename(file, '.svg'); - return `${BASE_URL}/dpi/${iconName}/32`; -}).join(' '); - -const changeFilesLowDPIImageTags48 = getImageTagsByFiles(changedFiles, (file) => { - const iconName = path.basename(file, '.svg'); - return `${BASE_URL}/dpi/${iconName}/48`; -}).join(' '); - -const changeFilesXRayImageTags = getImageTagsByFiles( - changedFiles, - (file) => { - const iconName = path.basename(file, '.svg'); - - return `${BASE_URL}/${iconName}`; - }, - 400, - true, -).join(' '); - -const changeFilesDiffImageTags = getImageTagsByFiles( - changedFiles, - (file) => { - const iconName = path.basename(file, '.svg'); - - return `${BASE_URL}/diff/${iconName}`; - }, - 400, -).join(' '); - -const changeFilesSymmetryImageTagsRotate180 = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/symmetry/rotate-180`, - 400, -).join(' '); - -const changeFilesSymmetryImageTagsFlipHorizontal = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/symmetry/flip-horizontal`, - 400, -).join(' '); - -const changeFilesSymmetryImageTagsFlipVertical = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/symmetry/flip-vertical`, - 400, -).join(' '); - -const changeFilesSymmetryImageTagsFlipSlash = getImageTagsByFiles( - changedFiles, - () => `${BASE_URL}/symmetry/flip-slash`, - 400, -).join(' '); - -const readyToUseCode = changedFiles - .map((changedFile) => { - const svgContent = fs.readFileSync(changedFile, 'utf-8'); - const name = path.basename(changedFile, '.svg'); - return `const ${toPascalCase(name)}Icon = createLucideIcon('${toPascalCase(name)}', [ - ${parseSync(svgContent) - .children.map(({ name, attributes }) => JSON.stringify([name, attributes])) - .join(',\n ')} -])`; - }) - .join('\n\n'); - -const commentMarkup = `\ -### Added or changed icons -${ - changedFiles.length >= 8 - ? `
-Icon X-rays -${changeFilesXRayImageTags} -
-` - : '' -}${changeFiles2pxStrokeImageTags} -
-Preview cohesion -${cohesionSquaresImageTags}
-${changeFiles2pxStrokeImageTags}
-${cohesionRandomImageTags}
-
-
-Preview stroke widths -${changeFiles1pxStrokeImageTags}
-${changeFiles2pxStrokeImageTags}
-${changeFiles3pxStrokeImageTags}
-
-
-DPI Preview -

16px (shadcn/ui)

-${changeFilesLowDPIImageTags16} -

24px (default)

-${changeFilesLowDPIImageTags24} -

32px (shadcn/ui + retina)

-${changeFilesLowDPIImageTags32} -

48px (default + retina)

-${changeFilesLowDPIImageTags48} -
${ - changedFiles.length < 8 - ? ` -
-Icon X-rays -${changeFilesXRayImageTags} -
` - : '' -} -
-Icon Diffs -${changeFilesDiffImageTags} -
-
-Icon Symmetry -

Flip Horizontal

-${changeFilesSymmetryImageTagsFlipHorizontal} -

Flip Vertical

-${changeFilesSymmetryImageTagsFlipVertical} -

Flip Diagonal

-${changeFilesSymmetryImageTagsFlipSlash} -

Rotate 180°

-${changeFilesSymmetryImageTagsRotate180} -
-
-Icons as code - -Works for: \`lucide-react\`, \`lucide-react-native\`, \`lucide-preact\`, \`lucide-vue-next\` -\`\`\`ts -${readyToUseCode} -\`\`\` - -
`; - -console.log(commentMarkup); diff --git a/.github/actions/icon-preview/package.json b/.github/actions/icon-preview/package.json index 2a8ca0387..e7319ac15 100644 --- a/.github/actions/icon-preview/package.json +++ b/.github/actions/icon-preview/package.json @@ -2,13 +2,10 @@ "name": "@lucide/icon-preview-action", "private": true, "type": "module", - "description": "GitHub action that generates the icon preview comment markup for changed icons in a pull request", + "description": "GitHub action that writes a preview of the added or changed icons into the pull request description", "scripts": { - "start": "node ./generateChangedIconsCommentMarkup.mts", - "debug": "node --env-file .env ./generateChangedIconsCommentMarkup.mts" - }, - "dependencies": { - "@lucide/helpers": "workspace:*", - "svgson": "catalog:" + "start": "node ./updatePullRequestDescriptionPreview.mts", + "debug": "node --env-file .env ./updatePullRequestDescriptionPreview.mts", + "test": "node --test ./*.test.mts" } } diff --git a/.github/actions/icon-preview/updatePullRequestDescriptionPreview.mts b/.github/actions/icon-preview/updatePullRequestDescriptionPreview.mts new file mode 100644 index 000000000..0abaefbc7 --- /dev/null +++ b/.github/actions/icon-preview/updatePullRequestDescriptionPreview.mts @@ -0,0 +1,208 @@ +/** + * 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 `` per icon. The `` has to be on its own line + * inside the ``, 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 [ + ``, + ``, + ` `, + ` `, + ` ${escapeHtml(`${name} (${status})`)}`, + ``, + ``, + ].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).`); + } + } +} diff --git a/.github/actions/icon-preview/updatePullRequestDescriptionPreview.test.mts b/.github/actions/icon-preview/updatePullRequestDescriptionPreview.test.mts new file mode 100644 index 000000000..4387fda61 --- /dev/null +++ b/.github/actions/icon-preview/updatePullRequestDescriptionPreview.test.mts @@ -0,0 +1,222 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + endMarker, + MAX_ICONS, + renderIconPreview, + replaceBetweenMarkers, + startMarker, +} from './updatePullRequestDescriptionPreview.mts'; + +const SHA = 'abc1234def5678'; + +describe('renderIconPreview', () => { + it('renders a linked picture per icon', () => { + assert.equal( + renderIconPreview({ pr: 42, sha: SHA, icons: [{ name: 'heart', status: 'added' }] }), + [ + '', + '', + ' ', + ' ', + ' heart (added)', + '', + '', + ].join('\n'), + ); + }); + + it('uses the status in the alt text', () => { + const markup = renderIconPreview({ + pr: 1, + sha: SHA, + icons: [ + { name: 'heart', status: 'changed' }, + { name: 'star', status: 'added' }, + ], + }); + assert.match(markup, /alt="heart \(changed\)"/); + assert.match(markup, /alt="star \(added\)"/); + }); + + it('sorts by name and separates icons with a blank line', () => { + const markup = renderIconPreview({ + pr: 1, + sha: SHA, + icons: [ + { name: 'zap', status: 'added' }, + { name: 'anchor', status: 'changed' }, + ], + }); + const blocks = markup.split('\n\n'); + assert.equal(blocks.length, 2); + assert.match(blocks[0], /icon=anchor"/); + assert.match(blocks[1], /icon=zap"/); + }); + + it('drops invalid icon names', () => { + const markup = renderIconPreview({ + pr: 1, + sha: SHA, + icons: [ + { name: 'heart', status: 'added' }, + { name: 'Heart', status: 'added' }, + { name: '">