mirror of
https://github.com/lucide-icons/lucide.git
synced 2026-11-14 13:58:21 +00:00
Merge branch 'main' of https://github.com/lucide-icons/lucide into icon-usage-context
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* ESLint formatter for GitHub Actions. Prints each problem as a readable line plus a workflow
|
||||
* command (`::error file=…`), so it shows up as an inline annotation in the PR diff.
|
||||
*
|
||||
* Unlike setup-node's `eslint-stylish` problem matcher, this also annotates parsing errors, which
|
||||
* have no rule id.
|
||||
*
|
||||
* Usage: eslint --format ./scripts/eslint/githubFormatter.mjs
|
||||
*/
|
||||
|
||||
/** Escape data for a workflow command, see https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts */
|
||||
const escapeData = (/** @type {string} */ value) =>
|
||||
value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
|
||||
const escapeProperty = (/** @type {string} */ value) =>
|
||||
escapeData(value).replaceAll(':', '%3A').replaceAll(',', '%2C');
|
||||
|
||||
/** @type {import('eslint').ESLint.FormatterFunction} */
|
||||
const formatter = (results) => {
|
||||
const lines = [];
|
||||
let errors = 0;
|
||||
let warnings = 0;
|
||||
|
||||
for (const result of results) {
|
||||
const file = path.relative(process.cwd(), result.filePath);
|
||||
|
||||
for (const message of result.messages) {
|
||||
const severity = message.severity === 2 ? 'error' : 'warning';
|
||||
if (severity === 'error') errors++;
|
||||
else warnings++;
|
||||
|
||||
const rule = message.ruleId ?? 'parse';
|
||||
const line = message.line ?? 1;
|
||||
const column = message.column ?? 1;
|
||||
lines.push(`${file}:${line}:${column} ${severity} ${message.message} (${rule})`);
|
||||
|
||||
const properties = [
|
||||
`file=${escapeProperty(file)}`,
|
||||
`line=${line}`,
|
||||
`col=${column}`,
|
||||
message.endLine ? `endLine=${message.endLine}` : '',
|
||||
message.endColumn ? `endColumn=${message.endColumn}` : '',
|
||||
`title=${escapeProperty(`ESLint (${rule})`)}`,
|
||||
].filter(Boolean);
|
||||
lines.push(`::${severity} ${properties.join(',')}::${escapeData(message.message)}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (errors + warnings > 0) {
|
||||
const plural = (/** @type {number} */ count, /** @type {string} */ word) =>
|
||||
`${count} ${word}${count === 1 ? '' : 's'}`;
|
||||
lines.push(
|
||||
'',
|
||||
`✖ ${plural(errors + warnings, 'problem')} (${plural(errors, 'error')}, ${plural(warnings, 'warning')})`,
|
||||
);
|
||||
}
|
||||
return lines.join('\n');
|
||||
};
|
||||
|
||||
export default formatter;
|
||||
@@ -0,0 +1,147 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Ajv2020 } from 'ajv/dist/2020.js';
|
||||
import { getStaticJSONValue } from 'jsonc-eslint-parser';
|
||||
|
||||
/**
|
||||
* ESLint plugin that validates JSON files against a configured JSON Schema (draft 2020-12),
|
||||
* reporting each error at the offending property. It also requires the file's `$schema` field to
|
||||
* point at that schema.
|
||||
*
|
||||
* Off-the-shelf plugins (e.g. eslint-plugin-json-schema-validator) only run Ajv in draft-07 mode,
|
||||
* which silently skips 2020-12 keywords such as `dependentRequired`.
|
||||
*/
|
||||
|
||||
const ajv = new Ajv2020({ allErrors: true });
|
||||
/** @type {Map<string, import('ajv').ValidateFunction>} */
|
||||
const validators = new Map();
|
||||
|
||||
/** @param {string} schemaPath */
|
||||
const getValidator = (schemaPath) => {
|
||||
let validate = validators.get(schemaPath);
|
||||
if (!validate) {
|
||||
validate = ajv.compile(JSON.parse(fs.readFileSync(schemaPath, 'utf-8')));
|
||||
validators.set(schemaPath, validate);
|
||||
}
|
||||
return validate;
|
||||
};
|
||||
|
||||
/**
|
||||
* Find the AST node for a JSON pointer (e.g. `/aliases/0/name`). Returns the property node for
|
||||
* object members so the report points at the key, falling back to the closest existing parent.
|
||||
*
|
||||
* @param {any} node
|
||||
* @param {string} pointer
|
||||
*/
|
||||
const findNode = (node, pointer) => {
|
||||
const segments = pointer
|
||||
.split('/')
|
||||
.slice(1)
|
||||
.map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'));
|
||||
let current = node;
|
||||
let reportNode = node;
|
||||
for (const segment of segments) {
|
||||
if (current?.type === 'JSONObjectExpression') {
|
||||
const property = current.properties.find(
|
||||
(/** @type {any} */ prop) => (prop.key.value ?? prop.key.name) === segment,
|
||||
);
|
||||
if (!property) break;
|
||||
reportNode = property;
|
||||
current = property.value;
|
||||
} else if (current?.type === 'JSONArrayExpression') {
|
||||
const element = current.elements[Number(segment)];
|
||||
if (!element) break;
|
||||
reportNode = element;
|
||||
current = element;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { node: current, reportNode };
|
||||
};
|
||||
|
||||
/** @type {import('eslint').Rule.RuleModule} */
|
||||
const noInvalid = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Validate JSON files against a JSON Schema and require `$schema` to point at it',
|
||||
},
|
||||
schema: [
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
// Path to the schema, relative to the ESLint working directory (the repo root).
|
||||
schema: { type: 'string' },
|
||||
},
|
||||
required: ['schema'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
create(context) {
|
||||
return {
|
||||
/** @param {any} program */
|
||||
Program(program) {
|
||||
const root = program.body[0]?.expression;
|
||||
if (root?.type !== 'JSONObjectExpression') {
|
||||
context.report({ node: root ?? program, message: 'Root value must be an object.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const data = getStaticJSONValue(root);
|
||||
if (typeof data?.$schema !== 'string') {
|
||||
context.report({ node: root, message: 'Missing `$schema` field.' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate against the configured schema, not whatever `$schema` points at, so a file can't
|
||||
// opt out of validation by referencing a more permissive schema.
|
||||
const schemaPath = path.resolve(context.cwd, context.options[0].schema);
|
||||
const expectedRef = path
|
||||
.relative(path.dirname(context.filename), schemaPath)
|
||||
.split(path.sep)
|
||||
.join('/');
|
||||
if (path.resolve(path.dirname(context.filename), data.$schema) !== schemaPath) {
|
||||
context.report({
|
||||
node: findNode(root, '/$schema').reportNode,
|
||||
message: `\`$schema\` must be "${expectedRef}".`,
|
||||
});
|
||||
}
|
||||
|
||||
const validate = getValidator(schemaPath);
|
||||
if (validate(data)) return;
|
||||
|
||||
for (const error of validate.errors ?? []) {
|
||||
const { node, reportNode } = findNode(root, error.instancePath);
|
||||
const location = error.instancePath || '(root)';
|
||||
|
||||
if (error.keyword === 'additionalProperties' && node?.type === 'JSONObjectExpression') {
|
||||
const property = findNode(
|
||||
node,
|
||||
`/${error.params.additionalProperty.replaceAll('~', '~0').replaceAll('/', '~1')}`,
|
||||
).reportNode;
|
||||
context.report({
|
||||
node: property,
|
||||
message: `${location} has unexpected property "${error.params.additionalProperty}".`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const isContainer =
|
||||
reportNode.type === 'JSONObjectExpression' || reportNode.type === 'JSONArrayExpression';
|
||||
context.report({
|
||||
// Report objects and arrays at their opening bracket only, not their whole range.
|
||||
loc: isContainer ? reportNode.loc.start : reportNode.loc,
|
||||
message: `${location} ${error.message}.`,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default {
|
||||
meta: { name: 'json-schema' },
|
||||
rules: { 'no-invalid': noInvalid },
|
||||
};
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* Generates a conventional-commit PR title from the paths a pull request changes.
|
||||
*
|
||||
* Because merges in this repository are squashed, the PR title becomes the
|
||||
* commit message and the changelog entry. This script generates the whole title
|
||||
* for icon contributions and, for every other kind of PR, inserts or updates the
|
||||
* conventional-commit scope so `lint-pr-title` is satisfied.
|
||||
*
|
||||
* It follows the convention of `generateChangedIconsCommentMarkup.mts`: it reads
|
||||
* its input from the environment, prints the result to stdout and has no other
|
||||
* side effects. It only imports Node built-ins and the shared
|
||||
* `conventional-commit-types.json` (a native JSON import), so Node can still run
|
||||
* it natively as an `.mts` file without a `pnpm install` step.
|
||||
*
|
||||
* Env input (CLI wrapper at the bottom):
|
||||
* - `ADDED_FILES_FILE`: path to a newline-separated list of added files, or
|
||||
* - `ADDED_FILES`: a space-separated list of added files (handy for local runs).
|
||||
* - `CHANGED_FILES_FILE` / `CHANGED_FILES`: the same for all changed files
|
||||
* (added, modified, renamed and deleted).
|
||||
* - `CURRENT_TITLE`: the current PR title.
|
||||
*
|
||||
* Output: the new title on stdout, or nothing at all when no change is needed.
|
||||
*/
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// Single source of truth for the conventional-commit types, shared with
|
||||
// `lint-pr-title` (amannn/action-semantic-pull-request).
|
||||
import VALID_TYPES from '../.github/conventional-commit-types.json' with { type: 'json' };
|
||||
|
||||
// Default type used in prefix mode when the current title has no valid type.
|
||||
// The path reliably tells us the scope but nothing about whether a change is a
|
||||
// feat/fix/chore, so we fall back to the most neutral type.
|
||||
const DEFAULT_TYPE = 'chore';
|
||||
|
||||
// How many icon names to list in a generated title before summarising the rest.
|
||||
const MAX_NAMES = 3;
|
||||
|
||||
// How many package scopes to join with `|` before falling back to `packages`.
|
||||
const MAX_SCOPES = 3;
|
||||
const PACKAGES_SCOPE = 'packages';
|
||||
|
||||
/**
|
||||
* - `icon`: an added file *is* the subject, so the whole title is generated.
|
||||
* Changed (not added) icon files only provide a scope.
|
||||
* - `package`: a package in `packages/`, scoped by its `package.json` name.
|
||||
* - `repo`: any other area of the repository.
|
||||
*/
|
||||
type Kind = 'icon' | 'package' | 'repo';
|
||||
|
||||
type Rule = {
|
||||
pattern: RegExp;
|
||||
scope: string;
|
||||
kind: Kind;
|
||||
};
|
||||
|
||||
/**
|
||||
* Path -> scope rules. Each file is matched by the *first* rule in this list
|
||||
* that matches it, and scopes are listed in the order of this list, which keeps
|
||||
* the outcome deterministic. The `icons`, `lab`, `metadata`, `docs` and `site`
|
||||
* scopes mirror `.github/labeler.yml`; `packages/*` scopes mirror each
|
||||
* package's `package.json` name.
|
||||
*/
|
||||
const RULES: Rule[] = [
|
||||
{ pattern: /^icons\/[^/]+\.svg$/, scope: 'icons', kind: 'icon' },
|
||||
{ pattern: /^lab\/[^/]+\.svg$/, scope: 'lab', kind: 'icon' },
|
||||
{ pattern: /^packages\/lucide-react-native\//, scope: 'lucide-react-native', kind: 'package' },
|
||||
{ pattern: /^packages\/lucide-react\//, scope: 'lucide-react', kind: 'package' },
|
||||
{ pattern: /^packages\/lucide-preact\//, scope: 'lucide-preact', kind: 'package' },
|
||||
{ pattern: /^packages\/lucide-solid\//, scope: 'lucide-solid', kind: 'package' },
|
||||
{ pattern: /^packages\/lucide-static\//, scope: 'lucide-static', kind: 'package' },
|
||||
{ pattern: /^packages\/icons\//, scope: '@lucide/icons', kind: 'package' },
|
||||
{ pattern: /^packages\/vue\//, scope: '@lucide/vue', kind: 'package' },
|
||||
{ pattern: /^packages\/angular\//, scope: '@lucide/angular', kind: 'package' },
|
||||
{ pattern: /^packages\/svelte\//, scope: '@lucide/svelte', kind: 'package' },
|
||||
{ pattern: /^packages\/solid\//, scope: '@lucide/solid', kind: 'package' },
|
||||
{ pattern: /^packages\/astro\//, scope: '@lucide/astro', kind: 'package' },
|
||||
{ pattern: /^packages\/lab\//, scope: '@lucide/lab', kind: 'package' },
|
||||
{ pattern: /^packages\/shared\//, scope: '@lucide/shared', kind: 'package' },
|
||||
{ pattern: /^packages\/lucide\//, scope: 'lucide', kind: 'package' },
|
||||
{ pattern: /^(?:icons|categories)\/[^/]+\.json$/, scope: 'metadata', kind: 'repo' },
|
||||
{ pattern: /^docs\/.*\.md$/, scope: 'docs', kind: 'repo' },
|
||||
{ pattern: /^docs\//, scope: 'site', kind: 'repo' },
|
||||
];
|
||||
|
||||
/**
|
||||
* Every scope this script can produce. A title whose scope consists only of
|
||||
* these is owned by the script and may be updated; any other scope was chosen
|
||||
* by a person and is kept.
|
||||
*/
|
||||
const GENERATED_SCOPES = new Set([...RULES.map((rule) => rule.scope), PACKAGES_SCOPE]);
|
||||
|
||||
/**
|
||||
* Formats a list of icon names into the subject of a generated title, e.g.
|
||||
* `` `heart` icon ``, `` `heart`, `heart-off` icons `` or
|
||||
* `` `a`, `b`, `c` and 2 more icons ``.
|
||||
*/
|
||||
const formatIconNames = (names: string[]): string => {
|
||||
const quoted = names.map((name) => `\`${name}\``);
|
||||
const noun = names.length === 1 ? 'icon' : 'icons';
|
||||
|
||||
if (quoted.length <= MAX_NAMES) {
|
||||
return `${quoted.join(', ')} ${noun}`;
|
||||
}
|
||||
|
||||
const shown = quoted.slice(0, MAX_NAMES).join(', ');
|
||||
const remaining = quoted.length - MAX_NAMES;
|
||||
return `${shown} and ${remaining} more ${noun}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds the whole title for an icon rule from the added files matching it.
|
||||
* Names are deduped by basename (an icon PR adds both `heart.svg` and
|
||||
* `heart.json`) and kept in the order they first appear.
|
||||
*/
|
||||
const generateTitle = (scope: string, matchedFiles: string[]): string => {
|
||||
const names = matchedFiles
|
||||
.map((file) => file.replace(/^.*\//, '').replace(/\.[^.]+$/, ''))
|
||||
.filter((name, index, all) => all.indexOf(name) === index);
|
||||
|
||||
return `feat(${scope}): added ${formatIconNames(names)}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Derives the scope from the changed files. Package scopes win over icon
|
||||
* scopes, which win over any other scope (an icon change usually touches its
|
||||
* metadata too). Multiple scopes are joined with `|`, e.g.
|
||||
* `lucide-react|@lucide/vue`, and more than `MAX_SCOPES` packages are
|
||||
* summarised as `packages`.
|
||||
*/
|
||||
const resolveScope = (changedFiles: string[]): string | null => {
|
||||
const matchedRules = new Set(
|
||||
changedFiles
|
||||
.map((file) => RULES.find((rule) => rule.pattern.test(file)))
|
||||
.filter((rule) => rule != null),
|
||||
);
|
||||
const scopesOf = (kind: Kind) =>
|
||||
RULES.filter((rule) => rule.kind === kind && matchedRules.has(rule)).map((rule) => rule.scope);
|
||||
|
||||
const packageScopes = scopesOf('package');
|
||||
if (packageScopes.length > MAX_SCOPES) return PACKAGES_SCOPE;
|
||||
if (packageScopes.length > 0) return packageScopes.join('|');
|
||||
|
||||
for (const kind of ['icon', 'repo'] as const) {
|
||||
const scopes = scopesOf(kind);
|
||||
if (scopes.length > 0) return scopes.join('|');
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const isGeneratedScope = (scope: string): boolean =>
|
||||
scope.split('|').every((part) => GENERATED_SCOPES.has(part.trim()));
|
||||
|
||||
/**
|
||||
* Rewrites the current title around the resolved scope: the contributor's own
|
||||
* type and subject are preserved and the title is normalised to
|
||||
* `type(scope)!: subject`. A scope chosen by a person is kept; a missing scope or
|
||||
* one this script generated earlier is replaced by `scope`. When the title has
|
||||
* no valid type, `DEFAULT_TYPE` is used. When there is no subject or no scope to
|
||||
* work with, `null` is returned so the title is left untouched.
|
||||
*/
|
||||
const prefixTitle = (scope: string | null, currentTitle: string): string | null => {
|
||||
const match = currentTitle.match(/^\s*(\w+)\s*(?:\(([^)]*)\))?\s*(!?)\s*:\s*(.*)$/);
|
||||
const type = match?.[1].toLowerCase();
|
||||
|
||||
if (match && type != null && VALID_TYPES.includes(type)) {
|
||||
const [, , currentScope = '', breaking, subject] = match;
|
||||
if (subject.trim() === '') return null;
|
||||
|
||||
const keepScope =
|
||||
currentScope.trim() !== '' && (scope == null || !isGeneratedScope(currentScope));
|
||||
const newScope = keepScope ? currentScope.trim() : scope;
|
||||
if (newScope == null) return null;
|
||||
|
||||
return `${type}(${newScope})${breaking}: ${subject.trim()}`;
|
||||
}
|
||||
|
||||
const subject = currentTitle.trim();
|
||||
if (scope == null || subject === '') return null;
|
||||
return `${DEFAULT_TYPE}(${scope}): ${subject}`;
|
||||
};
|
||||
|
||||
type PullRequestFiles = {
|
||||
addedFiles: string[];
|
||||
changedFiles: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Pure title function: given the added and changed files and the current
|
||||
* title, returns the new title, or `null` when nothing should change (no
|
||||
* matching rule, no subject to work with, or the title is already correct).
|
||||
*/
|
||||
export const generatePullRequestTitle = (
|
||||
{ addedFiles, changedFiles }: PullRequestFiles,
|
||||
currentTitle: string,
|
||||
): string | null => {
|
||||
const iconRule = RULES.find(
|
||||
(rule) => rule.kind === 'icon' && addedFiles.some((file) => rule.pattern.test(file)),
|
||||
);
|
||||
|
||||
// Added files are changed files too, also when only `ADDED_FILES` is given.
|
||||
const allChangedFiles = [...new Set([...addedFiles, ...changedFiles])];
|
||||
|
||||
const newTitle =
|
||||
iconRule != null
|
||||
? generateTitle(
|
||||
iconRule.scope,
|
||||
addedFiles.filter((file) => iconRule.pattern.test(file)),
|
||||
)
|
||||
: prefixTitle(resolveScope(allChangedFiles), currentTitle);
|
||||
|
||||
if (newTitle == null || newTitle === currentTitle) return null;
|
||||
|
||||
return newTitle;
|
||||
};
|
||||
|
||||
// --- CLI wrapper -----------------------------------------------------------
|
||||
// Only runs when executed directly, keeping the function above unit-testable.
|
||||
|
||||
const readFileList = (filePath: string | undefined, list: string | undefined): string[] => {
|
||||
const raw = filePath != null && filePath !== '' ? readFileSync(filePath, 'utf-8') : (list ?? '');
|
||||
|
||||
return raw
|
||||
.split(/\s+/)
|
||||
.map((file) => file.trim())
|
||||
.filter((file) => file !== '');
|
||||
};
|
||||
|
||||
if (import.meta.main) {
|
||||
const { ADDED_FILES_FILE, ADDED_FILES, CHANGED_FILES_FILE, CHANGED_FILES, CURRENT_TITLE } =
|
||||
process.env;
|
||||
|
||||
const newTitle = generatePullRequestTitle(
|
||||
{
|
||||
addedFiles: readFileList(ADDED_FILES_FILE, ADDED_FILES),
|
||||
changedFiles: readFileList(CHANGED_FILES_FILE, CHANGED_FILES),
|
||||
},
|
||||
CURRENT_TITLE ?? '',
|
||||
);
|
||||
|
||||
if (newTitle != null) {
|
||||
process.stdout.write(newTitle);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
|
||||
import { generatePullRequestTitle } from './generatePullRequestTitle.mts';
|
||||
|
||||
const added = (addedFiles: string[], title: string) =>
|
||||
generatePullRequestTitle({ addedFiles, changedFiles: [] }, title);
|
||||
|
||||
const changed = (changedFiles: string[], title: string) =>
|
||||
generatePullRequestTitle({ addedFiles: [], changedFiles }, title);
|
||||
|
||||
describe('generatePullRequestTitle', () => {
|
||||
describe('icon titles', () => {
|
||||
it('generates a title for a single icon and dedupes svg and json', () => {
|
||||
assert.equal(
|
||||
added(['icons/heart.svg', 'icons/heart.json'], 'add heart'),
|
||||
'feat(icons): added `heart` icon',
|
||||
);
|
||||
});
|
||||
|
||||
it('lists multiple icons', () => {
|
||||
assert.equal(
|
||||
added(['icons/heart.svg', 'icons/heart-off.svg'], 'icons'),
|
||||
'feat(icons): added `heart`, `heart-off` icons',
|
||||
);
|
||||
});
|
||||
|
||||
it('summarises many icons', () => {
|
||||
assert.equal(
|
||||
added(['icons/a.svg', 'icons/b.svg', 'icons/c.svg', 'icons/d.svg', 'icons/e.svg'], 'x'),
|
||||
'feat(icons): added `a`, `b`, `c` and 2 more icons',
|
||||
);
|
||||
});
|
||||
|
||||
it('generates a title for lab icons', () => {
|
||||
assert.equal(added(['lab/ghost.svg'], 'x'), 'feat(lab): added `ghost` icon');
|
||||
});
|
||||
|
||||
it('returns null when the title is already correct', () => {
|
||||
assert.equal(added(['icons/heart.svg'], 'feat(icons): added `heart` icon'), null);
|
||||
});
|
||||
|
||||
it('ignores other changed files when an icon is added', () => {
|
||||
assert.equal(
|
||||
generatePullRequestTitle(
|
||||
{ addedFiles: ['icons/heart.svg'], changedFiles: ['docs/guide.md'] },
|
||||
'x',
|
||||
),
|
||||
'feat(icons): added `heart` icon',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scope resolution', () => {
|
||||
it('uses the package name as scope', () => {
|
||||
assert.equal(
|
||||
changed(['packages/lucide-react/src/a.ts'], 'fix: crash'),
|
||||
'fix(lucide-react): crash',
|
||||
);
|
||||
});
|
||||
|
||||
it('joins multiple packages with a pipe', () => {
|
||||
assert.equal(
|
||||
changed(['packages/vue/src/b.ts', 'packages/lucide-react/src/a.ts'], 'chore: Fix export'),
|
||||
'chore(lucide-react|@lucide/vue): Fix export',
|
||||
);
|
||||
});
|
||||
|
||||
it('summarises more than three packages as `packages`', () => {
|
||||
assert.equal(
|
||||
changed(
|
||||
[
|
||||
'packages/lucide-react/a.ts',
|
||||
'packages/vue/a.ts',
|
||||
'packages/svelte/a.ts',
|
||||
'packages/angular/a.ts',
|
||||
],
|
||||
'refactor: shared types',
|
||||
),
|
||||
'refactor(packages): shared types',
|
||||
);
|
||||
});
|
||||
|
||||
it('prefers packages over docs', () => {
|
||||
assert.equal(
|
||||
changed(['docs/guide/react.md', 'packages/lucide-react/src/a.ts'], 'feat: new prop'),
|
||||
'feat(lucide-react): new prop',
|
||||
);
|
||||
});
|
||||
|
||||
it('joins docs and site scopes', () => {
|
||||
assert.equal(
|
||||
changed(['docs/guide/a.md', 'docs/.vitepress/theme/b.vue'], 'docs: update'),
|
||||
'docs(docs|site): update',
|
||||
);
|
||||
});
|
||||
|
||||
it('uses `metadata` for icon and category json files', () => {
|
||||
assert.equal(changed(['icons/heart.json'], 'fix: tags'), 'fix(metadata): tags');
|
||||
assert.equal(changed(['categories/shapes.json'], 'fix: category'), 'fix(metadata): category');
|
||||
});
|
||||
|
||||
it('prefers icons over metadata for changed icons', () => {
|
||||
assert.equal(
|
||||
changed(['icons/heart.svg', 'icons/heart.json'], 'fix: heart'),
|
||||
'fix(icons): heart',
|
||||
);
|
||||
});
|
||||
|
||||
it('supports @lucide/solid', () => {
|
||||
assert.equal(changed(['packages/solid/src/a.ts'], 'feat: x'), 'feat(@lucide/solid): x');
|
||||
});
|
||||
|
||||
it('does not match lucide-react for lucide-react-native files', () => {
|
||||
assert.equal(
|
||||
changed(['packages/lucide-react-native/src/a.ts'], 'fix: x'),
|
||||
'fix(lucide-react-native): x',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null when no rule matches', () => {
|
||||
assert.equal(changed(['README.md'], 'chore: readme'), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('prefix titles', () => {
|
||||
const files = ['packages/lucide-react/src/a.ts'];
|
||||
|
||||
it('keeps a custom scope', () => {
|
||||
assert.equal(changed(files, 'fix(react): crash'), null);
|
||||
});
|
||||
|
||||
it('extends a generated scope', () => {
|
||||
assert.equal(
|
||||
changed([...files, 'packages/vue/src/a.ts'], 'fix(lucide-react): crash'),
|
||||
'fix(lucide-react|@lucide/vue): crash',
|
||||
);
|
||||
});
|
||||
|
||||
it('normalises the type casing', () => {
|
||||
assert.equal(changed(files, 'Fix: crash'), 'fix(lucide-react): crash');
|
||||
});
|
||||
|
||||
it('normalises whitespace and keeps a custom scope', () => {
|
||||
assert.equal(changed(files, 'feat (react): x'), 'feat(react): x');
|
||||
});
|
||||
|
||||
it('keeps the breaking-change marker', () => {
|
||||
assert.equal(changed(files, 'feat!: drop old api'), 'feat(lucide-react)!: drop old api');
|
||||
});
|
||||
|
||||
it('returns null for an empty subject', () => {
|
||||
assert.equal(changed(files, 'fix:'), null);
|
||||
});
|
||||
|
||||
it('falls back to the default type', () => {
|
||||
assert.equal(changed(files, 'Fix crash'), 'chore(lucide-react): Fix crash');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Checks formatting with Prettier and reports every unformatted range as a GitHub Actions
|
||||
* annotation (`::error file=…,line=…`), so it shows up inline in the PR diff.
|
||||
*
|
||||
* `prettier --check` only reports file names, so this formats each listed file in memory and
|
||||
* diffs it against the original to find the exact lines.
|
||||
*/
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import process from 'process';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { createRequire } from 'module';
|
||||
import * as prettier from 'prettier';
|
||||
|
||||
const PATTERNS = ['**/*.{js,mjs,ts,jsx,tsx,html,css,scss,json,yml,yaml}', 'icons/*.svg'];
|
||||
|
||||
const prettierBin = createRequire(import.meta.url).resolve('prettier/bin/prettier.cjs');
|
||||
|
||||
const listDifferent = spawnSync(
|
||||
process.execPath,
|
||||
[prettierBin, '--list-different', '--no-color', ...PATTERNS],
|
||||
{ encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
|
||||
/** Escape data for a workflow command, see https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts */
|
||||
const escapeData = (value: string) =>
|
||||
value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
|
||||
const escapeProperty = (value: string) =>
|
||||
escapeData(value).replaceAll(':', '%3A').replaceAll(',', '%2C');
|
||||
|
||||
let problems = 0;
|
||||
|
||||
// Exit code 2 means Prettier could not process a file, e.g. because of a syntax error.
|
||||
if (listDifferent.status !== 0 && listDifferent.status !== 1) {
|
||||
console.log('::group::Prettier errors');
|
||||
console.log(listDifferent.stderr);
|
||||
console.log('::endgroup::');
|
||||
|
||||
const syntaxError = /^\[error\] (.+?): (\w*Error: .+) \((\d+):(\d+)\)$/;
|
||||
for (const line of listDifferent.stderr.split('\n')) {
|
||||
const match = line.match(syntaxError);
|
||||
if (!match) continue;
|
||||
const [, file, message, errorLine, column] = match;
|
||||
console.log(
|
||||
`::error file=${escapeProperty(file)},line=${errorLine},col=${column},title=Prettier::${escapeData(message)}`,
|
||||
);
|
||||
problems++;
|
||||
}
|
||||
|
||||
if (problems === 0) {
|
||||
console.log(
|
||||
`::error title=Prettier::${escapeData(listDifferent.stderr.trim() || 'Prettier failed.')}`,
|
||||
);
|
||||
problems++;
|
||||
}
|
||||
}
|
||||
|
||||
const files = listDifferent.stdout.split('\n').filter(Boolean);
|
||||
|
||||
if (files.length === 0 && problems === 0) {
|
||||
console.log('All matched files use Prettier code style!');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-format-'));
|
||||
const hunkHeader = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;
|
||||
|
||||
for (const file of files) {
|
||||
const source = fs.readFileSync(file, 'utf-8');
|
||||
const options = await prettier.resolveConfig(file);
|
||||
const formatted = await prettier.format(source, { ...options, filepath: file });
|
||||
|
||||
const formattedFile = path.join(tmpDir, 'formatted');
|
||||
fs.writeFileSync(formattedFile, formatted);
|
||||
|
||||
const { stdout: diff } = spawnSync(
|
||||
'git',
|
||||
['diff', '--no-index', '--no-color', '-U0', '--', file, formattedFile],
|
||||
{ encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
|
||||
console.log(`::group::${file}`);
|
||||
console.log(diff);
|
||||
console.log('::endgroup::');
|
||||
|
||||
const lines = diff.split('\n');
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const match = lines[index].match(hunkHeader);
|
||||
if (!match) continue;
|
||||
|
||||
const start = Number(match[1]);
|
||||
const count = match[2] === undefined ? 1 : Number(match[2]);
|
||||
|
||||
const expected: string[] = [];
|
||||
while (index + 1 < lines.length && /^[-+\\ ]/.test(lines[index + 1])) {
|
||||
index++;
|
||||
if (lines[index].startsWith('+')) expected.push(lines[index].slice(1));
|
||||
}
|
||||
|
||||
// A pure insertion (count 0) happens after `start`, so point at that line.
|
||||
const line = Math.max(start, 1);
|
||||
const endLine = count === 0 ? line : start + count - 1;
|
||||
|
||||
const message =
|
||||
expected.length > 0
|
||||
? `Code is not formatted with Prettier. Expected:\n${expected.join('\n')}`
|
||||
: 'Code is not formatted with Prettier. Remove these lines.';
|
||||
|
||||
console.log(
|
||||
`::error file=${escapeProperty(file)},line=${line},endLine=${endLine},title=Prettier::${escapeData(message)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
|
||||
if (files.length > 0) {
|
||||
console.log(
|
||||
`\n${files.length} file(s) not formatted with Prettier. Run \`pnpm lint:format-fix\` and \`pnpm lint:icons-fix\` to fix.`,
|
||||
);
|
||||
}
|
||||
process.exit(1);
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Spell checks icon and category metadata with cspell and reports every unknown word as a GitHub
|
||||
* Actions annotation (`::error file=…,line=…`), so it shows up inline in the PR diff.
|
||||
*
|
||||
* Words that are correct but unknown to cspell go in `.cspell/custom-words.txt`.
|
||||
*/
|
||||
import process from 'process';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const PATTERNS = ['icons/*.json', 'categories/*.json'];
|
||||
|
||||
// cspell only exports its bin for `import`, so resolve it the ESM way.
|
||||
const cspellBin = fileURLToPath(import.meta.resolve('cspell/bin.mjs'));
|
||||
|
||||
const cspell = spawnSync(
|
||||
process.execPath,
|
||||
[cspellBin, '--no-color', '--no-progress', '--no-summary', ...PATTERNS],
|
||||
{ encoding: 'utf-8', maxBuffer: 64 * 1024 * 1024 },
|
||||
);
|
||||
|
||||
/** Escape data for a workflow command, see https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts */
|
||||
const escapeData = (value: string) =>
|
||||
value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A');
|
||||
const escapeProperty = (value: string) =>
|
||||
escapeData(value).replaceAll(':', '%3A').replaceAll(',', '%2C');
|
||||
|
||||
const issue = /^(.+?):(\d+):(\d+) - Unknown word \((.+?)\)(?: fix: \((.+?)\))?/;
|
||||
let problems = 0;
|
||||
|
||||
for (const line of cspell.stdout.split('\n')) {
|
||||
const match = line.match(issue);
|
||||
if (!match) continue;
|
||||
|
||||
const [, file, lineNumber, column, word, fix] = match;
|
||||
const suggestion = fix ? ` Did you mean "${fix}"?` : '';
|
||||
const message = `Unknown word "${word}".${suggestion} Fix the typo or add the word to .cspell/custom-words.txt.`;
|
||||
|
||||
console.log(line);
|
||||
console.log(
|
||||
`::error file=${escapeProperty(file)},line=${lineNumber},col=${column},endColumn=${Number(column) + word.length},title=cspell::${escapeData(message)}`,
|
||||
);
|
||||
problems++;
|
||||
}
|
||||
|
||||
if (cspell.status !== 0 && problems === 0) {
|
||||
process.stderr.write(cspell.stderr);
|
||||
console.log(`::error title=cspell::${escapeData(cspell.stderr.trim() || 'cspell failed.')}`);
|
||||
process.exit(cspell.status ?? 1);
|
||||
}
|
||||
|
||||
if (problems > 0) {
|
||||
console.log(`\n${problems} spelling issue(s) found.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('No spelling issues found.');
|
||||
Reference in New Issue
Block a user