From 423b51e78059981db827af76cbee67fe8e347423 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:44:00 +0800 Subject: [PATCH] ci: restore automated Mihomo changelog sync --- .github/workflows/sync-mihomo-changelog.yml | 113 ++++++++++++++++++++ scripts/sync-mihomo-version.mjs | 88 +++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 .github/workflows/sync-mihomo-changelog.yml create mode 100644 scripts/sync-mihomo-version.mjs diff --git a/.github/workflows/sync-mihomo-changelog.yml b/.github/workflows/sync-mihomo-changelog.yml new file mode 100644 index 000000000..db4662b1a --- /dev/null +++ b/.github/workflows/sync-mihomo-changelog.yml @@ -0,0 +1,113 @@ +name: Sync Mihomo Changelog + +on: + workflow_dispatch: + inputs: + dry_run: + description: Preview the Changelog diff without creating a PR + type: boolean + default: true + schedule: + # UTC+8 Monday 11:30 + - cron: '30 3 * * 1' + +permissions: + contents: write + pull-requests: write + issues: write + +concurrency: + group: sync-mihomo-changelog + cancel-in-progress: false + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - uses: actions/setup-node@v7 + with: + node-version: '26.13.1' + + - name: Sync Mihomo version + id: sync + env: + DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} + run: | + args=() + if [[ "$DRY_RUN" == 'true' ]]; then args+=(--dry-run); fi + node scripts/sync-mihomo-version.mjs "${args[@]}" + + - name: Create labeled PR and enqueue + if: steps.sync.outputs.changed == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) + uses: actions/github-script@v9 + env: + MIHOMO_VERSION: ${{ steps.sync.outputs.version }} + with: + script: | + const { readFileSync } = await import('node:fs'); + const { execFileSync } = await import('node:child_process'); + const { owner, repo } = context.repo; + const base = context.payload.repository.default_branch; + const version = process.env.MIHOMO_VERSION; + const appVersion = JSON.parse(readFileSync('package.json', 'utf8')).version; + const branch = `chore/sync-mihomo-${appVersion}-${version}`; + const title = `chore: sync Mihomo changelog to ${version}`; + const pulls = await github.rest.pulls.list({ + owner, repo, base, head: `${owner}:${branch}`, state: 'all', + }); + let pr = pulls.data[0]; + if (pr && (pr.state !== 'open' || pr.user.login !== 'github-actions[bot]')) { + throw new Error(`Existing candidate needs maintainer attention: ${pr.html_url}`); + } + if (!pr) { + const sha = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(); + await github.rest.git.createRef({ owner, repo, ref: `refs/heads/${branch}`, sha }); + await github.graphql(`mutation($input: CreateCommitOnBranchInput!) { + createCommitOnBranch(input: $input) { commit { oid } } + }`, { + input: { + branch: { repositoryNameWithOwner: `${owner}/${repo}`, branchName: branch }, + expectedHeadOid: sha, + message: { headline: title }, + fileChanges: { additions: [{ + path: 'Changelog.md', + contents: readFileSync('Changelog.md').toString('base64'), + }] }, + }, + }); + ({ data: pr } = await github.rest.pulls.create({ + owner, repo, base, head: branch, title, + body: `## Problem\n\nChangelog.md needs to record the latest stable Mihomo version.\n\n` + + `## Approach\n\nRead the same upstream version.txt used by the core download script.\n\n` + + `## Scope\n\nOnly the Mihomo version line in Changelog.md changes to ${version}.`, + })); + } + for (let attempt = 0; attempt < 10; attempt++) { + ({ data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: pr.number })); + if (pr.mergeable !== null) break; + await new Promise(resolve => setTimeout(resolve, 2000)); + } + if (!pr.mergeable) throw new Error(`Sync PR is not mergeable: ${pr.html_url}`); + const files = await github.paginate(github.rest.pulls.listFiles, { + owner, repo, pull_number: pr.number, + }); + if (files.length !== 1 || files[0].filename !== 'Changelog.md') { + throw new Error('The sync PR must change only Changelog.md.'); + } + await github.rest.issues.addLabels({ + owner, repo, issue_number: pr.number, labels: ['dependencies', 'upstream'], + }); + const result = await github.graphql(`query($id: ID!) { + node(id: $id) { ... on PullRequest { mergeQueueEntry { id } } } + }`, { id: pr.node_id }); + if (!result.node.mergeQueueEntry) { + await github.graphql(`mutation($input: EnqueuePullRequestInput!) { + enqueuePullRequest(input: $input) { mergeQueueEntry { id } } + }`, { input: { pullRequestId: pr.node_id, expectedHeadOid: pr.head.sha } }); + } + await core.summary.addRaw(`Queued Mihomo sync PR: ${pr.html_url}\n`).write(); diff --git a/scripts/sync-mihomo-version.mjs b/scripts/sync-mihomo-version.mjs new file mode 100644 index 000000000..97d6d2594 --- /dev/null +++ b/scripts/sync-mihomo-version.mjs @@ -0,0 +1,88 @@ +import { spawnSync } from 'node:child_process' +import { appendFileSync, readFileSync, writeFileSync } from 'node:fs' +import { parseArgs } from 'node:util' + +const { values } = parseArgs({ + options: { + 'dry-run': { type: 'boolean', default: false }, + check: { type: 'boolean', default: false }, + version: { type: 'string' }, + file: { type: 'string', default: 'Changelog.md' }, + }, +}) + +async function main() { + let version = values.version + if (!version) { + const response = await fetch( + 'https://github.com/MetaCubeX/mihomo/releases/latest/download/version.txt', + { signal: AbortSignal.timeout(30_000) }, + ) + if (!response.ok) + throw new Error(`Failed to fetch Mihomo version: ${response.status}`) + version = await response.text() + } + version = version.trim().replace(/^v?/, 'v') + if (!/^v\d+\.\d+\.\d+$/.test(version)) + throw new Error(`Invalid stable Mihomo version: ${version}`) + + const content = readFileSync(values.file, 'utf8') + const title = /^## .+$/m.exec(content) + if (!title) throw new Error('Could not find changelog title.') + const start = title.index + title[0].length + const end = content.indexOf('\n## ', start) + const section = content.slice(start, end === -1 ? undefined : end) + const line = + /^(\s*-\s*(?:\*\*)?\s*Mihomo(?:\(Meta\))?\s*内核升级至\s*)v?\d+(?:\.\d+)+(?:[-+][^\s*]+)?((?:\*\*)?[\t ]*)$/m + const nextSection = line.test(section) + ? section.replace(line, `$1${version}$2`) + : `\n\n- **Mihomo 内核升级至 ${version}**${section.replace(/^\n*/, '\n\n')}` + const nextContent = + content.slice(0, start) + + nextSection + + (end === -1 ? '' : content.slice(end)) + const changed = content !== nextContent + + if (process.env.GITHUB_OUTPUT) + appendFileSync( + process.env.GITHUB_OUTPUT, + `version=${version}\nchanged=${changed}\n`, + ) + if (!changed) { + console.log(`Mihomo version in changelog is already ${version}`) + return + } + + const diff = spawnSync( + 'diff', + [ + '-u', + '--label', + `a/${values.file}`, + '--label', + `b/${values.file}`, + values.file, + '-', + ], + { input: nextContent, encoding: 'utf8' }, + ) + if (diff.error) throw diff.error + if (diff.status !== 1) + throw new Error(diff.stderr || 'Could not preview changelog diff.') + process.stdout.write(diff.stdout) + if (process.env.GITHUB_STEP_SUMMARY) + appendFileSync( + process.env.GITHUB_STEP_SUMMARY, + `### Mihomo ${version}\n\n\`\`\`diff\n${diff.stdout}\`\`\`\n`, + ) + if (values.check) { + process.exitCode = 1 + return + } + if (!values['dry-run']) writeFileSync(values.file, nextContent) +} + +main().catch((error) => { + console.error('sync-mihomo-version failed:', error.message) + process.exitCode = 1 +})