Files
RSSHub/scripts/workflow/test-route/identify.mjs
T
dependabot[bot]andTony 873618e99d chore(deps-dev): bump eslint-plugin-unicorn from 65.0.1 to 66.0.0 (#22274)
* chore(deps-dev): bump eslint-plugin-unicorn from 65.0.1 to 66.0.0

Bumps [eslint-plugin-unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn) from 65.0.1 to 66.0.0.
- [Release notes](https://github.com/sindresorhus/eslint-plugin-unicorn/releases)
- [Commits](https://github.com/sindresorhus/eslint-plugin-unicorn/compare/v65.0.1...v66.0.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-unicorn
  dependency-version: 66.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* style: fix unicorn-js/prefer-url-href

* style: oxlint disable

* style: fix unicorn-js/no-useless-else

* style: no-unsafe-string-replacement

* style: fix no-duplicate-loops

* style: fix prefer-number-is-safe-integer

* style: fix prefer-single-array-predicate

* style: fix no-object-methods-with-collections

* style: fix no-useless-boolean-cast

* style: fix no-useless-template-literals

* style: fix no-negated-array-predicate

* style: fix prefer-direct-iteration

* style: fix consistent-optional-chaining

* style: fix prefer-simple-sort-comparator

* style: fix prefer-global-number-constants

* style: fix prefer-type-literal-last

* style: fix require-array-sort-compare.

* style: fix prefer-early-return

* style: fix prefer-short-arrow-method

* style: fix prefer-array-from-map

* style: fix prefer-scoped-selector

* style: fix no-global-object-property-assignment

* style: fix no-unnecessary-global-this

* style: fix no-unreadable-object-destructuring

* style: fix no-invalid-argument-count

* style: fix prefer-smaller-scope

* style: fix prefer-iterator-to-array.

* style: fix prefer-object-iterable-methods

* style: fix typo

* style: fix max-nested-calls

* style: fix no-incorrect-template-string-interpolation

* style: fix no-break-in-nested-loop

* style: fix prefer-await

* style: fix no-computed-property-existence-check

* style: fix prefer-number-coercion

* style: fix no-empty-file

* style: update eslint unicorn v66 recommended preset

* style: add unicorn/prefer-spread to oxlint-disable comments

* style: fix no-array-reduce

* style: delete github/no-then as it's covered by unicorn/prefer-await

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Tony <TonyRL@users.noreply.github.com>
2026-06-16 14:43:42 +08:00

210 lines
7.1 KiB
JavaScript

import remarkParse from 'remark-parse';
import { unified } from 'unified';
const noFound = 'auto: route no found';
const criticalFailure = 'auto: DO NOT merge';
const routeTestFailed = 'auto: not ready to review';
const allowedUser = new Set(['dependabot[bot]', 'pull[bot]']); // dependabot and downstream PR requested by pull[bot]
const requiredHeadings = ['Involved Issue / 该 PR 相关 Issue', 'Example for the Proposed Route(s) / 路由地址示例', 'New RSS Route Checklist / 新 RSS 路由检查表', 'Note / 说明'];
const routeHeading = 'Example for the Proposed Route(s) / 路由地址示例';
const requiredHeadingDepth = 2;
/** @type {boolean} */
const isPR = Boolean(process.env.PULL_REQUEST);
/**
* @param {{ github: ReturnType<typeof import('@actions/github').getOctokit>, context: typeof import('@actions/github').context, core: typeof import('@actions/core') }} githubScript
* @param {string | null} body
* @param {number} number
* @param {string} sender
* @returns {Promise<string[] | void>}
*/
export default async function identify({ github, context, core }, body, number, sender) {
core.debug(`sender: ${sender}`);
core.debug(`body: ${body}`);
const issueFacts = {
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: number,
};
const prFacts = {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: number,
};
let issue;
try {
/** @type {Awaited<ReturnType<typeof github.rest.issues.get>>} */
const response = await github.rest.issues.get({
...issueFacts,
});
issue = response.data;
} catch (error) {
core.warning(error);
throw error;
}
/** @param {string[]} labels */
const addLabels = (labels) => {
try {
return github.rest.issues.addLabels({
...issueFacts,
labels,
});
} catch (error) {
core.warning(error);
}
};
/** @param {string} labelName */
const removeLabel = (labelName = noFound) => {
try {
return github.rest.issues.removeLabel({
...issueFacts,
name: labelName,
});
} catch (error) {
core.warning(error);
}
};
/** @param {'open' | 'closed'} state */
const updatePrState = (state) => {
try {
return github.rest.pulls.update({
...prFacts,
state,
});
} catch (error) {
core.warning(error);
}
};
/** @param {string} body */
const createComment = (body) => {
try {
return github.rest.issues.createComment({
...issueFacts,
body,
});
} catch (error) {
core.warning(error);
}
};
const createFailedComment = () => {
const logUrl = `${process.env.GITHUB_SERVER_URL}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
if (isPR) {
return createComment(`Auto Route Test failed, please check your PR body format and reopen pull request. Check [logs](${logUrl}) for more details.
自动路由测试失败,请确认 PR 正文部分符合格式规范并重新开启,详情请检查 [日志](${logUrl})。`);
}
return createComment(`Route Test failed, please check your comment body. Check [logs](${logUrl}) for more details.
路由测试失败,请确认评论部分符合格式规范,详情请检查 [日志](${logUrl})。`);
};
if (isPR) {
if (issue.state === 'closed') {
await updatePrState('open');
}
if (issue.labels.some((e) => e.name === criticalFailure || e.name === routeTestFailed)) {
await removeLabel(criticalFailure);
await removeLabel(routeTestFailed);
}
}
if (allowedUser.has(sender)) {
core.info('PR created by a allowed user, passing');
await removeLabel();
await addLabels(['auto: ready to merge']);
return;
}
core.debug('PR created by ' + sender);
let hasWriteAccess;
try {
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
owner: context.repo.owner,
repo: context.repo.repo,
username: sender,
});
hasWriteAccess = ['admin', 'maintain', 'write'].includes(data.permission);
} catch (error) {
core.warning(error);
hasWriteAccess = false;
}
core.debug(`hasWriteAccess: ${hasWriteAccess}`);
/** @type {string[] | undefined} */
let routes;
if (body) {
const ast = unified().use(remarkParse).parse(body);
let searchStart = 0;
let searchEnd = ast.children.length;
if (isPR) {
/** @param {string} text */
const findHeading = (text) => ast.children.findIndex((node) => node.type === 'heading' && node.depth === requiredHeadingDepth && node.children?.some((child) => child.type === 'text' && child.value.trim() === text));
const missingHeadings = requiredHeadings.filter((text) => findHeading(text) === -1);
if (missingHeadings.length > 0) {
searchStart = -1; // skip search
} else {
const headingIndex = findHeading(routeHeading);
core.debug(`headingIndex: ${headingIndex}`);
searchStart = headingIndex + 1;
const nextHeading = ast.children.findIndex((node, i) => i > headingIndex && node.type === 'heading');
if (nextHeading !== -1) {
searchEnd = nextHeading;
}
}
}
for (let i = searchStart; i >= 0 && i < searchEnd; i++) {
const node = ast.children[i];
if (node.type === 'code' && node.lang === 'routes') {
const code = node.value?.trim();
core.debug(`match: ${code}`);
if (code) {
routes = code.split(/\r?\n/).filter(Boolean);
}
break;
}
}
}
if (routes?.length) {
core.info(`routes detected: ${routes}`);
if (routes[0] === 'NOROUTE') {
core.info('PR stated no route, passing');
await removeLabel();
await addLabels(['auto: route test bypassed']);
return;
}
if (routes.some((e) => e.includes('/:'))) {
await addLabels([noFound]);
return createComment(`Please use actual values in \`routes\` section instead of path parameters.
请在 \`routes\` 部分使用实际值而不是路径参数。`);
}
core.exportVariable('TEST_CONTINUE', true);
await removeLabel();
return routes;
}
core.warning('Seems like no valid routes can be found. Failing.');
await createFailedComment();
if (isPR) {
await addLabels([noFound]);
if (!hasWriteAccess) {
await updatePrState('closed');
}
}
throw new Error('Please follow the PR rules: failed to detect route');
}