From a979e8fec5773dcbb6a46c351a41632455ac3df5 Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:42:44 +0700 Subject: [PATCH 1/7] fix(github): fix issue templates, auto-labeling, and moderator workflows --- .github/ISSUE_TEMPLATE/request_feature.yml | 2 +- .github/scripts/auto-label-issue.cjs | 204 ++++++++++++++++ .github/scripts/auto-label-issue.test.cjs | 217 ++++++++++++++++++ .github/scripts/blank_report_issue.yml | 4 +- .github/scripts/generate-issue-index.cjs | 41 +--- .github/scripts/generate-issue-index.test.cjs | 108 +++++++++ .github/scripts/issue-parsing.cjs | 68 ++++++ .github/workflows/generate-issue-index.yml | 1 + .github/workflows/issue_auto_label.yml | 87 +++---- .github/workflows/issue_moderator.yml | 24 +- .github/workflows/theme_auto_label.yml | 111 +++++---- 11 files changed, 707 insertions(+), 160 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/generate-issue-index.test.cjs create mode 100644 .github/scripts/issue-parsing.cjs 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..0358881438 --- /dev/null +++ b/.github/scripts/auto-label-issue.cjs @@ -0,0 +1,204 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { + VALID_SEVERITIES, + comparisonValue, + escapeRegExp, + extractSection, + nonEmptySectionLines, +} = require('./issue-parsing.cjs'); + +const LANGUAGE_ALIASES = new Map([ + // Arabic + ['arabic', 'arabic'], + ['ar', 'arabic'], + ['العربية', 'arabic'], + ['عربي', 'arabic'], + // Bengali + ['bengali', 'bengali'], + ['bangla', 'bengali'], + ['bn', 'bengali'], + ['বাংলা', 'bengali'], + // Chinese + ['chinese', 'chinese'], + ['zh', 'chinese'], + ['zh-cn', 'chinese'], + ['zh-tw', 'chinese'], + ['cn', 'chinese'], + ['中文', 'chinese'], + ['汉语', 'chinese'], + ['漢語', 'chinese'], + ['简体中文', 'chinese'], + ['繁體中文', 'chinese'], + // French + ['french', 'french'], + ['fr', 'french'], + ['français', 'french'], + ['francais', 'french'], + // German + ['german', 'german'], + ['de', 'german'], + ['deutsch', 'german'], + // 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'], + // Polish + ['polish', 'polish'], + ['pl', 'polish'], + ['polski', 'polish'], + // Portuguese + ['portuguese', 'portuguese'], + ['pt', 'portuguese'], + ['pt-br', 'portuguese'], + ['português', 'portuguese'], + ['portugues', 'portuguese'], + // 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'], +]); + +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; + return `plugin: ${name}[${cleanId}]`; +} + +function matchPluginLabels(lines, pluginKeys) { + if (!pluginKeys || typeof pluginKeys !== 'object' || 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 }); + } + + if (entriesByKey.size === 0) return []; + + const sortedKeys = [...entriesByKey.keys()].sort( + (a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0), + ); + const alternatives = sortedKeys.map(escapeRegExp).join('|'); + const selection = comparisonValue(lines.join(', ')); + const regex = new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); + + const labels = []; + let match; + while ((match = regex.exec(selection)) !== null) { + const entry = entriesByKey.get(match[1]); + if (!entry) continue; + const label = formatPluginLabel(entry.displayKey, entry.id); + if (label) labels.push(label); + } + return labels; +} + +function computeIssueLabels({ body, existingLabels = [], pluginKeys = {} }) { + const normalizedExisting = new Set( + (Array.isArray(existingLabels) ? existingLabels : []) + .filter(label => typeof label === 'string') + .map(comparisonValue), + ); + + const result = []; + const seen = new Set(); + const addLabel = label => { + if (!label || seen.has(label)) return; + seen.add(label); + result.push(label); + }; + + const pluginSection = extractSection(body, 'Plugin'); + if (normalizedExisting.has('bug') && pluginSection.present) { + 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'); + if (normalizedExisting.has('plugin request') && languageSection.present) { + const languageLines = nonEmptySectionLines(languageSection); + const rawLanguage = + languageLines.length > 0 ? comparisonValue(languageLines[0]) : ''; + const canonical = LANGUAGE_ALIASES.get(rawLanguage); + if (canonical) { + addLabel(`language: ${canonical}`); + } + } + + return result; +} + +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 labels = computeIssueLabels({ body, existingLabels, pluginKeys }); + process.stdout.write(`${JSON.stringify({ labels })}\n`); +} + +module.exports = { computeIssueLabels }; diff --git a/.github/scripts/auto-label-issue.test.cjs b/.github/scripts/auto-label-issue.test.cjs new file mode 100644 index 0000000000..ee7d5a5a13 --- /dev/null +++ b/.github/scripts/auto-label-issue.test.cjs @@ -0,0 +1,217 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const { computeIssueLabels } = require('./auto-label-issue.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( + computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + ["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( + computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + [ + '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( + computeIssueLabels({ body: withLrm, existingLabels: ['bug'], pluginKeys }), + ['severity: missing chapter', 'plugin: arnovel[arnovel]'], + ); + assert.deepEqual( + computeIssueLabels({ + body: withoutLrm, + existingLabels: ['bug'], + pluginKeys, + }), + ['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( + computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + ['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 = computeIssueLabels({ + body, + existingLabels: ['bug'], + pluginKeys, + }); + 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( + computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + ['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( + computeIssueLabels({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }), + [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( + computeIssueLabels({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }), + [], + ); + } +}); + +test('unrelated issue emits []', () => { + const body = [ + '### Feature Description', + '', + 'Add dark mode', + '', + '### Language', + '', + 'English', + ].join('\n'); + + assert.deepEqual( + computeIssueLabels({ + body, + existingLabels: ['feature request'], + pluginKeys, + }), + [], + ); +}); 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/generate-issue-index.cjs b/.github/scripts/generate-issue-index.cjs index 9cafd5b426..ef99824344 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, + comparisonValue, + escapeRegExp, + extractSection, +} = require('./issue-parsing.cjs'); function createLookups(pluginKeys) { const prototype = @@ -95,7 +68,7 @@ function resolveSelection(lines, lookups, issueNumber, warn) { .join(', '); const normalized = comparisonValue(selection); const alternatives = lookups.candidates - .map(candidate => candidate.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + .map(candidate => escapeRegExp(candidate.value)) .join('|'); if (!alternatives) return { ids: new Set(), unresolved: selection }; const regex = new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); 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/issue-parsing.cjs b/.github/scripts/issue-parsing.cjs new file mode 100644 index 0000000000..d1a330722f --- /dev/null +++ b/.github/scripts/issue-parsing.cjs @@ -0,0 +1,68 @@ +'use strict'; + +const DIRECTIONAL_CONTROLS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g; + +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 extractSection(body, headingName) { + 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: [] }; + + let end = start + 1; + while ( + end < lines.length && + !/^\s{0,3}#{1,6}(?:\s|$)/.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_', + ); +} + +module.exports = { + DIRECTIONAL_CONTROLS, + CATEGORY_CODES, + VALID_SEVERITIES, + stripDirectional, + comparisonValue, + escapeRegExp, + extractSection, + nonEmptySectionLines, +}; 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/issue_auto_label.yml b/.github/workflows/issue_auto_label.yml index 71f58f40e5..d6b61ea386 100644 --- a/.github/workflows/issue_auto_label.yml +++ b/.github/workflows/issue_auto_label.yml @@ -15,13 +15,15 @@ concurrency: 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 && ( + (contains(github.event.issue.labels.*.name, 'bug') && contains(github.event.issue.body, '### Plugin')) || + (contains(github.event.issue.labels.*.name, 'plugin request') && contains(github.event.issue.body, '### Language')) + ) }} runs-on: ubuntu-latest permissions: contents: read issues: write - env: - ISSUE_BODY: ${{ github.event.issue.body }} steps: - name: Checkout Repository @@ -29,69 +31,34 @@ 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" + node .github/scripts/auto-label-issue.cjs > "$RUNNER_TEMP/labels.json" + COUNT=$(jq '.labels | length' "$RUNNER_TEMP/labels.json") + echo "label_count=$COUNT" >> "$GITHUB_OUTPUT" - name: Add Labels To Issue - if: env.LABELS != '' + if: steps.determine-labels.outputs.label_count != '0' env: GH_TOKEN: ${{ github.token }} ISSUE_NUMBER: ${{ github.event.issue.number }} REPOSITORY: ${{ github.repository }} 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 - - - - name: Handle Missing Label - if: env.LABELS == '' - run: echo "No matching label found for the selected plugin." + while IFS= read -r label; do + [ -n "$label" ] || continue + gh api --method POST "repos/$REPOSITORY/labels" -f "name=$label" -f "color=ADD8E6" >/dev/null 2>&1 || true + done < <(jq -r '.labels[] | select(startswith("language: "))' "$RUNNER_TEMP/labels.json") + gh api --method POST "repos/$REPOSITORY/issues/$ISSUE_NUMBER/labels" --input "$RUNNER_TEMP/labels.json" + + - name: Log No Matching Labels + if: steps.determine-labels.outputs.label_count == '0' + run: echo "No matching labels found for the issue." diff --git a/.github/workflows/issue_moderator.yml b/.github/workflows/issue_moderator.yml index 38a1a4bf36..e504c8885e 100644 --- a/.github/workflows/issue_moderator.yml +++ b/.github/workflows/issue_moderator.yml @@ -26,31 +26,13 @@ jobs: duplicate-label: duplicate duplicate-check-enabled: true + # tachiyomiorg/issue-moderator-action@v2 checks duplicates on issues.opened using initial payload.issue.labels, + # so including both labels lets new plugin requests deduplicate against open domain-change reports too. duplicate-check-labels: | - ["plugin request", "domain changed"] + ["plugin request", "domain changed", "severity: domain changed"] existing-check-enabled: false - auto-close-rules: | - [ - { - "type": "body", - "regex": ".*DELETE THIS SECTION IF YOU HAVE READ AND ACKNOWLEDGED IT.*", - "message": "The acknowledgment section was not removed." - }, - { - "type": "body", - "regex": ".*\\* (LNReader version|Android version|Device): \\?.*", - "message": "Requested information in the template was not filled out." - }, - { - "type": "title", - "regex": ".*(Plugin name|Short description).*", - "message": "You did not fill out the description in the title" - } - ] - auto-close-ignore-label: do-not-autoclose - - name: Update moderated issue index if: ${{ always() && !cancelled() && !github.event.issue.pull_request }} env: diff --git a/.github/workflows/theme_auto_label.yml b/.github/workflows/theme_auto_label.yml index 5789a80b4b..4b7b670735 100644 --- a/.github/workflows/theme_auto_label.yml +++ b/.github/workflows/theme_auto_label.yml @@ -26,27 +26,35 @@ jobs: env: ISSUE_BODY: ${{ github.event.issue.body }} run: | - URL=$(echo "$ISSUE_BODY" | sed -n '/### Website URL/,+2p' | sed '1,2d' | tr -d '[:space:]') - echo "URL=$URL" >> $GITHUB_OUTPUT - echo "Using URL: \`$URL\`" >> $GITHUB_STEP_SUMMARY + URL=$(printf '%s\n' "$ISSUE_BODY" | tr -d '\r' | awk '/### Website URL/ {f=1; next} f && /^### / {exit} f && NF {print; exit}' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//') + if [ "$URL" = "_No response_" ]; then + URL="" + fi + echo "URL=$URL" >> "$GITHUB_OUTPUT" + echo "Using URL: \`$URL\`" >> "$GITHUB_STEP_SUMMARY" - name: Get Base URL id: get_base_url env: URL: ${{ steps.get_url.outputs.URL }} run: | - BASE_URL=$(echo "$URL" | sed 's/https\?:\/\///' | cut -d'/' -f1) - echo "BASE_URL=$BASE_URL" >> $GITHUB_OUTPUT - echo "Using Base URL: \`$BASE_URL\`" >> $GITHUB_STEP_SUMMARY + BASE_URL=$(printf '%s' "$URL" | sed -E 's#^https?://##; s#[/?#].*$##') + if [[ ! "$BASE_URL" =~ ^[A-Za-z0-9.-]+\.([A-Za-z]{2,}|xn--[A-Za-z0-9-]{2,})(:[0-9]+)?$ ]]; then + BASE_URL="" + fi + echo "BASE_URL=$BASE_URL" >> "$GITHUB_OUTPUT" + echo "Using Base URL: \`$BASE_URL\`" >> "$GITHUB_STEP_SUMMARY" - name: Get User Agent id: get_user_agent + if: steps.get_base_url.outputs.BASE_URL != '' run: | CHROME_VERSION=$(curl -s https://chromiumdash.appspot.com/fetch_releases?channel=Stable\&platform=Windows\&num=1 | jq -r '.[0].version // "126.0.6478.36"') echo "USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$CHROME_VERSION Safari/537.36" >> $GITHUB_OUTPUT - name: Check Madara Theme id: check_madara + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} @@ -62,8 +70,8 @@ jobs: fi - name: Check Lightnovelwp Theme - id: check_lighnovelwp - if: always() + id: check_lightnovelwp + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} @@ -71,16 +79,16 @@ jobs: echo "🔍 Checking for Lightnovelwp theme..." >> $GITHUB_STEP_SUMMARY if curl --location --output /dev/null --silent --head --fail --max-time 10 "https://$BASE_URL/wp-content/themes/lightnovel/style.css" -H "User-Agent: $USER_AGENT" 2>/dev/null || \ curl --location --output /dev/null --silent --head --fail --max-time 10 "http://$BASE_URL/wp-content/themes/lightnovel/style.css" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - echo "lighnovelwp=true" >> $GITHUB_OUTPUT + echo "lightnovelwp=true" >> $GITHUB_OUTPUT echo "✅ Lightnovelwp Theme Detected" >> $GITHUB_STEP_SUMMARY else - echo "lighnovelwp=false" >> $GITHUB_OUTPUT + echo "lightnovelwp=false" >> $GITHUB_OUTPUT echo "❌ Lightnovelwp Theme Not Found" >> $GITHUB_STEP_SUMMARY fi - name: Check HotNovelPub Theme id: check_hotnovelpub - if: always() + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} @@ -97,7 +105,7 @@ jobs: - name: Check Fictioneer Theme id: check_fictioneer - if: always() + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} @@ -114,7 +122,7 @@ jobs: - name: Check Novel Fire Theme id: check_novel_fire - if: always() + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} @@ -129,44 +137,63 @@ jobs: echo "❌ Novel Fire Theme Not Found" >> $GITHUB_STEP_SUMMARY fi + - name: Check Readwn Theme + id: check_readwn + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' + env: + BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} + USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} + run: | + echo "🔍 Checking for Readwn theme..." >> $GITHUB_STEP_SUMMARY + if curl --location --silent --fail --max-time 10 "https://$BASE_URL/list/all/all-newstime-0.html" -H "User-Agent: $USER_AGENT" 2>/dev/null | grep -q 'novel-item' || \ + curl --location --silent --fail --max-time 10 "http://$BASE_URL/list/all/all-newstime-0.html" -H "User-Agent: $USER_AGENT" 2>/dev/null | grep -q 'novel-item'; then + echo "readwn=true" >> $GITHUB_OUTPUT + echo "✅ Readwn Theme Detected" >> $GITHUB_STEP_SUMMARY + else + echo "readwn=false" >> $GITHUB_OUTPUT + echo "❌ Readwn Theme Not Found" >> $GITHUB_STEP_SUMMARY + fi + - name: Add Theme Label To Issue id: add_theme_label - if: always() + if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: MADARA: ${{ steps.check_madara.outputs.madara }} - LIGHNOVELWP: ${{ steps.check_lighnovelwp.outputs.lighnovelwp }} + LIGHTNOVELWP: ${{ steps.check_lightnovelwp.outputs.lightnovelwp }} HOTNOVELPUB: ${{ steps.check_hotnovelpub.outputs.hotnovelpub }} FICTIONEER: ${{ steps.check_fictioneer.outputs.fictioneer }} NOVEL_FIRE: ${{ steps.check_novel_fire.outputs.novel_fire }} + READWN: ${{ steps.check_readwn.outputs.readwn }} GH_TOKEN: ${{ github.token }} run: | - MATCH_COUNT=0 - [[ "$MADARA" == "true" ]] && ((MATCH_COUNT+=1)) - [[ "$LIGHNOVELWP" == "true" ]] && ((MATCH_COUNT+=1)) - [[ "$HOTNOVELPUB" == "true" ]] && ((MATCH_COUNT+=1)) - [[ "$FICTIONEER" == "true" ]] && ((MATCH_COUNT+=1)) - [[ "$NOVEL_FIRE" == "true" ]] && ((MATCH_COUNT+=1)) + MATCHED=() + [[ "$MADARA" == "true" ]] && MATCHED+=("theme: madara") + [[ "$LIGHTNOVELWP" == "true" ]] && MATCHED+=("theme: lightnovelwp") + [[ "$HOTNOVELPUB" == "true" ]] && MATCHED+=("theme: hotnovelpub") + [[ "$FICTIONEER" == "true" ]] && MATCHED+=("theme: fictioneer") + [[ "$NOVEL_FIRE" == "true" ]] && MATCHED+=("theme: novel fire") + [[ "$READWN" == "true" ]] && MATCHED+=("theme: readwn") - echo "## Theme Detection Result" >> $GITHUB_STEP_SUMMARY - if (( MATCH_COUNT > 1 )); then - echo "⚠️ Multiple themes detected ($MATCH_COUNT)." >> $GITHUB_STEP_SUMMARY - else - if [[ "$MADARA" == "true" ]]; then - echo "🏷️ Adding label: theme: madara" >> $GITHUB_STEP_SUMMARY - gh issue edit $ISSUE_NUMBER --add-label "theme: madara" -R $REPO - elif [[ "$LIGHNOVELWP" == "true" ]]; then - echo "🏷️ Adding label: theme: lighnovelwp" >> $GITHUB_STEP_SUMMARY - gh issue edit $ISSUE_NUMBER --add-label "theme: lighnovelwp" -R $REPO - elif [[ "$HOTNOVELPUB" == "true" ]]; then - echo "🏷️ Adding label: theme: hotnovelpub" >> $GITHUB_STEP_SUMMARY - gh issue edit $ISSUE_NUMBER --add-label "theme: hotnovelpub" -R $REPO - elif [[ "$FICTIONEER" == "true" ]]; then - echo "🏷️ Adding label: theme: fictioneer" >> $GITHUB_STEP_SUMMARY - gh issue edit $ISSUE_NUMBER --add-label "theme: fictioneer" -R $REPO - elif [[ "$NOVEL_FIRE" == "true" ]]; then - echo "🏷️ Adding label: theme: novel fire" >> $GITHUB_STEP_SUMMARY - gh issue edit $ISSUE_NUMBER --add-label "theme: novel fire" -R $REPO - else - echo "❌ No Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "## Theme Detection Result" >> "$GITHUB_STEP_SUMMARY" + if (( ${#MATCHED[@]} > 1 )); then + echo "⚠️ Multiple themes detected (${#MATCHED[@]})." >> "$GITHUB_STEP_SUMMARY" + elif (( ${#MATCHED[@]} == 1 )); then + THEME_LABEL="${MATCHED[0]}" + if [ "$THEME_LABEL" = "theme: lightnovelwp" ]; then + if ! gh api "repos/$REPO/labels/theme%3A%20lightnovelwp" >/dev/null 2>&1; then + if gh api "repos/$REPO/labels/theme%3A%20lighnovelwp" >/dev/null 2>&1; then + THEME_LABEL="theme: lighnovelwp" + else + gh api --method POST "repos/$REPO/labels" \ + -f "name=theme: lightnovelwp" \ + -f "color=D4C5F9" \ + -f "description=Site uses Lightnovelwp theme" >/dev/null 2>&1 || true + fi + fi fi + echo "🏷️ Adding label: $THEME_LABEL" >> "$GITHUB_STEP_SUMMARY" + jq -n --arg label "$THEME_LABEL" '{labels: [$label]}' \ + | gh api --method POST "repos/$REPO/issues/$ISSUE_NUMBER/labels" --input - + else + echo "❌ No Theme Detected" >> "$GITHUB_STEP_SUMMARY" fi From 919429310c34230abc2f5ab6b33827c21cb6b12f Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:07:25 +0700 Subject: [PATCH 2/7] chore(github): wire script tests, cjs lint-staged, and repo map pointer --- .github/workflows/github-scripts-check.yml | 65 ++++++++++++++++++++++ .husky/pre-commit | 3 - AGENTS.md | 1 + package.json | 3 +- 4 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/github-scripts-check.yml diff --git a/.github/workflows/github-scripts-check.yml b/.github/workflows/github-scripts-check.yml new file mode 100644 index 0000000000..b6d6b36f86 --- /dev/null +++ b/.github/workflows/github-scripts-check.yml @@ -0,0 +1,65 @@ +name: GitHub Scripts & Templates Check + +on: + pull_request: + 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 + permissions: + contents: read + + steps: + - name: Checkout Repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Setup Node.js + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: '24' + + - name: Run GitHub Script Tests + run: node --test .github/scripts/*.test.cjs + + - name: Validate GitHub YAML Files + run: | + python3 - <<'PY' + import glob + import sys + import yaml + + paths = sorted( + glob.glob('.github/workflows/*.yml') + + glob.glob('.github/ISSUE_TEMPLATE/*.yml') + + ['.github/scripts/blank_report_issue.yml'] + ) + + failed = False + for path in paths: + try: + with open(path, encoding='utf-8') as fh: + content = fh.read() + if path == '.github/scripts/blank_report_issue.yml': + content = content.replace('{#CHANGE#}', '- "English: Example"') + yaml.safe_load(content) + except Exception as exc: + print(f'Invalid YAML in {path}: {exc}', file=sys.stderr) + failed = True + + if failed: + sys.exit(1) + print(f'Validated {len(paths)} YAML files.') + PY diff --git a/.husky/pre-commit b/.husky/pre-commit index 36af219892..2312dc587f 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - npx lint-staged diff --git a/AGENTS.md b/AGENTS.md index b2e191a3cb..c465efb77f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`). ## Environment & package management diff --git a/package.json b/package.json index 8946218eb8..0e40fe8a45 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "format:check": "prettier --check \"./**/*.{js,ts}\"", "check:sites": "node scripts/check-plugin-sites.js", "check:plugin": "node scripts/live-check-plugin.js", + "test:scripts": "node --test .github/scripts/*.test.cjs", "prepare": "husky" }, "author": "LNReader", @@ -95,7 +96,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" ] From de8221839dbaeeabcdab21b47ec91144086aca18 Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:02:22 +0700 Subject: [PATCH 3/7] fix(github): harden auto-label, theme, moderator, and scripts CI --- .github/ISSUE_TEMPLATE/report_issue.yml | 4 +- .github/scripts/auto-label-issue.cjs | 144 ++++++++++++++--- .github/scripts/auto-label-issue.test.cjs | 179 ++++++++++++++++++++- .github/workflows/github-scripts-check.yml | 137 +++++++++++++++- .github/workflows/issue_auto_label.yml | 55 +++++-- .github/workflows/issue_moderator.yml | 51 +++++- .github/workflows/theme_auto_label.yml | 149 +++++++++++------ 7 files changed, 630 insertions(+), 89 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/report_issue.yml b/.github/ISSUE_TEMPLATE/report_issue.yml index 78cb387fe5..129bbb1e7c 100644 --- a/.github/ISSUE_TEMPLATE/report_issue.yml +++ b/.github/ISSUE_TEMPLATE/report_issue.yml @@ -448,7 +448,7 @@ body: label: LNReader Version description: Find this in **More → About**. placeholder: | - Example: "2.0.0" + Example: "2.1.4" validations: required: true @@ -490,7 +490,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/auto-label-issue.cjs b/.github/scripts/auto-label-issue.cjs index 0358881438..879408a05f 100644 --- a/.github/scripts/auto-label-issue.cjs +++ b/.github/scripts/auto-label-issue.cjs @@ -10,6 +10,8 @@ const { nonEmptySectionLines, } = require('./issue-parsing.cjs'); +const MAX_LABEL_LENGTH = 50; + const LANGUAGE_ALIASES = new Map([ // Arabic ['arabic', 'arabic'], @@ -21,6 +23,10 @@ const LANGUAGE_ALIASES = new Map([ ['bangla', 'bengali'], ['bn', 'bengali'], ['বাংলা', 'bengali'], + // Burmese + ['burmese', 'burmese'], + ['my', 'burmese'], + ['မြန်မာ', 'burmese'], // Chinese ['chinese', 'chinese'], ['zh', 'chinese'], @@ -32,6 +38,20 @@ const LANGUAGE_ALIASES = new Map([ ['漢語', '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'], @@ -41,6 +61,20 @@ const LANGUAGE_ALIASES = new Map([ ['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'], @@ -61,6 +95,15 @@ const LANGUAGE_ALIASES = new Map([ ['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'], @@ -71,6 +114,11 @@ const LANGUAGE_ALIASES = new Map([ ['pt-br', 'portuguese'], ['português', 'portuguese'], ['portugues', 'portuguese'], + // Romanian + ['romanian', 'romanian'], + ['ro', 'romanian'], + ['română', 'romanian'], + ['romana', 'romanian'], // Russian ['russian', 'russian'], ['ru', 'russian'], @@ -103,13 +151,30 @@ const LANGUAGE_ALIASES = new Map([ ['tieng viet', 'vietnamese'], ]); +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; - return `plugin: ${name}[${cleanId}]`; + 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}`; + } + return `plugin: ${suffix}`.slice(0, MAX_LABEL_LENGTH); } function matchPluginLabels(lines, pluginKeys) { @@ -145,23 +210,24 @@ function matchPluginLabels(lines, pluginKeys) { return labels; } -function computeIssueLabels({ body, existingLabels = [], pluginKeys = {} }) { - const normalizedExisting = new Set( - (Array.isArray(existingLabels) ? existingLabels : []) - .filter(label => typeof label === 'string') - .map(comparisonValue), - ); +function computeLabelPlan({ body, existingLabels = [], pluginKeys = {} }) { + const rawExisting = ( + Array.isArray(existingLabels) ? existingLabels : [] + ).filter(label => typeof label === 'string'); + const normalizedExisting = new Set(rawExisting.map(comparisonValue)); - const result = []; - const seen = new Set(); + const desired = []; + const seenDesired = new Set(); const addLabel = label => { - if (!label || seen.has(label)) return; - seen.add(label); - result.push(label); + const normalized = comparisonValue(label); + if (!normalized || seenDesired.has(normalized)) return; + seenDesired.add(normalized); + desired.push(label); }; const pluginSection = extractSection(body, 'Plugin'); - if (normalizedExisting.has('bug') && pluginSection.present) { + const manageBug = normalizedExisting.has('bug') && pluginSection.present; + if (manageBug) { const severityLines = nonEmptySectionLines( extractSection(body, 'Severity'), ); @@ -179,17 +245,55 @@ function computeIssueLabels({ body, existingLabels = [], pluginKeys = {} }) { } const languageSection = extractSection(body, 'Language'); - if (normalizedExisting.has('plugin request') && languageSection.present) { + const manageLanguage = + normalizedExisting.has('plugin request') && languageSection.present; + if (manageLanguage) { const languageLines = nonEmptySectionLines(languageSection); const rawLanguage = languageLines.length > 0 ? comparisonValue(languageLines[0]) : ''; - const canonical = LANGUAGE_ALIASES.get(rawLanguage); + const canonical = resolveLanguageAlias(rawLanguage); if (canonical) { addLabel(`language: ${canonical}`); } } - return result; + const isManagedLabel = normalized => { + if ( + manageBug && + (normalized === 'plugin:' || + normalized.startsWith('plugin: ') || + normalized.startsWith('severity: ')) + ) { + return true; + } + return manageLanguage && normalized.startsWith('language: '); + }; + + 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 }; +} + +function computeIssueLabels(args) { + return computeLabelPlan(args).desired; } if (require.main === module) { @@ -197,8 +301,10 @@ if (require.main === module) { const pluginKeys = JSON.parse(fs.readFileSync(keysPath, 'utf8')); const body = process.env.ISSUE_BODY || ''; const existingLabels = JSON.parse(process.env.ISSUE_LABELS || '[]'); - const labels = computeIssueLabels({ body, existingLabels, pluginKeys }); - process.stdout.write(`${JSON.stringify({ labels })}\n`); + const plan = computeLabelPlan({ body, existingLabels, pluginKeys }); + process.stdout.write( + `${JSON.stringify({ labels: plan.add, add: plan.add, remove: plan.remove })}\n`, + ); } -module.exports = { computeIssueLabels }; +module.exports = { computeIssueLabels, computeLabelPlan, formatPluginLabel }; diff --git a/.github/scripts/auto-label-issue.test.cjs b/.github/scripts/auto-label-issue.test.cjs index ee7d5a5a13..d52f10c871 100644 --- a/.github/scripts/auto-label-issue.test.cjs +++ b/.github/scripts/auto-label-issue.test.cjs @@ -4,8 +4,12 @@ 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 { computeIssueLabels } = require('./auto-label-issue.cjs'); +const { + computeIssueLabels, + computeLabelPlan, +} = require('./auto-label-issue.cjs'); const pluginKeys = JSON.parse( fs.readFileSync(path.join(__dirname, 'keys.json'), 'utf8'), @@ -215,3 +219,176 @@ test('unrelated issue emits []', () => { [], ); }); + +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 = computeIssueLabels({ + body, + existingLabels: ['bug'], + pluginKeys, + }); + 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( + computeIssueLabels({ + body: longestBody, + existingLabels: ['bug'], + pluginKeys, + }), + ['severity: other', 'plugin: taxingcorn117…[taxingcorn117stranslations]'], + ); +}); + +test('computeLabelPlan reconciles stale severity, plugin, and language labels on edited issues', () => { + 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'], + }, + ); +}); + +test('plugin request issue supports expanded language aliases and delimited primary language', () => { + const cases = [ + ['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( + computeIssueLabels({ + body, + existingLabels: ['plugin request'], + pluginKeys, + }), + expected, + ); + } +}); + +test('auto-label-issue CLI outputs labels, 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), { + labels: ['severity: missing chapter', 'plugin: novel fire[novelfire]'], + add: ['severity: missing chapter', 'plugin: novel fire[novelfire]'], + remove: ['severity: other'], + }); +}); diff --git a/.github/workflows/github-scripts-check.yml b/.github/workflows/github-scripts-check.yml index b6d6b36f86..be5c641d80 100644 --- a/.github/workflows/github-scripts-check.yml +++ b/.github/workflows/github-scripts-check.yml @@ -3,6 +3,8 @@ name: GitHub Scripts & Templates Check on: pull_request: branches: [master] + push: + branches: [master] paths: - '.github/**' workflow_dispatch: @@ -17,6 +19,7 @@ jobs: check: name: Validate GitHub Scripts & YAML runs-on: ubuntu-latest + timeout-minutes: 10 permissions: contents: read @@ -24,27 +27,90 @@ jobs: - 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: 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 - - name: Validate GitHub YAML Files + - 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: | + python3 -c 'import yaml' 2>/dev/null || python3 -m pip install --quiet PyYAML==6.0.2 python3 - <<'PY' import glob + import json + 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, + ) + paths = sorted( - glob.glob('.github/workflows/*.yml') - + glob.glob('.github/ISSUE_TEMPLATE/*.yml') - + ['.github/scripts/blank_report_issue.yml'] + set( + glob.glob('.github/workflows/*.yml') + + glob.glob('.github/workflows/*.yaml') + + glob.glob('.github/ISSUE_TEMPLATE/*.yml') + + glob.glob('.github/ISSUE_TEMPLATE/*.yaml') + + ['.github/scripts/blank_report_issue.yml'] + ) ) failed = False @@ -54,12 +120,71 @@ jobs: content = fh.read() if path == '.github/scripts/blank_report_issue.yml': content = content.replace('{#CHANGE#}', '- "English: Example"') - yaml.safe_load(content) + data = yaml.load(content, Loader=UniqueKeyLoader) + if path.startswith('.github/ISSUE_TEMPLATE/') and os.path.basename(path) not in ('config.yml', 'config.yaml'): + 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') except Exception as exc: print(f'Invalid YAML in {path}: {exc}', file=sys.stderr) failed = True + try: + with open('.github/scripts/blank_report_issue.yml', encoding='utf-8') as fh: + blank = fh.read() + with open('.github/scripts/keys.json', encoding='utf-8') as fh: + keys = list(json.load(fh).keys()) + with open('.github/ISSUE_TEMPLATE/report_issue.yml', encoding='utf-8') as fh: + actual_report = fh.read() + rendered = blank.replace('{#CHANGE#}', '- "' + '"\n - "'.join(keys) + '"') + yaml.load(rendered, Loader=UniqueKeyLoader) + if rendered != actual_report: + print( + 'Drift detected: .github/ISSUE_TEMPLATE/report_issue.yml does not match blank_report_issue.yml + keys.json', + file=sys.stderr, + ) + failed = True + except Exception as exc: + print(f'Template sync check failed: {exc}', file=sys.stderr) + failed = True + if failed: sys.exit(1) - print(f'Validated {len(paths)} YAML files.') + print(f'Validated {len(paths)} YAML files and issue template sync.') PY + + - 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 + # Exclude untouched upstream workflow with pre-existing SC2086 notice + [ "$(basename "$wf")" = "publish-plugins.yml" ] && continue + WORKFLOWS+=("$wf") + done + # Ignore 2 pre-existing upstream workflow notices unrelated to PR changes: + # - generate-issue-index.yml uses concurrency.queue (beta/unsupported in actionlint schema) + # - lint.yml uses reviewdog/action-eslint@v1 deprecated fail_on_error input + "$BIN_DIR/actionlint" \ + -ignore 'unexpected key "queue" for "concurrency" section' \ + -ignore 'avoid using deprecated input "fail_on_error" in action "reviewdog/action-eslint@v1"' \ + "${WORKFLOWS[@]}" diff --git a/.github/workflows/issue_auto_label.yml b/.github/workflows/issue_auto_label.yml index d6b61ea386..fc2c71f0cf 100644 --- a/.github/workflows/issue_auto_label.yml +++ b/.github/workflows/issue_auto_label.yml @@ -5,6 +5,7 @@ on: types: - opened - edited + - labeled permissions: {} @@ -16,11 +17,16 @@ jobs: auto-label: name: Auto Label Issues if: >- - ${{ github.event.issue.body && ( - (contains(github.event.issue.labels.*.name, 'bug') && contains(github.event.issue.body, '### Plugin')) || - (contains(github.event.issue.labels.*.name, 'plugin request') && contains(github.event.issue.body, '### Language')) - ) }} + ${{ + 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 @@ -43,22 +49,45 @@ jobs: ISSUE_LABELS: ${{ toJSON(github.event.issue.labels.*.name) }} run: | node .github/scripts/auto-label-issue.cjs > "$RUNNER_TEMP/labels.json" - COUNT=$(jq '.labels | length' "$RUNNER_TEMP/labels.json") - echo "label_count=$COUNT" >> "$GITHUB_OUTPUT" + 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: Add Labels To Issue - if: steps.determine-labels.outputs.label_count != '0' + - 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: | while IFS= read -r label; do [ -n "$label" ] || continue - gh api --method POST "repos/$REPOSITORY/labels" -f "name=$label" -f "color=ADD8E6" >/dev/null 2>&1 || true - done < <(jq -r '.labels[] | select(startswith("language: "))' "$RUNNER_TEMP/labels.json") - gh api --method POST "repos/$REPOSITORY/issues/$ISSUE_NUMBER/labels" --input "$RUNNER_TEMP/labels.json" + 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: Log No Matching Labels - if: steps.determine-labels.outputs.label_count == '0' - run: echo "No matching labels found for the issue." + 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/.github/workflows/issue_moderator.yml b/.github/workflows/issue_moderator.yml index e504c8885e..3cee92d66b 100644 --- a/.github/workflows/issue_moderator.yml +++ b/.github/workflows/issue_moderator.yml @@ -12,15 +12,16 @@ concurrency: jobs: autoclose: - name: Auto Close Invalid Issues + name: Moderate Issues runs-on: ubuntu-latest + timeout-minutes: 5 permissions: issues: write pull-requests: write actions: write steps: - name: Moderate Issues - uses: tachiyomiorg/issue-moderator-action@v2 + uses: tachiyomiorg/issue-moderator-action@32a31ab12ad6e68ebf4c65408f47bef132d4fd3c # v2 with: repo-token: ${{ secrets.GITHUB_TOKEN }} duplicate-label: duplicate @@ -37,12 +38,58 @@ jobs: if: ${{ always() && !cancelled() && !github.event.issue.pull_request }} env: GH_TOKEN: ${{ github.token }} + GITHUB_API_URL: ${{ github.api_url }} REPOSITORY: ${{ github.repository }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} ISSUE_NUMBER: ${{ github.event.issue.number }} + EVENT_ISSUE_STATE: ${{ github.event.issue.state }} + EVENT_ISSUE_LABELS: ${{ toJSON(github.event.issue.labels.*.name) }} shell: bash run: | set -euo pipefail + NEEDS_DISPATCH=$(node <<'NODE' + const normalizeLabels = labels => + [...new Set((Array.isArray(labels) ? labels : []).map(l => String(l).trim().toLowerCase()))].sort(); + + async function main() { + const url = `${process.env.GITHUB_API_URL}/repos/${process.env.REPOSITORY}/issues/${process.env.ISSUE_NUMBER}`; + const response = await fetch(url, { + redirect: 'manual', + headers: { + Authorization: `Bearer ${process.env.GH_TOKEN}`, + Accept: 'application/vnd.github+json', + 'User-Agent': 'lnreader-issue-moderator', + }, + }); + if (response.status === 404 || response.status === 410) { + process.stdout.write('true'); + return; + } + if (response.status !== 200) { + throw new Error(`Issue lookup failed with HTTP ${response.status}.`); + } + const issue = await response.json(); + const currentLabels = normalizeLabels( + Array.isArray(issue.labels) ? issue.labels.map(l => (typeof l === 'string' ? l : l && l.name)) : [], + ); + const eventLabels = normalizeLabels(JSON.parse(process.env.EVENT_ISSUE_LABELS || '[]')); + const stateChanged = issue.state !== process.env.EVENT_ISSUE_STATE; + const labelsChanged = JSON.stringify(currentLabels) !== JSON.stringify(eventLabels); + process.stdout.write(stateChanged || labelsChanged ? 'true' : 'false'); + } + + main().catch(err => { + process.stderr.write(`${err.message}\n`); + process.exitCode = 1; + }); + NODE + ) + + if [ "$NEEDS_DISPATCH" != "true" ]; then + echo "No moderator state/label changes; skipping issue index dispatch." + exit 0 + fi + jq -n --arg ref "$DEFAULT_BRANCH" --arg number "$ISSUE_NUMBER" \ '{ref: $ref, inputs: {issue_number: $number}}' \ | gh api --method POST "repos/$REPOSITORY/actions/workflows/generate-issue-index.yml/dispatches" --input - diff --git a/.github/workflows/theme_auto_label.yml b/.github/workflows/theme_auto_label.yml index 4b7b670735..ddc860fee6 100644 --- a/.github/workflows/theme_auto_label.yml +++ b/.github/workflows/theme_auto_label.yml @@ -2,7 +2,7 @@ name: Auto Theme Labeler on: issues: - types: [labeled] + types: [labeled, edited] permissions: {} @@ -13,8 +13,13 @@ concurrency: jobs: auto-label: name: Auto Label Theme - if: contains(github.event.issue.labels.*.name, 'plugin request') + if: >- + ${{ + contains(github.event.issue.labels.*.name, 'plugin request') && + (github.event.action != 'labeled' || github.event.label.name == 'plugin request') + }} runs-on: ubuntu-latest + timeout-minutes: 5 permissions: issues: write env: @@ -41,6 +46,11 @@ jobs: BASE_URL=$(printf '%s' "$URL" | sed -E 's#^https?://##; s#[/?#].*$##') if [[ ! "$BASE_URL" =~ ^[A-Za-z0-9.-]+\.([A-Za-z]{2,}|xn--[A-Za-z0-9-]{2,})(:[0-9]+)?$ ]]; then BASE_URL="" + else + HOST_ONLY=$(printf '%s' "${BASE_URL%%:*}" | tr '[:upper:]' '[:lower:]') + if [[ "$HOST_ONLY" == "localhost" || "$HOST_ONLY" == *.localhost || "$HOST_ONLY" == *.local || "$HOST_ONLY" == *.internal ]]; then + BASE_URL="" + fi fi echo "BASE_URL=$BASE_URL" >> "$GITHUB_OUTPUT" echo "Using Base URL: \`$BASE_URL\`" >> "$GITHUB_STEP_SUMMARY" @@ -49,8 +59,9 @@ jobs: id: get_user_agent if: steps.get_base_url.outputs.BASE_URL != '' run: | - CHROME_VERSION=$(curl -s https://chromiumdash.appspot.com/fetch_releases?channel=Stable\&platform=Windows\&num=1 | jq -r '.[0].version // "126.0.6478.36"') - echo "USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$CHROME_VERSION Safari/537.36" >> $GITHUB_OUTPUT + CHROME_VERSION=$(curl --silent --max-time 10 'https://chromiumdash.appspot.com/fetch_releases?channel=Stable&platform=Windows&num=1' | jq -r '.[0].version // empty' || true) + CHROME_VERSION="${CHROME_VERSION:-126.0.6478.36}" + echo "USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$CHROME_VERSION Safari/537.36" >> "$GITHUB_OUTPUT" - name: Check Madara Theme id: check_madara @@ -59,14 +70,21 @@ jobs: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for Madara theme..." >> $GITHUB_STEP_SUMMARY - if curl --location --output /dev/null --silent --head --fail --max-time 10 "https://$BASE_URL/wp-content/themes/madara/style.css" -H "User-Agent: $USER_AGENT" 2>/dev/null || \ - curl --location --output /dev/null --silent --head --fail --max-time 10 "http://$BASE_URL/wp-content/themes/madara/style.css" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - echo "madara=true" >> $GITHUB_OUTPUT - echo "✅ Madara Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "🔍 Checking for Madara theme..." >> "$GITHUB_STEP_SUMMARY" + check_head() { + local url="$1" meta code ctype + meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) + IFS=$'\t' read -r code ctype <<< "$meta" + ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') + [[ "$code" == "200" && "$ctype" == *"text/css"* ]] + } + if check_head "https://$BASE_URL/wp-content/themes/madara/style.css" || \ + check_head "http://$BASE_URL/wp-content/themes/madara/style.css"; then + echo "madara=true" >> "$GITHUB_OUTPUT" + echo "✅ Madara Theme Detected" >> "$GITHUB_STEP_SUMMARY" else - echo "madara=false" >> $GITHUB_OUTPUT - echo "❌ Madara Theme Not Found" >> $GITHUB_STEP_SUMMARY + echo "madara=false" >> "$GITHUB_OUTPUT" + echo "❌ Madara Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - name: Check Lightnovelwp Theme @@ -76,14 +94,21 @@ jobs: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for Lightnovelwp theme..." >> $GITHUB_STEP_SUMMARY - if curl --location --output /dev/null --silent --head --fail --max-time 10 "https://$BASE_URL/wp-content/themes/lightnovel/style.css" -H "User-Agent: $USER_AGENT" 2>/dev/null || \ - curl --location --output /dev/null --silent --head --fail --max-time 10 "http://$BASE_URL/wp-content/themes/lightnovel/style.css" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - echo "lightnovelwp=true" >> $GITHUB_OUTPUT - echo "✅ Lightnovelwp Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "🔍 Checking for Lightnovelwp theme..." >> "$GITHUB_STEP_SUMMARY" + check_head() { + local url="$1" meta code ctype + meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) + IFS=$'\t' read -r code ctype <<< "$meta" + ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') + [[ "$code" == "200" && "$ctype" == *"text/css"* ]] + } + if check_head "https://$BASE_URL/wp-content/themes/lightnovel/style.css" || \ + check_head "http://$BASE_URL/wp-content/themes/lightnovel/style.css"; then + echo "lightnovelwp=true" >> "$GITHUB_OUTPUT" + echo "✅ Lightnovelwp Theme Detected" >> "$GITHUB_STEP_SUMMARY" else - echo "lightnovelwp=false" >> $GITHUB_OUTPUT - echo "❌ Lightnovelwp Theme Not Found" >> $GITHUB_STEP_SUMMARY + echo "lightnovelwp=false" >> "$GITHUB_OUTPUT" + echo "❌ Lightnovelwp Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - name: Check HotNovelPub Theme @@ -93,14 +118,23 @@ jobs: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for HotNovelPub theme..." >> $GITHUB_STEP_SUMMARY - if curl --location --silent --fail --max-time 10 "https://api.$BASE_URL" -H "User-Agent: $USER_AGENT" 2>/dev/null | grep -q "Hello\!" || \ - curl --location --silent --fail --max-time 10 "http://api.$BASE_URL" -H "User-Agent: $USER_AGENT" 2>/dev/null | grep -q "Hello\!"; then - echo "hotnovelpub=true" >> $GITHUB_OUTPUT - echo "✅ HotNovelPub Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "🔍 Checking for HotNovelPub theme..." >> "$GITHUB_STEP_SUMMARY" + fetch_and_grep() { + local url="$1" out_file="$RUNNER_TEMP/hotnovelpub.txt" + rm -f "$out_file" + if curl --location --max-redirs 5 --silent --fail --max-time 10 --max-filesize 2097152 -o "$out_file" "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null; then + grep -q "Hello!" "$out_file" + return $? + fi + return 1 + } + if fetch_and_grep "https://api.$BASE_URL" || \ + fetch_and_grep "http://api.$BASE_URL"; then + echo "hotnovelpub=true" >> "$GITHUB_OUTPUT" + echo "✅ HotNovelPub Theme Detected" >> "$GITHUB_STEP_SUMMARY" else - echo "hotnovelpub=false" >> $GITHUB_OUTPUT - echo "❌ HotNovelPub Theme Not Found" >> $GITHUB_STEP_SUMMARY + echo "hotnovelpub=false" >> "$GITHUB_OUTPUT" + echo "❌ HotNovelPub Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - name: Check Fictioneer Theme @@ -110,14 +144,21 @@ jobs: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for Fictioneer theme..." >> $GITHUB_STEP_SUMMARY - if curl --location --output /dev/null --silent --head --fail --max-time 10 "https://$BASE_URL/wp-content/themes/fictioneer/css/application.css" -H "User-Agent: $USER_AGENT" 2>/dev/null || \ - curl --location --output /dev/null --silent --head --fail --max-time 10 "http://$BASE_URL/wp-content/themes/fictioneer/css/application.css" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - echo "fictioneer=true" >> $GITHUB_OUTPUT - echo "✅ Fictioneer Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "🔍 Checking for Fictioneer theme..." >> "$GITHUB_STEP_SUMMARY" + check_head() { + local url="$1" meta code ctype + meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) + IFS=$'\t' read -r code ctype <<< "$meta" + ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') + [[ "$code" == "200" && "$ctype" == *"text/css"* ]] + } + if check_head "https://$BASE_URL/wp-content/themes/fictioneer/css/application.css" || \ + check_head "http://$BASE_URL/wp-content/themes/fictioneer/css/application.css"; then + echo "fictioneer=true" >> "$GITHUB_OUTPUT" + echo "✅ Fictioneer Theme Detected" >> "$GITHUB_STEP_SUMMARY" else - echo "fictioneer=false" >> $GITHUB_OUTPUT - echo "❌ Fictioneer Theme Not Found" >> $GITHUB_STEP_SUMMARY + echo "fictioneer=false" >> "$GITHUB_OUTPUT" + echo "❌ Fictioneer Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - name: Check Novel Fire Theme @@ -127,14 +168,21 @@ jobs: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for Novel Fire theme..." >> $GITHUB_STEP_SUMMARY - if curl --location --output /dev/null --silent --head --fail --max-time 10 "https://$BASE_URL/frontend/js/appsettings.min.js" -H "User-Agent: $USER_AGENT" 2>/dev/null || \ - curl --location --output /dev/null --silent --head --fail --max-time 10 "http://$BASE_URL/frontend/js/appsettings.min.js" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - echo "novel_fire=true" >> $GITHUB_OUTPUT - echo "✅ Novel Fire Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "🔍 Checking for Novel Fire theme..." >> "$GITHUB_STEP_SUMMARY" + check_head() { + local url="$1" meta code ctype + meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) + IFS=$'\t' read -r code ctype <<< "$meta" + ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') + [[ "$code" == "200" && "$ctype" == *"javascript"* ]] + } + if check_head "https://$BASE_URL/frontend/js/appsettings.min.js" || \ + check_head "http://$BASE_URL/frontend/js/appsettings.min.js"; then + echo "novel_fire=true" >> "$GITHUB_OUTPUT" + echo "✅ Novel Fire Theme Detected" >> "$GITHUB_STEP_SUMMARY" else - echo "novel_fire=false" >> $GITHUB_OUTPUT - echo "❌ Novel Fire Theme Not Found" >> $GITHUB_STEP_SUMMARY + echo "novel_fire=false" >> "$GITHUB_OUTPUT" + echo "❌ Novel Fire Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - name: Check Readwn Theme @@ -144,14 +192,23 @@ jobs: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for Readwn theme..." >> $GITHUB_STEP_SUMMARY - if curl --location --silent --fail --max-time 10 "https://$BASE_URL/list/all/all-newstime-0.html" -H "User-Agent: $USER_AGENT" 2>/dev/null | grep -q 'novel-item' || \ - curl --location --silent --fail --max-time 10 "http://$BASE_URL/list/all/all-newstime-0.html" -H "User-Agent: $USER_AGENT" 2>/dev/null | grep -q 'novel-item'; then - echo "readwn=true" >> $GITHUB_OUTPUT - echo "✅ Readwn Theme Detected" >> $GITHUB_STEP_SUMMARY + echo "🔍 Checking for Readwn theme..." >> "$GITHUB_STEP_SUMMARY" + fetch_and_grep() { + local url="$1" out_file="$RUNNER_TEMP/readwn.html" + rm -f "$out_file" + if curl --location --max-redirs 5 --silent --fail --max-time 10 --max-filesize 2097152 -o "$out_file" "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null; then + grep -q 'novel-item' "$out_file" + return $? + fi + return 1 + } + if fetch_and_grep "https://$BASE_URL/list/all/all-newstime-0.html" || \ + fetch_and_grep "http://$BASE_URL/list/all/all-newstime-0.html"; then + echo "readwn=true" >> "$GITHUB_OUTPUT" + echo "✅ Readwn Theme Detected" >> "$GITHUB_STEP_SUMMARY" else - echo "readwn=false" >> $GITHUB_OUTPUT - echo "❌ Readwn Theme Not Found" >> $GITHUB_STEP_SUMMARY + echo "readwn=false" >> "$GITHUB_OUTPUT" + echo "❌ Readwn Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - name: Add Theme Label To Issue From 4d13027e0cb7953db256c8562fb3df43e349f3da Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:14:23 +0700 Subject: [PATCH 4/7] fix(github): address code review findings in workflows and script CI Co-Authored-By: Antigravity --- .github/ISSUE_TEMPLATE/report_issue.yml | 4 +- .github/scripts/auto-label-issue.cjs | 28 ++- .github/scripts/auto-label-issue.test.cjs | 107 +++++++--- .github/scripts/generate-issue-index.cjs | 11 +- .../generate-issue-template-options.cjs | 27 ++- .github/scripts/issue-parsing.cjs | 10 + .github/workflows/github-scripts-check.yml | 60 +++--- .github/workflows/theme_auto_label.yml | 186 +++++------------- .husky/pre-commit | 3 + 9 files changed, 204 insertions(+), 232 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/report_issue.yml b/.github/ISSUE_TEMPLATE/report_issue.yml index 129bbb1e7c..78cb387fe5 100644 --- a/.github/ISSUE_TEMPLATE/report_issue.yml +++ b/.github/ISSUE_TEMPLATE/report_issue.yml @@ -448,7 +448,7 @@ body: label: LNReader Version description: Find this in **More → About**. placeholder: | - Example: "2.1.4" + Example: "2.0.0" validations: required: true @@ -490,7 +490,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](https://github.com/LNReader/lnreader/releases/latest)**. + - 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)**. required: true - label: I have updated all installed plugins to the latest version. required: true diff --git a/.github/scripts/auto-label-issue.cjs b/.github/scripts/auto-label-issue.cjs index 879408a05f..f4ec58eb7b 100644 --- a/.github/scripts/auto-label-issue.cjs +++ b/.github/scripts/auto-label-issue.cjs @@ -4,8 +4,8 @@ const fs = require('node:fs'); const path = require('node:path'); const { VALID_SEVERITIES, + buildSelectionMatcher, comparisonValue, - escapeRegExp, extractSection, nonEmptySectionLines, } = require('./issue-parsing.cjs'); @@ -151,6 +151,10 @@ const LANGUAGE_ALIASES = new Map([ ['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); @@ -174,7 +178,8 @@ function formatPluginLabel(displayKey, id) { const truncated = name.slice(0, maxNameLen - 1).trimEnd(); if (truncated) return `plugin: ${truncated}…${suffix}`; } - return `plugin: ${suffix}`.slice(0, MAX_LABEL_LENGTH); + const maxIdLen = MAX_LABEL_LENGTH - 'plugin: []'.length; + return `plugin: [${cleanId.slice(0, maxIdLen)}]`; } function matchPluginLabels(lines, pluginKeys) { @@ -190,14 +195,9 @@ function matchPluginLabels(lines, pluginKeys) { entriesByKey.set(normalizedKey, { displayKey, id }); } - if (entriesByKey.size === 0) return []; - - const sortedKeys = [...entriesByKey.keys()].sort( - (a, b) => b.length - a.length || (a < b ? -1 : a > b ? 1 : 0), - ); - const alternatives = sortedKeys.map(escapeRegExp).join('|'); + const regex = buildSelectionMatcher(entriesByKey.keys()); + if (!regex) return []; const selection = comparisonValue(lines.join(', ')); - const regex = new RegExp(`(?:^|, )(${alternatives})(?=, |$)`, 'g'); const labels = []; let match; @@ -266,7 +266,7 @@ function computeLabelPlan({ body, existingLabels = [], pluginKeys = {} }) { ) { return true; } - return manageLanguage && normalized.startsWith('language: '); + return manageLanguage && MANAGED_LANGUAGE_LABELS.has(normalized); }; const add = desired.filter( @@ -292,10 +292,6 @@ function computeLabelPlan({ body, existingLabels = [], pluginKeys = {} }) { return { desired, add, remove }; } -function computeIssueLabels(args) { - return computeLabelPlan(args).desired; -} - if (require.main === module) { const keysPath = path.join(__dirname, 'keys.json'); const pluginKeys = JSON.parse(fs.readFileSync(keysPath, 'utf8')); @@ -303,8 +299,8 @@ if (require.main === module) { const existingLabels = JSON.parse(process.env.ISSUE_LABELS || '[]'); const plan = computeLabelPlan({ body, existingLabels, pluginKeys }); process.stdout.write( - `${JSON.stringify({ labels: plan.add, add: plan.add, remove: plan.remove })}\n`, + `${JSON.stringify({ add: plan.add, remove: plan.remove })}\n`, ); } -module.exports = { computeIssueLabels, computeLabelPlan, formatPluginLabel }; +module.exports = { computeLabelPlan }; diff --git a/.github/scripts/auto-label-issue.test.cjs b/.github/scripts/auto-label-issue.test.cjs index d52f10c871..4b287134db 100644 --- a/.github/scripts/auto-label-issue.test.cjs +++ b/.github/scripts/auto-label-issue.test.cjs @@ -6,10 +6,10 @@ const fs = require('node:fs'); const path = require('node:path'); const { execFileSync } = require('node:child_process'); +const { computeLabelPlan } = require('./auto-label-issue.cjs'); const { - computeIssueLabels, - computeLabelPlan, -} = require('./auto-label-issue.cjs'); + renderIssueTemplate, +} = require('./generate-issue-template-options.cjs'); const pluginKeys = JSON.parse( fs.readFileSync(path.join(__dirname, 'keys.json'), 'utf8'), @@ -27,7 +27,7 @@ test('bug issue with single English plugin and valid severity', () => { ].join('\n'); assert.deepEqual( - computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, ["severity: can't load novels", 'plugin: novel fire[novelfire]'], ); }); @@ -44,7 +44,7 @@ test('bug issue with comma-containing Chinese and Korean plugin keys', () => { ].join('\n'); assert.deepEqual( - computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, [ 'severity: wrong formatting', 'plugin: 69书吧[69shu]', @@ -75,15 +75,16 @@ test('bug issue with Arabic plugin with or without leading LRM directional contr ].join('\n'); assert.deepEqual( - computeIssueLabels({ body: withLrm, existingLabels: ['bug'], pluginKeys }), + computeLabelPlan({ body: withLrm, existingLabels: ['bug'], pluginKeys }) + .desired, ['severity: missing chapter', 'plugin: arnovel[arnovel]'], ); assert.deepEqual( - computeIssueLabels({ + computeLabelPlan({ body: withoutLrm, existingLabels: ['bug'], pluginKeys, - }), + }).desired, ['severity: missing chapter', 'plugin: arnovel[arnovel]'], ); }); @@ -100,7 +101,7 @@ test('bug issue with colon inside plugin name preserves colon after language pre ].join('\n'); assert.deepEqual( - computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, ['severity: wrong content', 'plugin: re:library[relib]'], ); }); @@ -127,11 +128,11 @@ test('bug issue with unmatched plugin or _No response_ never emits bare plugin: ].join('\n'); for (const body of [staleBody, noResponseBody]) { - const labels = computeIssueLabels({ + const labels = computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys, - }); + }).desired; assert.deepEqual(labels, ['severity: other']); assert.ok(!labels.some(label => label.trim() === 'plugin:')); } @@ -152,7 +153,7 @@ test('bug issue handles CRLF line endings and extra blank lines', () => { ].join('\r\n'); assert.deepEqual( - computeIssueLabels({ body, existingLabels: ['bug'], pluginKeys }), + computeLabelPlan({ body, existingLabels: ['bug'], pluginKeys }).desired, ['severity: domain changed', 'plugin: novelbuddy[novelbuddy]'], ); }); @@ -168,11 +169,11 @@ test('plugin request issue maps non-English language names and native aliases', for (const [languageInput, expectedLabel] of cases) { const body = ['### Language', '', languageInput].join('\n'); assert.deepEqual( - computeIssueLabels({ + computeLabelPlan({ body, existingLabels: ['plugin request'], pluginKeys, - }), + }).desired, [expectedLabel], ); } @@ -189,11 +190,11 @@ test('plugin request issue with English, Multi, empty, _No response_, or unrecog ]) { const body = ['### Language', '', languageInput].join('\n'); assert.deepEqual( - computeIssueLabels({ + computeLabelPlan({ body, existingLabels: ['plugin request'], pluginKeys, - }), + }).desired, [], ); } @@ -211,11 +212,11 @@ test('unrelated issue emits []', () => { ].join('\n'); assert.deepEqual( - computeIssueLabels({ + computeLabelPlan({ body, existingLabels: ['feature request'], pluginKeys, - }), + }).desired, [], ); }); @@ -232,11 +233,11 @@ test('all plugin labels in keys.json stay within GitHub 50-character limit and p 'Other', ].join('\n'); - const labels = computeIssueLabels({ + 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; @@ -259,16 +260,37 @@ test('all plugin labels in keys.json stay within GitHub 50-character limit and p 'Other', ].join('\n'); assert.deepEqual( - computeIssueLabels({ + 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 severity, plugin, and language labels on edited issues', () => { +test('computeLabelPlan reconciles stale labels and preserves unlisted manual language labels', () => { const editedBugBody = [ '### Plugin', '', @@ -344,10 +366,30 @@ test('computeLabelPlan reconciles stale severity, plugin, and language labels on remove: ['language: arabic'], }, ); + + assert.deepEqual( + computeLabelPlan({ + body: '### Language\n\nSwedish', + existingLabels: ['plugin request', 'language: swedish'], + pluginKeys, + }), + { + desired: [], + add: [], + remove: [], + }, + ); }); -test('plugin request issue supports expanded language aliases and delimited primary language', () => { +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']], @@ -361,17 +403,17 @@ test('plugin request issue supports expanded language aliases and delimited prim for (const [languageInput, expected] of cases) { const body = ['### Language', '', languageInput].join('\n'); assert.deepEqual( - computeIssueLabels({ + computeLabelPlan({ body, existingLabels: ['plugin request'], pluginKeys, - }), + }).desired, expected, ); } }); -test('auto-label-issue CLI outputs labels, add, and remove JSON', () => { +test('auto-label-issue CLI outputs add and remove JSON', () => { const stdout = execFileSync( process.execPath, [path.join(__dirname, 'auto-label-issue.cjs')], @@ -387,8 +429,17 @@ test('auto-label-issue CLI outputs labels, add, and remove JSON', () => { ); assert.deepEqual(JSON.parse(stdout), { - labels: ['severity: missing chapter', 'plugin: novel fire[novelfire]'], 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/generate-issue-index.cjs b/.github/scripts/generate-issue-index.cjs index ef99824344..f2985b3de2 100644 --- a/.github/scripts/generate-issue-index.cjs +++ b/.github/scripts/generate-issue-index.cjs @@ -3,8 +3,8 @@ const fs = require('node:fs'); const { CATEGORY_CODES, + buildSelectionMatcher, comparisonValue, - escapeRegExp, extractSection, } = require('./issue-parsing.cjs'); @@ -67,11 +67,10 @@ function resolveSelection(lines, lookups, issueNumber, warn) { .filter(Boolean) .join(', '); const normalized = comparisonValue(selection); - const alternatives = lookups.candidates - .map(candidate => escapeRegExp(candidate.value)) - .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-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 index d1a330722f..14167865e4 100644 --- a/.github/scripts/issue-parsing.cjs +++ b/.github/scripts/issue-parsing.cjs @@ -25,6 +25,15 @@ 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) { const lines = String(body || '') .replace(/\r\n?/g, '\n') @@ -63,6 +72,7 @@ module.exports = { stripDirectional, comparisonValue, escapeRegExp, + buildSelectionMatcher, extractSection, nonEmptySectionLines, }; diff --git a/.github/workflows/github-scripts-check.yml b/.github/workflows/github-scripts-check.yml index be5c641d80..7392096346 100644 --- a/.github/workflows/github-scripts-check.yml +++ b/.github/workflows/github-scripts-check.yml @@ -73,10 +73,18 @@ jobs: - 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 - <<'PY' import glob - import json import os import sys import yaml @@ -103,13 +111,19 @@ jobs: construct_mapping_no_duplicates, ) + rendered_report = os.path.join(os.environ['RUNNER_TEMP'], 'rendered-report-issue.yml') + 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') - + glob.glob('.github/ISSUE_TEMPLATE/*.yml') - + glob.glob('.github/ISSUE_TEMPLATE/*.yaml') - + ['.github/scripts/blank_report_issue.yml'] + + issue_templates + + [rendered_report] ) ) @@ -118,10 +132,15 @@ jobs: try: with open(path, encoding='utf-8') as fh: content = fh.read() - if path == '.github/scripts/blank_report_issue.yml': - content = content.replace('{#CHANGE#}', '- "English: Example"') data = yaml.load(content, Loader=UniqueKeyLoader) - if path.startswith('.github/ISSUE_TEMPLATE/') and os.path.basename(path) not in ('config.yml', 'config.yaml'): + is_issue_form = ( + path == rendered_report + or ( + path.startswith('.github/ISSUE_TEMPLATE/') + and os.path.basename(path) not in ('config.yml', 'config.yaml') + ) + ) + if is_issue_form: if not isinstance(data, dict): raise ValueError('Issue template must be a YAML mapping') for field in ('name', 'description'): @@ -138,28 +157,9 @@ jobs: print(f'Invalid YAML in {path}: {exc}', file=sys.stderr) failed = True - try: - with open('.github/scripts/blank_report_issue.yml', encoding='utf-8') as fh: - blank = fh.read() - with open('.github/scripts/keys.json', encoding='utf-8') as fh: - keys = list(json.load(fh).keys()) - with open('.github/ISSUE_TEMPLATE/report_issue.yml', encoding='utf-8') as fh: - actual_report = fh.read() - rendered = blank.replace('{#CHANGE#}', '- "' + '"\n - "'.join(keys) + '"') - yaml.load(rendered, Loader=UniqueKeyLoader) - if rendered != actual_report: - print( - 'Drift detected: .github/ISSUE_TEMPLATE/report_issue.yml does not match blank_report_issue.yml + keys.json', - file=sys.stderr, - ) - failed = True - except Exception as exc: - print(f'Template sync check failed: {exc}', file=sys.stderr) - failed = True - if failed: sys.exit(1) - print(f'Validated {len(paths)} YAML files and issue template sync.') + print(f'Validated {len(paths)} YAML files (including rendered blank_report_issue.yml).') PY - name: Run actionlint @@ -177,7 +177,6 @@ jobs: shopt -s nullglob WORKFLOWS=() for wf in .github/workflows/*.yml .github/workflows/*.yaml; do - # Exclude untouched upstream workflow with pre-existing SC2086 notice [ "$(basename "$wf")" = "publish-plugins.yml" ] && continue WORKFLOWS+=("$wf") done @@ -188,3 +187,8 @@ jobs: -ignore 'unexpected key "queue" for "concurrency" section' \ -ignore 'avoid using deprecated input "fail_on_error" in action "reviewdog/action-eslint@v1"' \ "${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 diff --git a/.github/workflows/theme_auto_label.yml b/.github/workflows/theme_auto_label.yml index ddc860fee6..bdee0d08af 100644 --- a/.github/workflows/theme_auto_label.yml +++ b/.github/workflows/theme_auto_label.yml @@ -43,7 +43,7 @@ jobs: env: URL: ${{ steps.get_url.outputs.URL }} run: | - BASE_URL=$(printf '%s' "$URL" | sed -E 's#^https?://##; s#[/?#].*$##') + BASE_URL=$(printf '%s' "$URL" | sed -E 's#^[Hh][Tt][Tt][Pp][Ss]?://##; s#[/?#].*$##') if [[ ! "$BASE_URL" =~ ^[A-Za-z0-9.-]+\.([A-Za-z]{2,}|xn--[A-Za-z0-9-]{2,})(:[0-9]+)?$ ]]; then BASE_URL="" else @@ -63,179 +63,81 @@ jobs: CHROME_VERSION="${CHROME_VERSION:-126.0.6478.36}" echo "USER_AGENT=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$CHROME_VERSION Safari/537.36" >> "$GITHUB_OUTPUT" - - name: Check Madara Theme - id: check_madara + - name: Detect Website Theme + id: detect_theme if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} run: | - echo "🔍 Checking for Madara theme..." >> "$GITHUB_STEP_SUMMARY" check_head() { - local url="$1" meta code ctype + local url="$1" expected_ct="$2" meta code ctype meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) IFS=$'\t' read -r code ctype <<< "$meta" ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') - [[ "$code" == "200" && "$ctype" == *"text/css"* ]] + [[ "$code" == "200" && "$ctype" == *"$expected_ct"* ]] } - if check_head "https://$BASE_URL/wp-content/themes/madara/style.css" || \ - check_head "http://$BASE_URL/wp-content/themes/madara/style.css"; then - echo "madara=true" >> "$GITHUB_OUTPUT" - echo "✅ Madara Theme Detected" >> "$GITHUB_STEP_SUMMARY" - else - echo "madara=false" >> "$GITHUB_OUTPUT" - echo "❌ Madara Theme Not Found" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Check Lightnovelwp Theme - id: check_lightnovelwp - if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' - env: - BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} - USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} - run: | - echo "🔍 Checking for Lightnovelwp theme..." >> "$GITHUB_STEP_SUMMARY" - check_head() { - local url="$1" meta code ctype - meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) - IFS=$'\t' read -r code ctype <<< "$meta" - ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') - [[ "$code" == "200" && "$ctype" == *"text/css"* ]] - } - if check_head "https://$BASE_URL/wp-content/themes/lightnovel/style.css" || \ - check_head "http://$BASE_URL/wp-content/themes/lightnovel/style.css"; then - echo "lightnovelwp=true" >> "$GITHUB_OUTPUT" - echo "✅ Lightnovelwp Theme Detected" >> "$GITHUB_STEP_SUMMARY" - else - echo "lightnovelwp=false" >> "$GITHUB_OUTPUT" - echo "❌ Lightnovelwp Theme Not Found" >> "$GITHUB_STEP_SUMMARY" - fi - - name: Check HotNovelPub Theme - id: check_hotnovelpub - if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' - env: - BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} - USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} - run: | - echo "🔍 Checking for HotNovelPub theme..." >> "$GITHUB_STEP_SUMMARY" fetch_and_grep() { - local url="$1" out_file="$RUNNER_TEMP/hotnovelpub.txt" + local url="$1" pattern="$2" out_file="$3" rm -f "$out_file" if curl --location --max-redirs 5 --silent --fail --max-time 10 --max-filesize 2097152 -o "$out_file" "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - grep -q "Hello!" "$out_file" + grep -q "$pattern" "$out_file" return $? fi return 1 } - if fetch_and_grep "https://api.$BASE_URL" || \ - fetch_and_grep "http://api.$BASE_URL"; then - echo "hotnovelpub=true" >> "$GITHUB_OUTPUT" - echo "✅ HotNovelPub Theme Detected" >> "$GITHUB_STEP_SUMMARY" - else - echo "hotnovelpub=false" >> "$GITHUB_OUTPUT" - echo "❌ HotNovelPub Theme Not Found" >> "$GITHUB_STEP_SUMMARY" - fi - - name: Check Fictioneer Theme - id: check_fictioneer - if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' - env: - BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} - USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} - run: | - echo "🔍 Checking for Fictioneer theme..." >> "$GITHUB_STEP_SUMMARY" - check_head() { - local url="$1" meta code ctype - meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) - IFS=$'\t' read -r code ctype <<< "$meta" - ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') - [[ "$code" == "200" && "$ctype" == *"text/css"* ]] - } - if check_head "https://$BASE_URL/wp-content/themes/fictioneer/css/application.css" || \ - check_head "http://$BASE_URL/wp-content/themes/fictioneer/css/application.css"; then - echo "fictioneer=true" >> "$GITHUB_OUTPUT" - echo "✅ Fictioneer Theme Detected" >> "$GITHUB_STEP_SUMMARY" - else - echo "fictioneer=false" >> "$GITHUB_OUTPUT" - echo "❌ Fictioneer Theme Not Found" >> "$GITHUB_STEP_SUMMARY" - fi + MATCHED=() - - name: Check Novel Fire Theme - id: check_novel_fire - if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' - env: - BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} - USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} - run: | - echo "🔍 Checking for Novel Fire theme..." >> "$GITHUB_STEP_SUMMARY" - check_head() { - local url="$1" meta code ctype - meta=$(curl --location --max-redirs 5 --output /dev/null --silent --head --max-time 10 -w '%{http_code}\t%{content_type}' "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null || true) - IFS=$'\t' read -r code ctype <<< "$meta" - ctype=$(printf '%s' "$ctype" | tr '[:upper:]' '[:lower:]') - [[ "$code" == "200" && "$ctype" == *"javascript"* ]] + probe_head() { + local name="$1" label="$2" path="$3" expected_ct="$4" + echo "🔍 Checking for $name theme..." >> "$GITHUB_STEP_SUMMARY" + if check_head "https://$BASE_URL$path" "$expected_ct" || \ + check_head "http://$BASE_URL$path" "$expected_ct"; then + MATCHED+=("$label") + echo "✅ $name Theme Detected" >> "$GITHUB_STEP_SUMMARY" + else + echo "❌ $name Theme Not Found" >> "$GITHUB_STEP_SUMMARY" + fi } - if check_head "https://$BASE_URL/frontend/js/appsettings.min.js" || \ - check_head "http://$BASE_URL/frontend/js/appsettings.min.js"; then - echo "novel_fire=true" >> "$GITHUB_OUTPUT" - echo "✅ Novel Fire Theme Detected" >> "$GITHUB_STEP_SUMMARY" - else - echo "novel_fire=false" >> "$GITHUB_OUTPUT" - echo "❌ Novel Fire Theme Not Found" >> "$GITHUB_STEP_SUMMARY" - fi - - name: Check Readwn Theme - id: check_readwn - if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' - env: - BASE_URL: ${{ steps.get_base_url.outputs.BASE_URL }} - USER_AGENT: ${{ steps.get_user_agent.outputs.USER_AGENT }} - run: | - echo "🔍 Checking for Readwn theme..." >> "$GITHUB_STEP_SUMMARY" - fetch_and_grep() { - local url="$1" out_file="$RUNNER_TEMP/readwn.html" - rm -f "$out_file" - if curl --location --max-redirs 5 --silent --fail --max-time 10 --max-filesize 2097152 -o "$out_file" "$url" -H "User-Agent: $USER_AGENT" 2>/dev/null; then - grep -q 'novel-item' "$out_file" - return $? + probe_body() { + local name="$1" label="$2" host="$3" path="$4" pattern="$5" out_file="$6" + echo "🔍 Checking for $name theme..." >> "$GITHUB_STEP_SUMMARY" + if fetch_and_grep "https://$host$path" "$pattern" "$out_file" || \ + fetch_and_grep "http://$host$path" "$pattern" "$out_file"; then + MATCHED+=("$label") + echo "✅ $name Theme Detected" >> "$GITHUB_STEP_SUMMARY" + else + echo "❌ $name Theme Not Found" >> "$GITHUB_STEP_SUMMARY" fi - return 1 } - if fetch_and_grep "https://$BASE_URL/list/all/all-newstime-0.html" || \ - fetch_and_grep "http://$BASE_URL/list/all/all-newstime-0.html"; then - echo "readwn=true" >> "$GITHUB_OUTPUT" - echo "✅ Readwn Theme Detected" >> "$GITHUB_STEP_SUMMARY" - else - echo "readwn=false" >> "$GITHUB_OUTPUT" - echo "❌ Readwn Theme Not Found" >> "$GITHUB_STEP_SUMMARY" - fi + + probe_head "Madara" "theme: madara" "/wp-content/themes/madara/style.css" "text/css" + probe_head "Lightnovelwp" "theme: lightnovelwp" "/wp-content/themes/lightnovel/style.css" "text/css" + probe_body "HotNovelPub" "theme: hotnovelpub" "api.$BASE_URL" "" "Hello!" "$RUNNER_TEMP/hotnovelpub.txt" + probe_head "Fictioneer" "theme: fictioneer" "/wp-content/themes/fictioneer/css/application.css" "text/css" + probe_head "Novel Fire" "theme: novel fire" "/frontend/js/appsettings.min.js" "javascript" + probe_body "Readwn" "theme: readwn" "$BASE_URL" "/list/all/all-newstime-0.html" "novel-item" "$RUNNER_TEMP/readwn.html" + + { + echo "match_count=${#MATCHED[@]}" + echo "theme_label=${MATCHED[0]:-}" + } >> "$GITHUB_OUTPUT" - name: Add Theme Label To Issue id: add_theme_label if: always() && !cancelled() && steps.get_base_url.outputs.BASE_URL != '' env: - MADARA: ${{ steps.check_madara.outputs.madara }} - LIGHTNOVELWP: ${{ steps.check_lightnovelwp.outputs.lightnovelwp }} - HOTNOVELPUB: ${{ steps.check_hotnovelpub.outputs.hotnovelpub }} - FICTIONEER: ${{ steps.check_fictioneer.outputs.fictioneer }} - NOVEL_FIRE: ${{ steps.check_novel_fire.outputs.novel_fire }} - READWN: ${{ steps.check_readwn.outputs.readwn }} + MATCH_COUNT: ${{ steps.detect_theme.outputs.match_count }} + THEME_LABEL: ${{ steps.detect_theme.outputs.theme_label }} GH_TOKEN: ${{ github.token }} run: | - MATCHED=() - [[ "$MADARA" == "true" ]] && MATCHED+=("theme: madara") - [[ "$LIGHTNOVELWP" == "true" ]] && MATCHED+=("theme: lightnovelwp") - [[ "$HOTNOVELPUB" == "true" ]] && MATCHED+=("theme: hotnovelpub") - [[ "$FICTIONEER" == "true" ]] && MATCHED+=("theme: fictioneer") - [[ "$NOVEL_FIRE" == "true" ]] && MATCHED+=("theme: novel fire") - [[ "$READWN" == "true" ]] && MATCHED+=("theme: readwn") - echo "## Theme Detection Result" >> "$GITHUB_STEP_SUMMARY" - if (( ${#MATCHED[@]} > 1 )); then - echo "⚠️ Multiple themes detected (${#MATCHED[@]})." >> "$GITHUB_STEP_SUMMARY" - elif (( ${#MATCHED[@]} == 1 )); then - THEME_LABEL="${MATCHED[0]}" + if (( MATCH_COUNT > 1 )); then + echo "⚠️ Multiple themes detected ($MATCH_COUNT)." >> "$GITHUB_STEP_SUMMARY" + elif (( MATCH_COUNT == 1 )) && [ -n "$THEME_LABEL" ]; then if [ "$THEME_LABEL" = "theme: lightnovelwp" ]; then if ! gh api "repos/$REPO/labels/theme%3A%20lightnovelwp" >/dev/null 2>&1; then if gh api "repos/$REPO/labels/theme%3A%20lighnovelwp" >/dev/null 2>&1; then diff --git a/.husky/pre-commit b/.husky/pre-commit index 2312dc587f..36af219892 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + npx lint-staged From 9eceaad5b2f69fe24ba138bd01ea535e62fb6e2a Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:21:54 +0700 Subject: [PATCH 5/7] chore(github): guard generated report_issue.yml and test cleanliness in CI Co-Authored-By: Antigravity --- .github/workflows/github-scripts-check.yml | 17 ++++++++++++++++- AGENTS.md | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/workflows/github-scripts-check.yml b/.github/workflows/github-scripts-check.yml index 7392096346..de50eeb4ed 100644 --- a/.github/workflows/github-scripts-check.yml +++ b/.github/workflows/github-scripts-check.yml @@ -49,6 +49,15 @@ jobs: 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 @@ -58,7 +67,13 @@ jobs: - name: Run GitHub Script Tests if: steps.scope.outputs.run_checks == 'true' - run: node --test .github/scripts/*.test.cjs + 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' diff --git a/AGENTS.md b/AGENTS.md index c465efb77f..f15cad0846 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ ## Navigation pointers -- `CODING_STANDARDS.md` — coding, plugin, multisrc migration, and PR review standards (consult during review and before adding/migrating plugins). +- `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 scripts (`lint`, `format:check`, `build:compile`, `build:full`, `dev:start`, `check:plugin`, `check:sites`). - `README.md`, `docs/quickstart.md`, `docs/docs.md`, `docs/testing.md`, `docs/plugin-template.ts` — setup, plugin API, live checker, and starter template. From d4c472cc3e68d82b56cf813cafe9e037af9b2338 Mon Sep 17 00:00:00 2001 From: 7ui77 <7ui77@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:36:43 +0700 Subject: [PATCH 6/7] feat(github): auto-close issues not following issue templates --- .github/scripts/validate-issue-template.cjs | 284 +++++++++++ .../scripts/validate-issue-template.test.cjs | 450 ++++++++++++++++++ .github/workflows/issue_moderator.yml | 44 ++ 3 files changed, 778 insertions(+) create mode 100644 .github/scripts/validate-issue-template.cjs create mode 100644 .github/scripts/validate-issue-template.test.cjs diff --git a/.github/scripts/validate-issue-template.cjs b/.github/scripts/validate-issue-template.cjs new file mode 100644 index 0000000000..6b4e5e6f15 --- /dev/null +++ b/.github/scripts/validate-issue-template.cjs @@ -0,0 +1,284 @@ +'use strict'; + +const { + comparisonValue, + extractSection, + nonEmptySectionLines, + stripDirectional, +} = require('./issue-parsing.cjs'); + +const EXEMPT_ASSOCIATIONS = new Set(['owner', 'member', 'collaborator']); + +const TEMPLATES = [ + { + name: 'Report Issue', + label: 'bug', + requiredSections: [ + 'Plugin', + 'Severity', + 'Steps To Reproduce', + 'Expected Behavior', + 'Actual Behavior', + 'LNReader Version', + 'Plugin Version', + 'Android Version', + ], + requiredAcknowledgements: 5, + }, + { + name: 'Request Plugin', + label: 'plugin request', + requiredSections: ['Plugin Name', 'Website URL', 'Language'], + requiredAcknowledgements: 4, + }, + { + name: 'Request Feature', + label: 'feature request', + requiredSections: ['Feature Description'], + requiredAcknowledgements: 5, + }, +]; + +function checkAcknowledgements(body, expectedCount) { + const section = extractSection(body, 'Acknowledgements'); + if (!section.present) { + return ['Missing required section: `Acknowledgements`.']; + } + + let checked = 0; + let unchecked = 0; + for (const line of section.lines) { + const trimmed = stripDirectional(line).trim(); + if (/^[-*]\s+\[[xX]\]\s+\S/.test(trimmed)) { + checked += 1; + } else if (/^[-*]\s+\[\s*\]\s+\S/.test(trimmed)) { + unchecked += 1; + } + } + + if (unchecked > 0) { + return ['All required checkboxes in `Acknowledgements` must be checked.']; + } + if (checked < expectedCount) { + return [ + `Incomplete \`Acknowledgements\` section (expected at least ${expectedCount} checked items).`, + ]; + } + return []; +} + +function evaluateTemplate(body, template) { + let matchedSections = 0; + const missingOrEmpty = []; + + for (const heading of template.requiredSections) { + const section = extractSection(body, heading); + if (section.present) { + matchedSections += 1; + } + if (!section.present || nonEmptySectionLines(section).length === 0) { + missingOrEmpty.push(heading); + } + } + + const reasons = []; + if (missingOrEmpty.length > 0) { + const formatted = missingOrEmpty + .map(heading => `\`${heading}\``) + .join(', '); + reasons.push(`Missing or empty required section(s): ${formatted}.`); + } + reasons.push( + ...checkAcknowledgements(body, template.requiredAcknowledgements), + ); + + return { + template: template.name, + valid: reasons.length === 0, + matchedSections, + missingOrEmpty, + reasons, + }; +} + +function buildCloseComment({ author, repository, templateName, reasons }) { + const safeAuthor = + typeof author === 'string' && + /^[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(author) + ? author + : ''; + const mention = safeAuthor ? `@${safeAuthor} ` : ''; + + const safeRepo = + typeof repository === 'string' && + /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._-]+$/.test(repository) + ? repository + : ''; + const chooseUrl = safeRepo + ? `https://github.com/${safeRepo}/issues/new/choose` + : ''; + + const intro = templateName + ? `${mention}this issue was automatically closed because it does not match the **${templateName}** template requirements:` + : `${mention}this issue was automatically closed because it does not follow one of the repository's issue templates:`; + + const bulletList = reasons.map(reason => `- ${reason}`).join('\n'); + const instructions = chooseUrl + ? `Please open a new issue using one of the [issue templates](${chooseUrl}) and fill out all required fields.` + : "Please open a new issue using one of the repository's issue templates and fill out all required fields."; + + return [ + intro, + '', + bulletList, + '', + instructions, + '', + '*If you believe this was closed in error, please comment below so a maintainer can review and reopen it.*', + ].join('\n'); +} + +function validateIssueTemplate({ + body = '', + labels = [], + author = '', + authorAssociation = '', + authorType = '', + state = 'open', + repository = '', +} = {}) { + if (comparisonValue(state) !== 'open') { + return { + shouldClose: false, + skipped: 'not-open', + template: null, + reasons: [], + comment: '', + }; + } + + if ( + EXEMPT_ASSOCIATIONS.has(comparisonValue(authorAssociation)) || + comparisonValue(authorType) === 'bot' + ) { + return { + shouldClose: false, + skipped: 'exempt-author', + template: null, + reasons: [], + comment: '', + }; + } + + const normalizedLabels = new Set( + (Array.isArray(labels) ? labels : []) + .filter(label => typeof label === 'string') + .map(comparisonValue) + .filter(Boolean), + ); + + const labeledTemplates = TEMPLATES.filter(template => + normalizedLabels.has(template.label), + ); + + if (labeledTemplates.length > 0) { + const evaluations = labeledTemplates.map(template => + evaluateTemplate(body, template), + ); + const validMatch = evaluations.find(evaluation => evaluation.valid); + if (validMatch) { + return { + shouldClose: false, + skipped: null, + template: validMatch.template, + reasons: [], + comment: '', + }; + } + + evaluations.sort( + (a, b) => + a.reasons.length - b.reasons.length || + b.matchedSections - a.matchedSections, + ); + const best = evaluations[0]; + return { + shouldClose: true, + skipped: null, + template: best.template, + reasons: best.reasons, + comment: buildCloseComment({ + author, + repository, + templateName: best.template, + reasons: best.reasons, + }), + }; + } + + const evaluations = TEMPLATES.map(template => + evaluateTemplate(body, template), + ); + const validMatch = evaluations.find(evaluation => evaluation.valid); + if (validMatch) { + return { + shouldClose: false, + skipped: null, + template: validMatch.template, + reasons: [], + comment: '', + }; + } + + evaluations.sort( + (a, b) => + b.matchedSections - a.matchedSections || + a.reasons.length - b.reasons.length, + ); + const best = evaluations[0]; + if (best.matchedSections > 0) { + return { + shouldClose: true, + skipped: null, + template: best.template, + reasons: best.reasons, + comment: buildCloseComment({ + author, + repository, + templateName: best.template, + reasons: best.reasons, + }), + }; + } + + const reasons = [ + "The issue body does not use one of the repository's issue templates (Report Issue, Request Plugin, or Request Feature).", + ]; + return { + shouldClose: true, + skipped: null, + template: null, + reasons, + comment: buildCloseComment({ + author, + repository, + templateName: null, + reasons, + }), + }; +} + +if (require.main === module) { + const result = validateIssueTemplate({ + body: process.env.ISSUE_BODY || '', + labels: JSON.parse(process.env.ISSUE_LABELS || '[]'), + author: process.env.ISSUE_AUTHOR || '', + authorAssociation: process.env.ISSUE_AUTHOR_ASSOCIATION || '', + authorType: process.env.ISSUE_AUTHOR_TYPE || '', + state: process.env.ISSUE_STATE || 'open', + repository: process.env.REPOSITORY || '', + }); + process.stdout.write(`${JSON.stringify(result)}\n`); +} + +module.exports = { TEMPLATES, validateIssueTemplate }; diff --git a/.github/scripts/validate-issue-template.test.cjs b/.github/scripts/validate-issue-template.test.cjs new file mode 100644 index 0000000000..f87f73e51c --- /dev/null +++ b/.github/scripts/validate-issue-template.test.cjs @@ -0,0 +1,450 @@ +'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 { + TEMPLATES, + validateIssueTemplate, +} = require('./validate-issue-template.cjs'); + +const VALID_REPORT_ISSUE_BODY = [ + '### Plugin', + '', + 'English: Ranobes', + '', + '### Severity', + '', + "Can't Load Novels", + '', + '### Steps To Reproduce', + '', + 'chapter list wont load', + '', + '### Expected Behavior', + '', + 'it should load chapter list', + '', + '### Actual Behavior', + '', + 'its just empty cant see the chapters', + '', + '### LNReader Version', + '', + '2.1.4', + '', + '### Plugin Version', + '', + '2.0.3', + '', + '### Android Version', + '', + '13', + '', + '### Other Details', + '', + '_No response_', + '', + '### Acknowledgements', + '', + '- [x] I have searched existing issues and confirmed this is not a duplicate.', + '- [x] I have written a clear and descriptive title.', + '- [x] I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**.', + '- [x] I have updated all installed plugins to the latest version.', + '- [x] I understand that app-specific issues should be reported in the [app repository](https://github.com/LNReader/lnreader/issues/new/choose).', +].join('\n'); + +const VALID_PLUGIN_REQUEST_BODY = [ + '### Plugin Name', + '', + 'Puffberry', + '', + '### Website URL', + '', + 'https://example.com', + '', + '### Language', + '', + 'English', + '', + '### Other Details', + '', + '_No response_', + '', + '### Acknowledgements', + '', + '- [x] I have searched existing issues and confirmed this plugin has not been requested before.', + '- [x] I have used the plugin name as the issue title.', + '- [x] I have verified this plugin does not already exist in the [repository](https://github.com/LNReader/lnreader-plugins).', + '- [X] I have provided all requested information in this form.', +].join('\n'); + +const VALID_FEATURE_REQUEST_BODY = [ + '### Feature Description', + '', + 'Add a toggle to hide disabled books.', + '', + '### Other Details', + '', + '_No response_', + '', + '### Acknowledgements', + '', + '- [x] I have searched existing issues and confirmed this is not a duplicate.', + '- [x] I have written a clear and descriptive title.', + '- [x] I understand that app-specific features should be requested in the [app repository](https://github.com/LNReader/lnreader/issues/new/choose).', + '- [x] I have updated the app to the **[latest version](https://github.com/LNReader/lnreader/releases/latest)**.', + '- [x] I have provided all requested information in this form.', +].join('\n'); + +function parseIssueTemplateSchema(filePath) { + const lines = fs + .readFileSync(filePath, 'utf8') + .replace(/\r\n?/g, '\n') + .split('\n'); + let label = null; + const requiredSections = []; + let requiredAcknowledgements = 0; + + let inBody = false; + let currentType = null; + let currentLabel = null; + let currentRequired = false; + let inValidations = false; + let inOptions = false; + + const flushBlock = () => { + if ( + currentType && + currentType !== 'markdown' && + currentType !== 'checkboxes' && + currentLabel && + currentRequired + ) { + requiredSections.push(currentLabel); + } + currentType = null; + currentLabel = null; + currentRequired = false; + inValidations = false; + inOptions = false; + }; + + for (const line of lines) { + const topLabelMatch = /^labels:\s*\[([^\]]+)\]/.exec(line); + if (topLabelMatch) { + label = topLabelMatch[1].split(',')[0].trim().toLowerCase(); + continue; + } + if (/^body:\s*$/.test(line)) { + inBody = true; + continue; + } + if (!inBody) continue; + + const itemMatch = /^ {2}- type:\s*(\S+)/.exec(line); + if (itemMatch) { + flushBlock(); + currentType = itemMatch[1]; + continue; + } + + const labelMatch = /^ {6}label:\s*(.+)$/.exec(line); + if (labelMatch && !inOptions) { + currentLabel = labelMatch[1].trim(); + continue; + } + + if (/^ {4}validations:\s*$/.test(line)) { + inValidations = true; + inOptions = false; + continue; + } + if (/^ {6}options:\s*$/.test(line)) { + inOptions = true; + inValidations = false; + continue; + } + if (/^ {4}[a-z]+:/.test(line)) { + inValidations = false; + inOptions = false; + } + + if (inValidations && /^\s+required:\s*true\s*$/.test(line)) { + currentRequired = true; + } + if ( + currentType === 'checkboxes' && + inOptions && + /^\s+required:\s*true\s*$/.test(line) + ) { + requiredAcknowledgements += 1; + } + } + flushBlock(); + + return { label, requiredSections, requiredAcknowledgements }; +} + +test('valid Report Issue, Request Plugin, and Request Feature pass validation', () => { + const cases = [ + { + body: VALID_REPORT_ISSUE_BODY.replace(/\n/g, '\r\n'), + labels: ['bug'], + expectedTemplate: 'Report Issue', + }, + { + body: VALID_PLUGIN_REQUEST_BODY, + labels: ['plugin request'], + expectedTemplate: 'Request Plugin', + }, + { + body: VALID_FEATURE_REQUEST_BODY, + labels: ['feature request'], + expectedTemplate: 'Request Feature', + }, + ]; + + for (const { body, labels, expectedTemplate } of cases) { + const result = validateIssueTemplate({ + body, + labels, + author: 'reader123', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + assert.equal(result.shouldClose, false); + assert.equal(result.template, expectedTemplate); + assert.deepEqual(result.reasons, []); + assert.equal(result.comment, ''); + } +}); + +test('valid unlabeled issue matching a template passes validation', () => { + const result = validateIssueTemplate({ + body: VALID_FEATURE_REQUEST_BODY, + labels: [], + author: 'reader123', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + assert.equal(result.shouldClose, false); + assert.equal(result.template, 'Request Feature'); +}); + +test('blank body and freeform body with no labels are closed with template link', () => { + for (const body of [ + '', + 'I cannot load the content but i can access the content from webview', + ]) { + const result = validateIssueTemplate({ + body, + labels: [], + author: 'some-user', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + assert.equal(result.shouldClose, true); + assert.equal(result.template, null); + assert.ok(result.comment.includes('@some-user ')); + assert.ok( + result.comment.includes( + 'https://github.com/lnreader/lnreader-plugins/issues/new/choose', + ), + ); + } +}); + +test('bug issue with missing heading or _No response_ in required field is closed with specific reasons', () => { + const brokenBody = VALID_REPORT_ISSUE_BODY.replace( + '### Plugin\n\nEnglish: Ranobes', + '### Plugin\n\n_No response_', + ).replace('### Android Version\n\n13\n\n', ''); + + const result = validateIssueTemplate({ + body: brokenBody, + labels: ['bug'], + author: 'reader123', + authorAssociation: 'NONE', + repository: 'lnreader/lnreader-plugins', + }); + + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Report Issue'); + assert.ok( + result.reasons.some( + reason => + reason.includes('`Plugin`') && reason.includes('`Android Version`'), + ), + ); + assert.ok(result.comment.includes('**Report Issue**')); +}); + +test('plugin request issue with unchecked box in Acknowledgements is closed', () => { + const uncheckedBody = VALID_PLUGIN_REQUEST_BODY.replace( + '- [x] I have used the plugin name as the issue title.', + '- [ ] I have used the plugin name as the issue title.', + ); + + const result = validateIssueTemplate({ + body: uncheckedBody, + labels: ['plugin request'], + author: 'reader123', + authorAssociation: 'NONE', + }); + + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Request Plugin'); + assert.ok( + result.reasons.some(reason => + reason.includes('All required checkboxes in `Acknowledgements`'), + ), + ); +}); + +test('feature request issue with missing or plain-text Acknowledgements is closed', () => { + const fewerBoxes = VALID_FEATURE_REQUEST_BODY.replace( + '- [x] I have provided all requested information in this form.', + '', + ); + const plainTextAck = VALID_FEATURE_REQUEST_BODY.replace( + /### Acknowledgements[\s\S]*$/, + '### Acknowledgements\n\nYes I agree', + ); + + for (const body of [fewerBoxes, plainTextAck]) { + const result = validateIssueTemplate({ + body, + labels: ['feature request'], + author: 'reader123', + authorAssociation: 'NONE', + }); + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Request Feature'); + assert.ok( + result.reasons.some(reason => + reason.includes('expected at least 5 checked items'), + ), + ); + } +}); + +test('unlabeled partial template reports specific missing sections for matched template', () => { + const partialBug = [ + '### Plugin', + '', + 'English: Ranobes', + '', + '### Severity', + '', + "Can't Load Novels", + ].join('\n'); + + const result = validateIssueTemplate({ + body: partialBug, + labels: [], + author: 'reader123', + authorAssociation: 'NONE', + }); + + assert.equal(result.shouldClose, true); + assert.equal(result.template, 'Report Issue'); + assert.ok( + result.reasons.some(reason => reason.includes('`Steps To Reproduce`')), + ); +}); + +test('exempt authors (OWNER, MEMBER, COLLABORATOR, Bot) are skipped even with blank body', () => { + for (const [authorAssociation, authorType] of [ + ['OWNER', 'User'], + ['MEMBER', 'User'], + ['COLLABORATOR', 'User'], + ['NONE', 'Bot'], + ]) { + const result = validateIssueTemplate({ + body: '', + labels: [], + author: 'maintainer', + authorAssociation, + authorType, + }); + assert.equal(result.shouldClose, false); + assert.equal(result.skipped, 'exempt-author'); + } +}); + +test('already closed issues are skipped', () => { + const result = validateIssueTemplate({ + body: '', + labels: [], + state: 'closed', + author: 'reader123', + authorAssociation: 'NONE', + }); + assert.equal(result.shouldClose, false); + assert.equal(result.skipped, 'not-open'); +}); + +test('invalid or unsafe author login is omitted instead of interpolated', () => { + const result = validateIssueTemplate({ + body: '', + labels: [], + author: 'bad user @everyone\n