From fd753b7f6b05555897af9e9f5c99f8739f70e0d6 Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Sat, 5 Dec 2026 05:44:50 +0700 Subject: [PATCH] fix(github): fix issue auto-labeling, templates, and add scripts CI Co-Authored-By: Antigravity --- .github/ISSUE_TEMPLATE/request_feature.yml | 2 +- .github/scripts/auto-label-issue.cjs | 284 +++++++++++ .github/scripts/auto-label-issue.test.cjs | 445 ++++++++++++++++++ .github/scripts/blank_report_issue.yml | 4 +- .github/scripts/check-github.cjs | 137 ++++++ .github/scripts/generate-issue-index.cjs | 48 +- .github/scripts/generate-issue-index.test.cjs | 108 +++++ .../generate-issue-template-options.cjs | 27 +- .github/scripts/issue-parsing.cjs | 210 +++++++++ .github/scripts/validate-github-yaml.py | 107 +++++ .github/workflows/generate-issue-index.yml | 1 + .github/workflows/github-scripts-check.yml | 135 ++++++ .github/workflows/issue_auto_label.yml | 120 +++-- AGENTS.md | 5 +- CODING_STANDARDS.md | 5 + package.json | 8 +- 16 files changed, 1528 insertions(+), 118 deletions(-) create mode 100644 .github/scripts/auto-label-issue.cjs create mode 100644 .github/scripts/auto-label-issue.test.cjs create mode 100644 .github/scripts/check-github.cjs create mode 100644 .github/scripts/generate-issue-index.test.cjs create mode 100644 .github/scripts/issue-parsing.cjs create mode 100644 .github/scripts/validate-github-yaml.py create mode 100644 .github/workflows/github-scripts-check.yml diff --git a/.github/ISSUE_TEMPLATE/request_feature.yml b/.github/ISSUE_TEMPLATE/request_feature.yml index 1437cce4f1..a0303b2f25 100644 --- a/.github/ISSUE_TEMPLATE/request_feature.yml +++ b/.github/ISSUE_TEMPLATE/request_feature.yml @@ -33,7 +33,7 @@ body: required: true - label: I understand that app-specific features should be requested in the [app repository](https://github.com/LNReader/lnreader/issues/new/choose). required: true - - label: I have updated the app to the latest version **[1.1.19](https://github.com/LNReader/lnreader/releases/latest)**. + - label: I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**. required: true - label: I have provided all requested information in this form. required: true diff --git a/.github/scripts/auto-label-issue.cjs b/.github/scripts/auto-label-issue.cjs new file mode 100644 index 0000000000..ad453a4d55 --- /dev/null +++ b/.github/scripts/auto-label-issue.cjs @@ -0,0 +1,284 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { + VALID_SEVERITIES, + comparisonValue, + extractSection, + matchPluginEntries, + nonEmptySectionLines, +} = require('./issue-parsing.cjs'); + +const MAX_LABEL_LENGTH = 50; + +const LANGUAGE_ALIASES = new Map([ + // Arabic + ['arabic', 'arabic'], + ['ar', 'arabic'], + ['العربية', 'arabic'], + ['عربي', 'arabic'], + // Bengali + ['bengali', 'bengali'], + ['bangla', 'bengali'], + ['bn', 'bengali'], + ['বাংলা', 'bengali'], + // Burmese + ['burmese', 'burmese'], + ['my', 'burmese'], + ['မြန်မာ', 'burmese'], + // Chinese + ['chinese', 'chinese'], + ['zh', 'chinese'], + ['zh-cn', 'chinese'], + ['zh-tw', 'chinese'], + ['cn', 'chinese'], + ['中文', 'chinese'], + ['汉语', 'chinese'], + ['漢語', 'chinese'], + ['简体中文', 'chinese'], + ['繁體中文', 'chinese'], + // Czech + ['czech', 'czech'], + ['cs', 'czech'], + ['čeština', 'czech'], + ['cestina', 'czech'], + // Dutch + ['dutch', 'dutch'], + ['nl', 'dutch'], + ['nederlands', 'dutch'], + // Filipino / Tagalog + ['filipino', 'filipino'], + ['tagalog', 'filipino'], + ['tl', 'filipino'], + ['fil', 'filipino'], + // French + ['french', 'french'], + ['fr', 'french'], + ['français', 'french'], + ['francais', 'french'], + // German + ['german', 'german'], + ['de', 'german'], + ['deutsch', 'german'], + // Greek + ['greek', 'greek'], + ['el', 'greek'], + ['ελληνικά', 'greek'], + ['ellinika', 'greek'], + // Hebrew + ['hebrew', 'hebrew'], + ['he', 'hebrew'], + ['עברית', 'hebrew'], + // Hindi + ['hindi', 'hindi'], + ['hi', 'hindi'], + ['हिन्दी', 'hindi'], + ['हिंदी', 'hindi'], + // Indonesian + ['indonesian', 'indonesian'], + ['id', 'indonesian'], + ['bahasa indonesia', 'indonesian'], + ['indo', 'indonesian'], + // Italian + ['italian', 'italian'], + ['it', 'italian'], + ['italiano', 'italian'], + // Japanese + ['japanese', 'japanese'], + ['ja', 'japanese'], + ['jp', 'japanese'], + ['日本語', 'japanese'], + // Korean + ['korean', 'korean'], + ['ko', 'korean'], + ['kr', 'korean'], + ['한국어', 'korean'], + ['조선말', 'korean'], + // Malay + ['malay', 'malay'], + ['ms', 'malay'], + ['bahasa melayu', 'malay'], + // Persian / Farsi + ['persian', 'persian'], + ['farsi', 'persian'], + ['fa', 'persian'], + ['فارسی', 'persian'], + // Polish + ['polish', 'polish'], + ['pl', 'polish'], + ['polski', 'polish'], + // Portuguese + ['portuguese', 'portuguese'], + ['pt', 'portuguese'], + ['pt-br', 'portuguese'], + ['português', 'portuguese'], + ['portugues', 'portuguese'], + // Romanian + ['romanian', 'romanian'], + ['ro', 'romanian'], + ['română', 'romanian'], + ['romana', 'romanian'], + // Russian + ['russian', 'russian'], + ['ru', 'russian'], + ['русский', 'russian'], + // Spanish + ['spanish', 'spanish'], + ['es', 'spanish'], + ['español', 'spanish'], + ['espanol', 'spanish'], + // Thai + ['thai', 'thai'], + ['th', 'thai'], + ['ไทย', 'thai'], + ['ภาษาไทย', 'thai'], + // Turkish + ['turkish', 'turkish'], + ['tr', 'turkish'], + ['türkçe', 'turkish'], + ['turkce', 'turkish'], + // Ukrainian + ['ukrainian', 'ukrainian'], + ['uk', 'ukrainian'], + ['ua', 'ukrainian'], + ['українська', 'ukrainian'], + // Vietnamese + ['vietnamese', 'vietnamese'], + ['vi', 'vietnamese'], + ['vn', 'vietnamese'], + ['tiếng việt', 'vietnamese'], + ['tieng viet', 'vietnamese'], +]); + +const MANAGED_LANGUAGE_LABELS = new Set( + [...LANGUAGE_ALIASES.values()].map(lang => `language: ${lang}`), +); + +function resolveLanguageAlias(rawLanguage) { + if (!rawLanguage) return null; + const direct = LANGUAGE_ALIASES.get(rawLanguage); + if (direct) return direct; + const firstSegment = comparisonValue(rawLanguage.split(/[,/(]/)[0]); + return firstSegment ? LANGUAGE_ALIASES.get(firstSegment) || null : null; +} + +function formatPluginLabel(displayKey, id) { + const idx = displayKey.indexOf(': '); + const rawName = idx >= 0 ? displayKey.slice(idx + 2) : displayKey; + const name = comparisonValue(rawName); + const cleanId = comparisonValue(id); + if (!name || !cleanId) return null; + const full = `plugin: ${name}[${cleanId}]`; + if (full.length <= MAX_LABEL_LENGTH) return full; + + const suffix = `[${cleanId}]`; + const maxNameLen = MAX_LABEL_LENGTH - 'plugin: '.length - suffix.length; + if (maxNameLen >= 4) { + const truncated = name.slice(0, maxNameLen - 1).trimEnd(); + if (truncated) return `plugin: ${truncated}…${suffix}`; + } + const maxIdLen = MAX_LABEL_LENGTH - 'plugin: []'.length; + return `plugin: [${cleanId.slice(0, maxIdLen)}]`; +} + +function matchPluginLabels(lines, pluginKeys) { + return matchPluginEntries(lines, pluginKeys) + .map(entry => formatPluginLabel(entry.displayKey, entry.id)) + .filter(Boolean); +} + +function computeLabelPlan({ body, existingLabels = [], pluginKeys = {} }) { + const rawExisting = ( + Array.isArray(existingLabels) ? existingLabels : [] + ).filter(label => typeof label === 'string'); + const normalizedExisting = new Set(rawExisting.map(comparisonValue)); + + const desired = []; + const seenDesired = new Set(); + const addLabel = label => { + const normalized = comparisonValue(label); + if (!normalized || seenDesired.has(normalized)) return; + seenDesired.add(normalized); + desired.push(label); + }; + + const pluginSection = extractSection(body, 'Plugin'); + const manageBug = normalizedExisting.has('bug') && pluginSection.present; + if (manageBug) { + const severityLines = nonEmptySectionLines( + extractSection(body, 'Severity'), + ); + const rawSeverity = + severityLines.length > 0 ? comparisonValue(severityLines[0]) : ''; + const severity = VALID_SEVERITIES.has(rawSeverity) ? rawSeverity : 'other'; + addLabel(`severity: ${severity}`); + + for (const pluginLabel of matchPluginLabels( + nonEmptySectionLines(pluginSection), + pluginKeys, + )) { + addLabel(pluginLabel); + } + } + + const languageSection = extractSection(body, 'Language'); + const manageLanguage = + normalizedExisting.has('plugin request') && languageSection.present; + if (manageLanguage) { + const languageLines = nonEmptySectionLines(languageSection); + const rawLanguage = + languageLines.length > 0 ? comparisonValue(languageLines[0]) : ''; + const canonical = resolveLanguageAlias(rawLanguage); + if (canonical) { + addLabel(`language: ${canonical}`); + } + } + + const isManagedLabel = normalized => { + if ( + manageBug && + (normalized === 'plugin:' || + normalized.startsWith('plugin: ') || + normalized.startsWith('severity: ')) + ) { + return true; + } + return manageLanguage && MANAGED_LANGUAGE_LABELS.has(normalized); + }; + + const add = desired.filter( + label => !normalizedExisting.has(comparisonValue(label)), + ); + + const remove = []; + const seenRemove = new Set(); + for (const label of rawExisting) { + const normalized = comparisonValue(label); + if ( + !normalized || + !isManagedLabel(normalized) || + seenDesired.has(normalized) || + seenRemove.has(normalized) + ) { + continue; + } + seenRemove.add(normalized); + remove.push(label); + } + + return { desired, add, remove }; +} + +if (require.main === module) { + const keysPath = path.join(__dirname, 'keys.json'); + const pluginKeys = JSON.parse(fs.readFileSync(keysPath, 'utf8')); + const body = process.env.ISSUE_BODY || ''; + const existingLabels = JSON.parse(process.env.ISSUE_LABELS || '[]'); + const plan = computeLabelPlan({ body, existingLabels, pluginKeys }); + process.stdout.write( + `${JSON.stringify({ add: plan.add, remove: plan.remove })}\n`, + ); +} + +module.exports = { computeLabelPlan }; diff --git a/.github/scripts/auto-label-issue.test.cjs b/.github/scripts/auto-label-issue.test.cjs new file mode 100644 index 0000000000..4b287134db --- /dev/null +++ b/.github/scripts/auto-label-issue.test.cjs @@ -0,0 +1,445 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync } = require('node:child_process'); + +const { computeLabelPlan } = require('./auto-label-issue.cjs'); +const { + renderIssueTemplate, +} = require('./generate-issue-template-options.cjs'); + +const pluginKeys = JSON.parse( + fs.readFileSync(path.join(__dirname, 'keys.json'), 'utf8'), +); + +test('bug issue with single English plugin and valid severity', () => { + const body = [ + '### Plugin', + '', + 'English: Novel Fire', + '', + '### Severity', + '', + "Can't Load Novels", + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + ["severity: can't load novels", 'plugin: novel fire[novelfire]'], + ); +}); + +test('bug issue with comma-containing Chinese and Korean plugin keys', () => { + const body = [ + '### Plugin', + '', + '中文, 汉语, 漢語: 69书吧, 조선말, 한국어: Agitoon', + '', + '### Severity', + '', + 'Wrong Formatting', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + [ + 'severity: wrong formatting', + 'plugin: 69书吧[69shu]', + 'plugin: agitoon[agit.xyz]', + ], + ); +}); + +test('bug issue with Arabic plugin with or without leading LRM directional control', () => { + const withLrm = [ + '### Plugin', + '', + '\u200eالعربية: ArNovel', + '', + '### Severity', + '', + 'Missing Chapter', + ].join('\n'); + + const withoutLrm = [ + '### Plugin', + '', + 'العربية: ArNovel', + '', + '### Severity', + '', + 'Missing Chapter', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body: withLrm, existingLabels: ['bug'], pluginKeys }) + .desired, + ['severity: missing chapter', 'plugin: arnovel[arnovel]'], + ); + assert.deepEqual( + computeLabelPlan({ + body: withoutLrm, + existingLabels: ['bug'], + pluginKeys, + }).desired, + ['severity: missing chapter', 'plugin: arnovel[arnovel]'], + ); +}); + +test('bug issue with colon inside plugin name preserves colon after language prefix', () => { + const body = [ + '### Plugin', + '', + 'English: Re:Library', + '', + '### Severity', + '', + 'Wrong Content', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + ['severity: wrong content', 'plugin: re:library[relib]'], + ); +}); + +test('bug issue with unmatched plugin or _No response_ never emits bare plugin: label', () => { + const staleBody = [ + '### Plugin', + '', + 'English: NonExistentPlugin', + '', + '### Severity', + '', + 'Unknown Severity', + ].join('\n'); + + const noResponseBody = [ + '### Plugin', + '', + '_No response_', + '', + '### Severity', + '', + '_No response_', + ].join('\n'); + + for (const body of [staleBody, noResponseBody]) { + const labels = computeLabelPlan({ + body, + existingLabels: ['bug'], + pluginKeys, + }).desired; + assert.deepEqual(labels, ['severity: other']); + assert.ok(!labels.some(label => label.trim() === 'plugin:')); + } +}); + +test('bug issue handles CRLF line endings and extra blank lines', () => { + const body = [ + '### Plugin', + '', + '', + ' English: NovelBuddy ', + '', + '### Severity', + '', + '', + ' Domain Changed ', + '', + ].join('\r\n'); + + assert.deepEqual( + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, + ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + ); +}); + +test('plugin request issue maps non-English language names and native aliases', () => { + const cases = [ + ['Arabic', 'language: arabic'], + ['Vietnamese', 'language: vietnamese'], + ['Tiếng Việt', 'language: vietnamese'], + ['中文', 'language: chinese'], + ]; + + for (const [languageInput, expectedLabel] of cases) { + const body = ['### Language', '', languageInput].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }).desired, + [expectedLabel], + ); + } +}); + +test('plugin request issue with English, Multi, empty, _No response_, or unrecognized language emits []', () => { + for (const languageInput of [ + 'English', + 'en', + 'Multi', + '', + '_No response_', + 'Please add support for this website soon', + ]) { + const body = ['### Language', '', languageInput].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }).desired, + [], + ); + } +}); + +test('unrelated issue emits []', () => { + const body = [ + '### Feature Description', + '', + 'Add dark mode', + '', + '### Language', + '', + 'English', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['feature request'], + pluginKeys, + }).desired, + [], + ); +}); + +test('all plugin labels in keys.json stay within GitHub 50-character limit and preserve [id]', () => { + for (const [displayKey, id] of Object.entries(pluginKeys)) { + const body = [ + '### Plugin', + '', + displayKey, + '', + '### Severity', + '', + 'Other', + ].join('\n'); + + const labels = computeLabelPlan({ + body, + existingLabels: ['bug'], + pluginKeys, + }).desired; + const pluginLabels = labels.filter(label => label.startsWith('plugin:')); + assert.equal(pluginLabels.length, 1, `Expected 1 label for ${displayKey}`); + const [pluginLabel] = pluginLabels; + assert.ok( + pluginLabel.length <= 50, + `Label too long (${pluginLabel.length}): ${pluginLabel}`, + ); + assert.match(pluginLabel, /^plugin: .*\[[^\]]+\]$/); + assert.ok(pluginLabel.includes(`[${id.toLowerCase()}]`)); + assert.notEqual(pluginLabel.trim(), 'plugin:'); + } + + const longestBody = [ + '### Plugin', + '', + "English: TaxingCorn117's Translations", + '', + '### Severity', + '', + 'Other', + ].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body: longestBody, + existingLabels: ['bug'], + pluginKeys, + }).desired, + ['severity: other', 'plugin: taxingcorn117…[taxingcorn117stranslations]'], + ); + + const syntheticLongIdBody = [ + '### Plugin', + '', + 'English: Ultra Long Plugin Name', + '', + '### Severity', + '', + 'Other', + ].join('\n'); + const syntheticPlan = computeLabelPlan({ + body: syntheticLongIdBody, + existingLabels: ['bug'], + pluginKeys: { 'English: Ultra Long Plugin Name': 'a'.repeat(45) }, + }); + const syntheticPluginLabel = syntheticPlan.desired.find(label => + label.startsWith('plugin:'), + ); + assert.ok(syntheticPluginLabel); + assert.ok(syntheticPluginLabel.length <= 50); + assert.match(syntheticPluginLabel, /^plugin: .*\[[^\]]+\]$/); +}); + +test('computeLabelPlan reconciles stale labels and preserves unlisted manual language labels', () => { + const editedBugBody = [ + '### Plugin', + '', + 'English: NovelBuddy', + '', + '### Severity', + '', + 'Domain Changed', + ].join('\n'); + + assert.deepEqual( + computeLabelPlan({ + body: editedBugBody, + existingLabels: [ + 'bug', + 'severity: wrong formatting', + 'plugin: novel fire[novelfire]', + 'plugin:', + 'duplicate', + ], + pluginKeys, + }), + { + desired: ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + add: ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + remove: [ + 'severity: wrong formatting', + 'plugin: novel fire[novelfire]', + 'plugin:', + ], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: editedBugBody, + existingLabels: [ + 'bug', + 'severity: domain changed', + 'plugin: novelbuddy[novelbuddy]', + ], + pluginKeys, + }), + { + desired: ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], + add: [], + remove: [], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nEnglish', + existingLabels: ['plugin request', 'language: vietnamese'], + pluginKeys, + }), + { + desired: [], + add: [], + remove: ['language: vietnamese'], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nVietnamese (Tiếng Việt)', + existingLabels: ['plugin request', 'language: arabic'], + pluginKeys, + }), + { + desired: ['language: vietnamese'], + add: ['language: vietnamese'], + remove: ['language: arabic'], + }, + ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nSwedish', + existingLabels: ['plugin request', 'language: swedish'], + pluginKeys, + }), + { + desired: [], + add: [], + remove: [], + }, + ); +}); + +test('plugin request issue supports all expanded language aliases and delimited primary language', () => { + const cases = [ + ['Burmese', ['language: burmese']], + ['မြန်မာ', ['language: burmese']], + ['Czech', ['language: czech']], + ['Čeština', ['language: czech']], + ['Greek', ['language: greek']], + ['Hebrew', ['language: hebrew']], + ['Romanian', ['language: romanian']], + ['Hindi', ['language: hindi']], + ['Tagalog', ['language: filipino']], + ['Filipino', ['language: filipino']], + ['Bahasa Melayu', ['language: malay']], + ['Persian', ['language: persian']], + ['Dutch', ['language: dutch']], + ['Vietnamese (Tiếng Việt)', ['language: vietnamese']], + ['English / Vietnamese', []], + ]; + + for (const [languageInput, expected] of cases) { + const body = ['### Language', '', languageInput].join('\n'); + assert.deepEqual( + computeLabelPlan({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }).desired, + expected, + ); + } +}); + +test('auto-label-issue CLI outputs add and remove JSON', () => { + const stdout = execFileSync( + process.execPath, + [path.join(__dirname, 'auto-label-issue.cjs')], + { + env: { + ...process.env, + ISSUE_BODY: + '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nMissing Chapter', + ISSUE_LABELS: JSON.stringify(['bug', 'severity: other']), + }, + encoding: 'utf8', + }, + ); + + assert.deepEqual(JSON.parse(stdout), { + add: ['severity: missing chapter', 'plugin: novel fire[novelfire]'], + remove: ['severity: other'], + }); +}); + +test('renderIssueTemplate substitutes {#CHANGE#} placeholder with YAML list options', () => { + assert.equal( + renderIssueTemplate('options:\n {#CHANGE#}\n', [ + 'English: A', + 'English: B', + ]), + 'options:\n - "English: A"\n - "English: B"\n', + ); +}); diff --git a/.github/scripts/blank_report_issue.yml b/.github/scripts/blank_report_issue.yml index 6427259f2b..603424121b 100644 --- a/.github/scripts/blank_report_issue.yml +++ b/.github/scripts/blank_report_issue.yml @@ -75,7 +75,7 @@ body: label: LNReader Version description: Find this in **More → About**. placeholder: | - Example: "2.0.0" + Example: "2.1.4" validations: required: true @@ -117,7 +117,7 @@ body: required: true - label: I have written a clear and descriptive title. required: true - - label: I have updated the app to the latest version **[2.0.0](https://github.com/LNReader/lnreader/releases/tag/v2.0.0-beta.3)**. + - label: I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**. required: true - label: I have updated all installed plugins to the latest version. required: true diff --git a/.github/scripts/check-github.cjs b/.github/scripts/check-github.cjs new file mode 100644 index 0000000000..2bf5fe19d6 --- /dev/null +++ b/.github/scripts/check-github.cjs @@ -0,0 +1,137 @@ +'use strict'; + +const { execFileSync } = require('node:child_process'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { + renderIssueTemplate, +} = require('./generate-issue-template-options.cjs'); + +const ROOT_DIR = path.resolve(__dirname, '../..'); +const SCRIPTS_DIR = path.join(ROOT_DIR, '.github', 'scripts'); +const WORKFLOWS_DIR = path.join(ROOT_DIR, '.github', 'workflows'); + +function run(cmd, args, label) { + process.stdout.write(`\n=== ${label} ===\n`); + execFileSync(cmd, args, { cwd: ROOT_DIR, stdio: 'inherit' }); +} + +function hasActionlint() { + try { + execFileSync('actionlint', ['-version'], { + cwd: ROOT_DIR, + stdio: 'ignore', + }); + return true; + } catch (err) { + if (err && err.code === 'ENOENT') return false; + throw err; + } +} + +function main() { + const requireActionlint = process.argv.includes('--require-actionlint'); + const scriptEntries = fs.readdirSync(SCRIPTS_DIR).sort(); + const cjsFiles = scriptEntries + .filter(name => name.endsWith('.cjs')) + .map(name => path.join('.github', 'scripts', name)); + const testFiles = cjsFiles.filter(file => file.endsWith('.test.cjs')); + + run(process.execPath, ['--test', ...testFiles], 'GitHub Script Tests'); + + const prettierBin = path.join(ROOT_DIR, 'node_modules', '.bin', 'prettier'); + const eslintBin = path.join(ROOT_DIR, 'node_modules', '.bin', 'eslint'); + run(prettierBin, ['--check', ...cjsFiles], 'Prettier Check'); + run(eslintBin, ['--max-warnings', '0', ...cjsFiles], 'ESLint Check'); + + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lnreader-gh-check-')); + try { + const blank = fs.readFileSync( + path.join(SCRIPTS_DIR, 'blank_report_issue.yml'), + 'utf8', + ); + const keys = Object.keys( + JSON.parse(fs.readFileSync(path.join(SCRIPTS_DIR, 'keys.json'), 'utf8')), + ); + const renderedPath = path.join(tmpDir, 'rendered-report-issue.yml'); + fs.writeFileSync(renderedPath, renderIssueTemplate(blank, keys)); + + run( + 'python3', + [ + path.join('.github', 'scripts', 'validate-github-yaml.py'), + '--rendered-report', + renderedPath, + ], + 'YAML & Issue Form Validation', + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + + if (!hasActionlint()) { + if (requireActionlint) { + throw new Error('actionlint is required but was not found on PATH.'); + } + process.stdout.write( + '\n=== actionlint ===\nSkipped (actionlint binary not found on PATH).\n', + ); + return; + } + + const workflowFiles = fs + .readdirSync(WORKFLOWS_DIR) + .filter(name => name.endsWith('.yml') || name.endsWith('.yaml')) + .sort() + .map(name => path.join('.github', 'workflows', name)); + const standardWorkflows = workflowFiles.filter( + file => + path.basename(file) !== 'publish-plugins.yml' && + path.basename(file) !== 'theme_auto_label.yml', + ); + + if (standardWorkflows.length > 0) { + run( + 'actionlint', + [ + '-ignore', + 'unexpected key "queue" for "concurrency" section', + ...standardWorkflows, + ], + 'actionlint', + ); + } + + const publishWorkflow = path.join( + '.github', + 'workflows', + 'publish-plugins.yml', + ); + if (fs.existsSync(path.join(ROOT_DIR, publishWorkflow))) { + run( + 'actionlint', + [ + '-ignore', + 'SC2086:info:1:29: Double quote to prevent globbing and word splitting', + publishWorkflow, + ], + 'actionlint (publish-plugins.yml)', + ); + } + + const themeWorkflow = path.join( + '.github', + 'workflows', + 'theme_auto_label.yml', + ); + if (fs.existsSync(path.join(ROOT_DIR, themeWorkflow))) { + run( + 'actionlint', + ['-ignore', 'SC2086:info:', themeWorkflow], + 'actionlint (theme_auto_label.yml)', + ); + } +} + +main(); diff --git a/.github/scripts/generate-issue-index.cjs b/.github/scripts/generate-issue-index.cjs index 9cafd5b426..f2985b3de2 100644 --- a/.github/scripts/generate-issue-index.cjs +++ b/.github/scripts/generate-issue-index.cjs @@ -1,39 +1,12 @@ 'use strict'; const fs = require('node:fs'); - -const CATEGORY_CODES = new Map([ - ['wrong formatting', 1], - ['wrong content', 2], - ['missing chapter', 3], - ['missing images', 4], - ["can't load novels", 5], - ['domain changed', 6], -]); -const DIRECTIONAL_CONTROLS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; - -function comparisonValue(value) { - return value - .replace(DIRECTIONAL_CONTROLS, '') - .trim() - .toLocaleLowerCase('en-US'); -} - -function extractSection(body, name) { - const lines = (body || '').replace(/\r\n?/g, '\n').split('\n'); - const heading = new RegExp(`^\\s{0,3}###\\s+${name}\\s*#*\\s*$`, 'i'); - const start = lines.findIndex(line => - heading.test(line.replace(DIRECTIONAL_CONTROLS, '')), - ); - if (start < 0) return { present: false, lines: [] }; - let end = start + 1; - while ( - end < lines.length && - !/^\s{0,3}#{1,6}(?:\s|$)/.test(lines[end].replace(DIRECTIONAL_CONTROLS, '')) - ) - end += 1; - return { present: true, lines: lines.slice(start + 1, end) }; -} +const { + CATEGORY_CODES, + buildSelectionMatcher, + comparisonValue, + extractSection, +} = require('./issue-parsing.cjs'); function createLookups(pluginKeys) { const prototype = @@ -94,11 +67,10 @@ function resolveSelection(lines, lookups, issueNumber, warn) { .filter(Boolean) .join(', '); const normalized = comparisonValue(selection); - const alternatives = lookups.candidates - .map(candidate => candidate.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - .join('|'); - if (!alternatives) return { ids: new Set(), unresolved: selection }; - const regex = new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); + const regex = buildSelectionMatcher( + lookups.candidates.map(candidate => candidate.value), + ); + if (!regex) return { ids: new Set(), unresolved: selection }; const ids = new Set(); const spans = []; let match; diff --git a/.github/scripts/generate-issue-index.test.cjs b/.github/scripts/generate-issue-index.test.cjs new file mode 100644 index 0000000000..bb098f13b8 --- /dev/null +++ b/.github/scripts/generate-issue-index.test.cjs @@ -0,0 +1,108 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const { + buildIssueIndex, + updateIssueIndex, +} = require('./generate-issue-index.cjs'); + +const pluginKeys = JSON.parse( + fs.readFileSync(path.join(__dirname, 'keys.json'), 'utf8'), +); + +test('buildIssueIndex resolves English, Chinese comma keys, Arabic LRM keys, and severity codes', () => { + const issues = [ + { + number: 101, + state: 'open', + labels: [{ name: 'bug' }], + body: [ + '### Plugin', + '', + 'English: Novel Fire, 中文, 汉语, 漢語: 69书吧', + '', + '### Severity', + '', + "Can't Load Novels", + ].join('\n'), + }, + { + number: 102, + state: 'open', + labels: [{ name: 'bug' }], + body: [ + '### Plugin', + '', + '\u200eالعربية: ArNovel', + '', + '### Severity', + '', + 'Wrong Formatting', + ].join('\n'), + }, + { + number: 103, + state: 'closed', + labels: [{ name: 'bug' }], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nOther', + }, + { + number: 104, + state: 'open', + pull_request: {}, + labels: [], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nOther', + }, + ]; + + const warnings = []; + assert.deepEqual( + buildIssueIndex(issues, pluginKeys, msg => warnings.push(msg)), + { + '69shu': [[5, 101]], + arnovel: [[1, 102]], + novelfire: [[5, 101]], + }, + ); + assert.deepEqual(warnings, []); +}); + +test('updateIssueIndex adds, updates, and removes open issues cleanly', () => { + const warnings = []; + const warn = msg => warnings.push(msg); + + const initial = buildIssueIndex( + [ + { + number: 201, + state: 'open', + labels: [{ name: 'bug' }], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nMissing Chapter', + }, + ], + pluginKeys, + warn, + ); + + const updated = updateIssueIndex( + initial, + 201, + { + number: 201, + state: 'open', + labels: [{ name: 'bug' }], + body: '### Plugin\n\nEnglish: Novel Fire\n\n### Severity\n\nDomain Changed', + }, + pluginKeys, + warn, + ); + assert.deepEqual(updated, { novelfire: [[6, 201]] }); + + const removed = updateIssueIndex(updated, 201, null, pluginKeys, warn); + assert.deepEqual(removed, {}); + assert.deepEqual(warnings, []); +}); diff --git a/.github/scripts/generate-issue-template-options.cjs b/.github/scripts/generate-issue-template-options.cjs index 8af5784764..c5c217be7f 100644 --- a/.github/scripts/generate-issue-template-options.cjs +++ b/.github/scripts/generate-issue-template-options.cjs @@ -2,12 +2,16 @@ const version = require('../../package.json').version; const dist = `plugins/v${version}`; const fs = require('fs'); -const rawText = fs.readFileSync( - '.github/scripts/blank_report_issue.yml', - 'utf8', -); +function renderIssueTemplate(rawText, keys) { + const text = keys.join('"\n - "'); + return rawText.replace(/{#CHANGE#}/g, '- "' + text + '"'); +} async function main() { + const rawText = fs.readFileSync( + '.github/scripts/blank_report_issue.yml', + 'utf8', + ); console.log(`Fetching published plugin manifest from ${dist}...`); try { @@ -41,8 +45,7 @@ async function main() { console.log('No saved plugin keys found; a new key map will be created.'); } - const text = newKeys.join('"\n - "'); - const issueTemplate = rawText.replace(/{#CHANGE#}/g, '- "' + text + '"'); + const issueTemplate = renderIssueTemplate(rawText, newKeys); const keysChanged = !sameKeys(newKeys, savedKeys) && Array.isArray(newKeys); if (keysChanged) { @@ -80,7 +83,11 @@ async function main() { } } -main().catch(err => { - console.error('Fatal error:', err); - process.exit(1); -}); +if (require.main === module) { + main().catch(err => { + console.error('Fatal error:', err); + process.exit(1); + }); +} + +module.exports = { renderIssueTemplate }; diff --git a/.github/scripts/issue-parsing.cjs b/.github/scripts/issue-parsing.cjs new file mode 100644 index 0000000000..69f50c11e1 --- /dev/null +++ b/.github/scripts/issue-parsing.cjs @@ -0,0 +1,210 @@ +'use strict'; + +const DIRECTIONAL_CONTROLS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; + +const EXEMPT_ASSOCIATIONS = new Set(['owner', 'member', 'collaborator']); + +const TEMPLATE_BOUNDARIES = Object.freeze({ + reportIssue: [ + 'Plugin', + 'Severity', + 'Steps To Reproduce', + 'Expected Behavior', + 'Actual Behavior', + 'LNReader Version', + 'Plugin Version', + 'Android Version', + 'Other Details', + 'Acknowledgements', + ], + requestPlugin: [ + 'Plugin Name', + 'Website URL', + 'Language', + 'Other Details', + 'Acknowledgements', + ], + requestFeature: ['Feature Description', 'Other Details', 'Acknowledgements'], +}); + +const CATEGORY_CODES = new Map([ + ['wrong formatting', 1], + ['wrong content', 2], + ['missing chapter', 3], + ['missing images', 4], + ["can't load novels", 5], + ['domain changed', 6], +]); + +const VALID_SEVERITIES = new Set([...CATEGORY_CODES.keys(), 'other']); + +function stripDirectional(value) { + return String(value || '').replace(DIRECTIONAL_CONTROLS, ''); +} + +function comparisonValue(value) { + return stripDirectional(value).trim().toLocaleLowerCase('en-US'); +} + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function buildSelectionMatcher(normalizedKeys) { + const sorted = [...new Set(normalizedKeys)].sort( + (a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0), + ); + if (sorted.length === 0) return null; + const alternatives = sorted.map(escapeRegExp).join('|'); + return new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); +} + +function extractSection(body, headingName, boundaryHeadings) { + const lines = String(body || '') + .replace(/\r\n?/g, '\n') + .split('\n'); + const heading = new RegExp( + `^\\s{0,3}###\\s+${escapeRegExp(headingName)}\\s*#*\\s*$`, + 'i', + ); + const start = lines.findIndex(line => heading.test(stripDirectional(line))); + if (start < 0) return { present: false, lines: [] }; + + const validBoundaries = Array.isArray(boundaryHeadings) + ? [...new Set(boundaryHeadings.filter(Boolean))] + : []; + const stopHeading = + validBoundaries.length > 0 + ? new RegExp( + `^\\s{0,3}###\\s+(?:${validBoundaries.map(escapeRegExp).join('|')})\\s*#*\\s*$`, + 'i', + ) + : /^\s{0,3}#{1,6}(?:\s|$)/; + + let end = start + 1; + while ( + end < lines.length && + !stopHeading.test(stripDirectional(lines[end])) + ) { + end += 1; + } + + return { present: true, lines: lines.slice(start + 1, end) }; +} + +function nonEmptySectionLines(section) { + if (!section || !Array.isArray(section.lines)) return []; + return section.lines + .map(line => stripDirectional(line).trim()) + .filter( + line => line.length > 0 && comparisonValue(line) !== '_no response_', + ); +} + +function isValidAuthor(author) { + return ( + typeof author === 'string' && + /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(author) + ); +} + +function isValidRepository(repository) { + if (typeof repository !== 'string') return false; + const parts = repository.split('/'); + if (parts.length !== 2) return false; + const [owner, repo] = parts; + return ( + isValidAuthor(owner) && + /^[a-zA-Z0-9._-]+$/.test(repo) && + repo !== '.' && + repo !== '..' + ); +} + +function normalizeLabelNames(labels) { + return new Set( + (Array.isArray(labels) ? labels : []) + .map(label => (typeof label === 'string' ? label : label && label.name)) + .filter(label => typeof label === 'string') + .map(comparisonValue) + .filter(Boolean), + ); +} + +function parseJsonOrDefault(rawValue, fallback) { + if (!rawValue) return fallback; + try { + const parsed = JSON.parse(rawValue); + return parsed === undefined ? fallback : parsed; + } catch { + return fallback; + } +} + +function isExemptAuthor({ authorAssociation = '', authorType = '' } = {}) { + return ( + EXEMPT_ASSOCIATIONS.has(comparisonValue(authorAssociation)) || + comparisonValue(authorType) === 'bot' + ); +} + +function matchPluginEntries(lines, pluginKeys) { + if ( + !pluginKeys || + typeof pluginKeys !== 'object' || + !Array.isArray(lines) || + lines.length === 0 + ) { + return []; + } + + const entriesByKey = new Map(); + for (const [displayKey, id] of Object.entries(pluginKeys)) { + if (typeof id !== 'string') continue; + const normalizedKey = comparisonValue(displayKey); + if (!normalizedKey || !comparisonValue(id)) continue; + entriesByKey.set(normalizedKey, { displayKey, id }); + } + + const regex = buildSelectionMatcher(entriesByKey.keys()); + if (!regex) return []; + const selection = comparisonValue(lines.join(', ')); + + const matched = []; + const seenIds = new Set(); + let match; + while ((match = regex.exec(selection)) !== null) { + const entry = entriesByKey.get(match[1]); + if (!entry) continue; + const normId = comparisonValue(entry.id); + if (seenIds.has(normId)) continue; + seenIds.add(normId); + const sepIdx = entry.displayKey.indexOf(': '); + const name = + sepIdx >= 0 ? entry.displayKey.slice(sepIdx + 2) : entry.displayKey; + matched.push({ + displayKey: entry.displayKey, + name, + id: entry.id, + }); + } + return matched; +} + +module.exports = { + CATEGORY_CODES, + VALID_SEVERITIES, + EXEMPT_ASSOCIATIONS, + TEMPLATE_BOUNDARIES, + stripDirectional, + comparisonValue, + buildSelectionMatcher, + extractSection, + nonEmptySectionLines, + isValidAuthor, + isValidRepository, + normalizeLabelNames, + parseJsonOrDefault, + isExemptAuthor, + matchPluginEntries, +}; diff --git a/.github/scripts/validate-github-yaml.py b/.github/scripts/validate-github-yaml.py new file mode 100644 index 0000000000..5eb9055f0e --- /dev/null +++ b/.github/scripts/validate-github-yaml.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Validate GitHub workflow YAML files and Issue Form templates.""" + +from __future__ import annotations + +import argparse +import glob +import os +import sys +import yaml + + +class UniqueKeyLoader(yaml.SafeLoader): + pass + + +def construct_mapping_no_duplicates(loader, node, deep=False): + mapping = {} + for key_node, value_node in node.value: + key = loader.construct_object(key_node, deep=deep) + if key in mapping: + raise yaml.constructor.ConstructorError( + 'while constructing a mapping', + node.start_mark, + f'found duplicate key {key!r}', + key_node.start_mark, + ) + mapping[key] = loader.construct_object(value_node, deep=deep) + return mapping + + +UniqueKeyLoader.add_constructor( + yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + construct_mapping_no_duplicates, +) + + +def validate_issue_form(data: object) -> None: + if not isinstance(data, dict): + raise ValueError('Issue template must be a YAML mapping') + for field in ('name', 'description'): + val = data.get(field) + if not isinstance(val, str) or not val.strip(): + raise ValueError(f'Missing or empty string field: {field}') + body = data.get('body') + if not isinstance(body, list) or len(body) == 0: + raise ValueError('Issue template body must be a non-empty list') + for idx, item in enumerate(body): + if ( + not isinstance(item, dict) + or not isinstance(item.get('type'), str) + or not item['type'].strip() + ): + raise ValueError(f'Issue template body[{idx}] missing valid type') + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + '--rendered-report', + default=os.environ.get('RENDERED_REPORT_PATH', ''), + help='Optional path to a rendered report_issue.yml file to validate.', + ) + args = parser.parse_args() + + rendered_report = args.rendered_report.strip() + issue_templates = sorted( + set( + glob.glob('.github/ISSUE_TEMPLATE/*.yml') + + glob.glob('.github/ISSUE_TEMPLATE/*.yaml') + ) + ) + paths = sorted( + set( + glob.glob('.github/workflows/*.yml') + + glob.glob('.github/workflows/*.yaml') + + issue_templates + + ([rendered_report] if rendered_report else []) + ) + ) + + failed = False + for file_path in paths: + try: + with open(file_path, encoding='utf-8') as fh: + content = fh.read() + data = yaml.load(content, Loader=UniqueKeyLoader) + is_issue_form = (rendered_report and file_path == rendered_report) or ( + file_path.startswith('.github/ISSUE_TEMPLATE/') + and os.path.basename(file_path) not in ('config.yml', 'config.yaml') + ) + if is_issue_form: + validate_issue_form(data) + except Exception as exc: + print(f'Invalid YAML in {file_path}: {exc}', file=sys.stderr) + failed = True + + if failed: + return 1 + + suffix = ' (including rendered blank_report_issue.yml)' if rendered_report else '' + print(f'Validated {len(paths)} YAML files{suffix}.') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/.github/workflows/generate-issue-index.yml b/.github/workflows/generate-issue-index.yml index 764555864a..8945a5f918 100644 --- a/.github/workflows/generate-issue-index.yml +++ b/.github/workflows/generate-issue-index.yml @@ -14,6 +14,7 @@ on: branches: [master] paths: - .github/scripts/generate-issue-index.cjs + - .github/scripts/issue-parsing.cjs - .github/scripts/keys.json - .github/workflows/generate-issue-index.yml workflow_run: diff --git a/.github/workflows/github-scripts-check.yml b/.github/workflows/github-scripts-check.yml new file mode 100644 index 0000000000..d045469c83 --- /dev/null +++ b/.github/workflows/github-scripts-check.yml @@ -0,0 +1,135 @@ +name: GitHub Scripts & Templates Check + +on: + pull_request: + branches: [master] + push: + branches: [master] + paths: + - '.github/**' + workflow_dispatch: + +permissions: {} + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + name: Validate GitHub Scripts & YAML + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + + steps: + - name: Checkout Repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: ${{ github.event_name == 'pull_request' && 2 || 1 }} + persist-credentials: false + + - name: Detect .github Changes + id: scope + env: + EVENT_NAME: ${{ github.event_name }} + run: | + if [ "$EVENT_NAME" != "pull_request" ]; then + echo "run_checks=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if git rev-parse --verify HEAD^1 >/dev/null 2>&1; then + if [ -n "$(git diff --name-only HEAD^1 HEAD -- .github/)" ]; then + echo "run_checks=true" >> "$GITHUB_OUTPUT" + else + echo "run_checks=false" >> "$GITHUB_OUTPUT" + fi + else + echo "run_checks=true" >> "$GITHUB_OUTPUT" + fi + + - name: Reject Direct Edits To Generated Issue Template + if: github.event_name == 'pull_request' && steps.scope.outputs.run_checks == 'true' + run: | + if git rev-parse --verify HEAD^1 >/dev/null 2>&1 && \ + [ -n "$(git diff --name-only HEAD^1 HEAD -- .github/ISSUE_TEMPLATE/report_issue.yml)" ]; then + echo "Do not edit .github/ISSUE_TEMPLATE/report_issue.yml directly; edit .github/scripts/blank_report_issue.yml instead." >&2 + exit 1 + fi + + - name: Setup Node.js + if: steps.scope.outputs.run_checks == 'true' + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: '24' + cache: 'npm' + + - name: Run GitHub Script Tests + if: steps.scope.outputs.run_checks == 'true' + run: | + node --test .github/scripts/*.test.cjs + if [ -n "$(git status --porcelain)" ]; then + echo "GitHub script tests modified the working tree:" >&2 + git status --short >&2 + exit 1 + fi + + - name: Install Dependencies + if: steps.scope.outputs.run_checks == 'true' + run: npm ci + + - name: Check Formatting & Lint for GitHub Scripts + if: steps.scope.outputs.run_checks == 'true' + run: | + ./node_modules/.bin/prettier --check ".github/scripts/*.cjs" + ./node_modules/.bin/eslint --max-warnings 0 ".github/scripts/*.cjs" + + - name: Validate GitHub YAML & Issue Templates + if: steps.scope.outputs.run_checks == 'true' + run: | + node <<'JS' + const fs = require('node:fs'); + const path = require('node:path'); + const { renderIssueTemplate } = require('./.github/scripts/generate-issue-template-options.cjs'); + const blank = fs.readFileSync('.github/scripts/blank_report_issue.yml', 'utf8'); + const keys = Object.keys(JSON.parse(fs.readFileSync('.github/scripts/keys.json', 'utf8'))); + const outPath = path.join(process.env.RUNNER_TEMP, 'rendered-report-issue.yml'); + fs.writeFileSync(outPath, renderIssueTemplate(blank, keys)); + JS + python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --quiet PyYAML==6.0.2 + python3 .github/scripts/validate-github-yaml.py --rendered-report "$RUNNER_TEMP/rendered-report-issue.yml" + + - name: Run actionlint + if: steps.scope.outputs.run_checks == 'true' + run: | + set -euo pipefail + ARCHIVE="$RUNNER_TEMP/actionlint.tar.gz" + BIN_DIR="$RUNNER_TEMP/actionlint-bin" + mkdir -p "$BIN_DIR" + curl --silent --show-error --fail --location --max-time 30 \ + -o "$ARCHIVE" \ + "https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz" + echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 $ARCHIVE" | sha256sum -c - + tar -xzf "$ARCHIVE" -C "$BIN_DIR" actionlint + shopt -s nullglob + WORKFLOWS=() + for wf in .github/workflows/*.yml .github/workflows/*.yaml; do + [ "$(basename "$wf")" = "publish-plugins.yml" ] || [ "$(basename "$wf")" = "theme_auto_label.yml" ] && continue + WORKFLOWS+=("$wf") + done + # Ignore pre-existing upstream workflow notices unrelated to PR changes: + # - generate-issue-index.yml uses concurrency.queue (beta/unsupported in actionlint schema) + "$BIN_DIR/actionlint" \ + -ignore 'unexpected key "queue" for "concurrency" section' \ + "${WORKFLOWS[@]}" + if [ -f .github/workflows/publish-plugins.yml ]; then + "$BIN_DIR/actionlint" \ + -ignore 'SC2086:info:1:29: Double quote to prevent globbing and word splitting' \ + .github/workflows/publish-plugins.yml + fi + if [ -f .github/workflows/theme_auto_label.yml ]; then + "$BIN_DIR/actionlint" \ + -ignore 'SC2086:info:' \ + .github/workflows/theme_auto_label.yml + fi diff --git a/.github/workflows/issue_auto_label.yml b/.github/workflows/issue_auto_label.yml index 71f58f40e5..48a0be87a4 100644 --- a/.github/workflows/issue_auto_label.yml +++ b/.github/workflows/issue_auto_label.yml @@ -5,23 +5,31 @@ on: types: - opened - edited + - labeled permissions: {} concurrency: group: ${{ github.workflow }}-${{ github.event.issue.number }} - cancel-in-progress: true + cancel-in-progress: false jobs: auto-label: name: Auto Label Issues - if: ${{ github.event.issue.body && contains(github.event.issue.body, '### Plugin') && contains(github.event.issue.labels.*.name, 'bug') }} + if: >- + ${{ + github.event.issue.body && + (github.event.action != 'labeled' || github.event.label.name == 'bug' || github.event.label.name == 'plugin request') && + ( + contains(github.event.issue.labels.*.name, 'bug') || + contains(github.event.issue.labels.*.name, 'plugin request') + ) + }} runs-on: ubuntu-latest + timeout-minutes: 5 permissions: contents: read issues: write - env: - ISSUE_BODY: ${{ github.event.issue.body }} steps: - name: Checkout Repository @@ -29,69 +37,57 @@ jobs: with: persist-credentials: false - - name: Extract Severity From Issue Body - id: extract-severity - run: | - USER_SELECTED_SEVERITY=$(printf '%s\n' "$ISSUE_BODY" | grep "### Severity" -A 2 | tail -n 1 | sed 's/[[:space:]]*$//') - SELECTED_SEVERITY="" - - case "$USER_SELECTED_SEVERITY" in - "Wrong Formatting"|"Wrong Content"|"Missing Chapter"|"Missing Images"|"Can't Load Novels"|"Domain Changed") - SELECTED_SEVERITY="$USER_SELECTED_SEVERITY" - ;; - *) - SELECTED_SEVERITY="Other" - ;; - esac - echo "SELECTED_SEVERITY=$SELECTED_SEVERITY" >> "$GITHUB_ENV" - - - name: Extract Plugin From Issue Body - id: parse-issue - run: | - SELECTED_PLUGIN=$(printf '%s\n' "$ISSUE_BODY" | awk '/### Plugin/ {f=1; next} f && NF {print; exit}' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - - echo "SELECTED_PLUGIN=$SELECTED_PLUGIN" >> "$GITHUB_ENV" - - - name: Extract Language From Issue Body - id: extract-language - run: | - SELECTED_LANGUAGE=$(printf '%s\n' "$ISSUE_BODY" | awk '/### Language/ {f=1; next} f && NF {print; exit}' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') - - echo "SELECTED_LANGUAGE=$SELECTED_LANGUAGE" >> "$GITHUB_ENV" + - name: Setup Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: '24' - - name: Determine Corresponding Label - id: determine-label + - name: Determine Labels + id: determine-labels + env: + ISSUE_BODY: ${{ github.event.issue.body }} + ISSUE_LABELS: ${{ toJSON(github.event.issue.labels.*.name) }} run: | - LABELS="$(jq --arg keys "$SELECTED_PLUGIN" '. as $data | $keys | split(", ") as $keyList | $keyList[] | . as $key | if $data[$key] != null then "\($key)[\($data[$key])]" else empty end' ./.github/scripts/keys.json | sed 's/"//g' | sed 's/^[^:]*: //')" - - LABELS="$(printf '%s' "$LABELS" | node -e "process.stdin.on('data', data => process.stdout.write(data.toString().toLowerCase()))")" - - # Add "plugin: " in front of each label - LABELS_WITH_PREFIX="$(echo "$LABELS" | sed 's/^/plugin: /')" - - FINAL_LABELS="$LABELS_WITH_PREFIX" - - if [ -n "$SELECTED_LANGUAGE" ]; then - LOWERCASE_LANGUAGE="$(printf '%s' "$SELECTED_LANGUAGE" | node -e "process.stdin.on('data', data => process.stdout.write(data.toString().toLowerCase()))")" - FINAL_LABELS="${FINAL_LABELS}"$'\n'"language: $LOWERCASE_LANGUAGE" - fi - - # Save to GitHub environment - printf "LABELS<> "$GITHUB_ENV" - - - name: Add Labels To Issue - if: env.LABELS != '' + node .github/scripts/auto-label-issue.cjs > "$RUNNER_TEMP/labels.json" + ADD_COUNT=$(jq '.add | length' "$RUNNER_TEMP/labels.json") + REMOVE_COUNT=$(jq '.remove | length' "$RUNNER_TEMP/labels.json") + { + echo "add_count=$ADD_COUNT" + echo "remove_count=$REMOVE_COUNT" + } >> "$GITHUB_OUTPUT" + + - name: Sync Labels On Issue + if: steps.determine-labels.outputs.add_count != '0' || steps.determine-labels.outputs.remove_count != '0' env: GH_TOKEN: ${{ github.token }} ISSUE_NUMBER: ${{ github.event.issue.number }} REPOSITORY: ${{ github.repository }} + ADD_COUNT: ${{ steps.determine-labels.outputs.add_count }} + REMOVE_COUNT: ${{ steps.determine-labels.outputs.remove_count }} run: | - jq -n \ - --arg severity "$(printf '%s' "$SELECTED_SEVERITY" | node -e "process.stdin.on('data', data => process.stdout.write(data.toString().toLowerCase()))")" \ - --arg labels "$LABELS" \ - '{labels: (["severity: " + $severity] + ($labels | split("\n") | map(select(length > 0))))}' \ - | gh api --method POST "repos/$REPOSITORY/issues/$ISSUE_NUMBER/labels" --input - + while IFS= read -r label; do + [ -n "$label" ] || continue + encoded=$(jq -rn --arg l "$label" '$l | @uri') + if ! gh api "repos/$REPOSITORY/labels/$encoded" >/dev/null 2>&1; then + if ! gh api --method POST "repos/$REPOSITORY/labels" -f "name=$label" -f "color=ADD8E6" >/dev/null; then + gh api "repos/$REPOSITORY/labels/$encoded" >/dev/null + fi + fi + done < <(jq -r '.add[] | select(startswith("language: "))' "$RUNNER_TEMP/labels.json") + + if [ "$ADD_COUNT" != "0" ]; then + jq '{labels: .add}' "$RUNNER_TEMP/labels.json" \ + | gh api --method POST "repos/$REPOSITORY/issues/$ISSUE_NUMBER/labels" --input - + fi + + if [ "$REMOVE_COUNT" != "0" ]; then + while IFS= read -r label; do + [ -n "$label" ] || continue + encoded=$(jq -rn --arg l "$label" '$l | @uri') + gh api --method DELETE "repos/$REPOSITORY/issues/$ISSUE_NUMBER/labels/$encoded" >/dev/null 2>&1 || true + done < <(jq -r '.remove[]' "$RUNNER_TEMP/labels.json") + fi - - name: Handle Missing Label - if: env.LABELS == '' - run: echo "No matching label found for the selected plugin." + - name: Log No Matching Labels + if: steps.determine-labels.outputs.add_count == '0' && steps.determine-labels.outputs.remove_count == '0' + run: echo "No matching label changes found for the issue." diff --git a/AGENTS.md b/AGENTS.md index ee9fc7403c..adc7eeb772 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,8 +2,8 @@ ## Navigation pointers -- `CODING_STANDARDS.md` — coding, plugin, multisrc migration, and PR review standards (consult during review and before adding/migrating plugins). -- `package.json` — authoritative scripts (`lint`, `format:check`, `build:compile`, `build:full`, `dev:start`, `check:plugin`, `check:sites`, `test:plugin-error`, `test:live-check`). +- `CODING_STANDARDS.md` — coding, plugin, multisrc migration, and PR review standards (consult before editing plugins, workflows, or repo tooling and during review). +- `package.json` — authoritative build, lint, test, and live-check scripts. - `README.md`, `docs/quickstart.md`, `docs/docs.md`, `docs/testing.md`, `docs/plugin-template.ts` — setup, plugin API, live checker, and starter template. ## Repository map @@ -15,6 +15,7 @@ - `src/types/plugin.ts`, `src/libs/`: canonical plugin interfaces and `@libs/*` runtime helpers. - `src/`: React/Vite playground; `scripts/`: build, manifest, publishing, and live-check tooling. - `BLACKLIST.json`: disallowed sources. +- `.github/scripts/`, `.github/workflows/`: issue-form generation (`blank_report_issue.yml` -> `report_issue.yml`), issue-index publishing, and label/moderator automation (`keys.json` is shared; validate via `npm run test:scripts` or `npm run check:github`). ## Environment & package management diff --git a/CODING_STANDARDS.md b/CODING_STANDARDS.md index bce710563b..ed84a18c34 100644 --- a/CODING_STANDARDS.md +++ b/CODING_STANDARDS.md @@ -23,6 +23,11 @@ Review-time standards for LNReader plugins and repository tooling. Automated che 2. Move `public/static/multisrc///icon.png` to `public/static/src///icon.png`. 3. Preserve `id`, support legacy `resolveUrl`/trailing-slash paths, and bump the major `version`. +## GitHub workflows & scripts + +- **Managed label reconciliation & concurrency**: Workflows triggered on `issues.edited` or `issues.labeled` that apply managed labels (`language: *`, `plugin: *`, `severity: *`) must reconcile (`add`/`remove`) against an explicit `MANAGED_*_LABELS` set rather than issuing add-only `POST /labels` calls, and set `concurrency.cancel-in-progress: false` when filtered events could otherwise cancel an active sync. +- **Shared issue parsing**: Share form/section/plugin-matching helpers via `issue-parsing.cjs`. + ## Naming & scope - **camelCase**: Use `camelCase` for plugin variables, properties, methods, and function parameters. Fields on type aliases that mirror external JSON/API/RSC schemas (e.g., `chapter_number`, `published_at`) are exempt. diff --git a/package.json b/package.json index 60b989aa8a..ef3d011418 100644 --- a/package.json +++ b/package.json @@ -20,12 +20,14 @@ "serve:dev": "npm run build:compile && npm run build:manifest:dev && node ./scripts/copy-legacy-plugin-path.js && serve", "lint": "npx eslint .", "lint:fix": "npx eslint . --fix", - "format": "prettier --write \"./**/*.{js,ts}\"", - "format:check": "prettier --check \"./**/*.{js,ts}\"", + "format": "prettier --write \"./**/*.{js,cjs,mjs,ts}\"", + "format:check": "prettier --check \"./**/*.{js,cjs,mjs,ts}\"", "check:sites": "node scripts/check-plugin-sites.js", "check:plugin": "node scripts/live-check-plugin.js", "test:plugin-error": "node --test scripts/plugin-error.test.js", "test:live-check": "node --test scripts/live-check-plugin.test.js", + "test:scripts": "node --test .github/scripts/*.test.cjs", + "check:github": "node .github/scripts/check-github.cjs", "prepare": "husky" }, "author": "LNReader", @@ -97,7 +99,7 @@ "zustand": "^5.0.1" }, "lint-staged": { - "**/*.{js,ts,jsx,tsx}": [ + "**/*.{js,cjs,mjs,ts,jsx,tsx}": [ "prettier --write", "eslint --max-warnings 0 --no-warn-ignored" ]