fix(release): generate notes from verified tag history

This commit is contained in:
手瓜一十雪 committed 2026-10-10 12:27:51 +08:00
1 parent ff9a829e29
commit 26ad589367
4 files changed
+240 -210

No files matched your search

@@ -0,0 +1,77 @@
import { execFileSync } from 'node:child_process';
import { writeFileSync } from 'node:fs';
function parseVersion (tag) {
const match = /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/.exec(tag);
if (!match) return null;
const prerelease = match[4]?.split('.') ?? [];
if (prerelease.some(identifier => !identifier || /^0\d+$/.test(identifier))) return null;
return { tag, numbers: match.slice(1, 4).map(BigInt), prerelease };
}
function compareVersions (left, right) {
for (let index = 0; index < 3; index++) {
if (left.numbers[index] !== right.numbers[index]) {
return left.numbers[index] > right.numbers[index] ? 1 : -1;
}
}
if (!left.prerelease.length || !right.prerelease.length) {
return Number(!left.prerelease.length) - Number(!right.prerelease.length);
}
for (let index = 0; index < Math.min(left.prerelease.length, right.prerelease.length); index++) {
const leftIdentifier = left.prerelease[index];
const rightIdentifier = right.prerelease[index];
if (leftIdentifier === rightIdentifier) continue;
const leftNumeric = /^\d+$/.test(leftIdentifier);
const rightNumeric = /^\d+$/.test(rightIdentifier);
if (leftNumeric && rightNumeric) return BigInt(leftIdentifier) > BigInt(rightIdentifier) ? 1 : -1;
if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
return leftIdentifier > rightIdentifier ? 1 : -1;
}
return left.prerelease.length - right.prerelease.length;
}
function git (...args) {
return execFileSync('git', args, { encoding: 'utf8' }).trim();
}
const [tag, repository, outputFile] = process.argv.slice(2);
const currentVersion = parseVersion(tag);
if (process.argv.length !== 5 || !currentVersion || !repository || !outputFile) {
throw new Error('Usage: node generate-release-notes.mjs <vX.Y.Z[-prerelease]> <owner/repo> <output.md>');
}
if (git('rev-parse', '--is-shallow-repository') === 'true') {
throw new Error('Release notes require complete Git history and tags (fetch-depth: 0)');
}
const currentRef = `refs/tags/${currentVersion.tag}`;
const previousVersion = git('tag', '--merged', currentRef)
.split('\n')
.map(parseVersion)
.filter(version => version && compareVersions(version, currentVersion) < 0)
.sort((left, right) => compareVersions(right, left))[0];
if (!previousVersion) throw new Error(`No preceding version tag is reachable from ${currentVersion.tag}`);
const commits = git('log', '--reverse', '--format=%H%x09%s', `refs/tags/${previousVersion.tag}..${currentRef}`);
const repositoryUrl = `https://github.com/${repository}`;
const changes = commits.split('\n').filter(Boolean).map(commit => {
const separator = commit.indexOf('\t');
const hash = commit.slice(0, separator);
const subject = commit.slice(separator + 1).replace(/[\\`*_[\]<>]/g, '\\$&');
return `- ${subject} ([${hash.slice(0, 8)}](${repositoryUrl}/commit/${hash}))`;
});
const notes = [
`# NapCat ${currentVersion.tag}`,
'',
'[使用文档](https://napneko.github.io/) · [Shell 安装与兼容说明](https://napneko.github.io/guide/boot/Shell)',
'',
'## 更新',
'',
...changes,
...(changes.length ? [] : ['此标签范围内没有新增提交。']),
'',
`[完整变更](${repositoryUrl}/compare/${previousVersion.tag}...${currentVersion.tag})`,
'',
].join('\n');
writeFileSync(outputFile, notes, 'utf8');
console.log(`Generated release notes: ${previousVersion.tag}...${currentVersion.tag}`);
@@ -0,0 +1,122 @@
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { test } from 'node:test';
const script = fileURLToPath(new URL('../../scripts/generate-release-notes.mjs', import.meta.url));
function fixture (context) {
const root = mkdtempSync(join(tmpdir(), 'napcat-release-'));
context.after(() => rmSync(root, { recursive: true, force: true }));
function git (...args) {
return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: 'pipe' }).trim();
}
git('init', '--initial-branch=main');
git('config', 'user.name', 'Release Test');
git('config', 'user.email', 'release-test@example.invalid');
git('config', 'commit.gpgSign', 'false');
git('config', 'tag.gpgSign', 'false');
function commit (subject, tag) {
git('commit', '--allow-empty', '-m', subject);
if (tag) git('tag', tag);
return git('rev-parse', 'HEAD');
}
function generate (tag, cwd = root) {
return spawnSync(process.execPath, [script, tag, 'NapNeko/NapCatQQ', join(root, '说明 # release.md')], {
cwd,
encoding: 'utf8',
});
}
function notes () {
return readFileSync(join(root, '说明 # release.md'), 'utf8');
}
return { root, git, commit, generate, notes };
}
test('uses numeric version order, exact tagged range, and UTF-8 output paths', context => {
const repository = fixture(context);
repository.commit('old release', 'v4.18.9');
repository.commit('previous release', 'v4.18.10');
const changeHash = repository.commit('fix: 中文 [loader] *paths* <native> `quoted` \\ newline', 'v4.18.11');
repository.commit('unreleased change', 'v4.18.12');
const result = repository.generate('v4.18.11');
assert.equal(result.status, 0, result.stderr);
const notes = repository.notes();
assert.ok(notes.includes('fix: 中文 \\[loader\\] \\*paths\\* \\<native\\> \\`quoted\\` \\\\ newline'));
assert.ok(notes.includes(`/commit/${changeHash}`));
assert.ok(notes.includes('/compare/v4.18.10...v4.18.11'));
assert.doesNotMatch(notes, /old release|previous release|unreleased change|v4\.10\.7|MacOS 暂不支持/);
});
test('ignores version tags from an unmerged branch', context => {
const repository = fixture(context);
repository.commit('base', 'v1.0.0');
repository.git('checkout', '-b', 'other');
repository.commit('unmerged change', 'v1.9.0');
repository.git('checkout', 'main');
repository.commit('released change', 'v2.0.0');
const result = repository.generate('v2.0.0');
assert.equal(result.status, 0, result.stderr);
assert.ok(repository.notes().includes('/compare/v1.0.0...v2.0.0'));
assert.doesNotMatch(repository.notes(), /unmerged change/);
});
test('orders prerelease identifiers using semantic version precedence', context => {
const repository = fixture(context);
const versions = ['v1.0.0', 'v2.0.0-alpha.1', 'v2.0.0-alpha.2', 'v2.0.0-alpha.10',
'v2.0.0-alpha.a10', 'v2.0.0-alpha.a2', 'v2.0.0-beta', 'v2.0.0-beta.1', 'v2.0.0-rc.1', 'v2.0.0'];
for (const version of versions) repository.commit(version, version);
for (let index = 1; index < versions.length; index++) {
const result = repository.generate(versions[index]);
assert.equal(result.status, 0, result.stderr);
assert.ok(repository.notes().includes(`/compare/${versions[index - 1]}...${versions[index]}`));
}
});
test('accepts annotated release tags and ignores invalid version tags', context => {
const repository = fixture(context);
repository.commit('base', 'v1.0.0');
repository.commit('change');
repository.git('tag', '-a', 'v1.1.0', '-m', 'Release v1.1.0');
for (const tag of ['v1.2.0-01', 'v1.2.0-.rc', 'v1.02.0', 'preview']) repository.git('tag', tag);
repository.commit('current', 'v2.0.0');
const result = repository.generate('v2.0.0');
assert.equal(result.status, 0, result.stderr);
assert.ok(repository.notes().includes('/compare/v1.1.0...v2.0.0'));
});
test('reports an empty tagged range without inventing changes', context => {
const repository = fixture(context);
repository.commit('base', 'v1.0.0');
repository.git('tag', 'v1.0.1');
const result = repository.generate('v1.0.1');
assert.equal(result.status, 0, result.stderr);
assert.ok(repository.notes().includes('此标签范围内没有新增提交。'));
});
test('fails for missing or invalid versions without replacing existing output', context => {
const repository = fixture(context);
repository.commit('base', 'v1.0.0');
const output = join(repository.root, '说明 # release.md');
writeFileSync(output, 'existing output');
for (const tag of ['v1.0.0', 'v2.0.0', 'v2.0.0-01', '--help', 'v1.0.1;echo invalid']) {
const result = repository.generate(tag);
assert.notEqual(result.status, 0, tag);
assert.equal(repository.notes(), 'existing output');
}
});
test('rejects a shallow checkout instead of generating incomplete notes', context => {
const repository = fixture(context);
repository.commit('base', 'v1.0.0');
repository.commit('current', 'v1.1.0');
const shallow = join(repository.root, 'shallow');
repository.git('clone', '--depth=1', '--no-local', pathToFileURL(repository.root).href, shallow);
const result = repository.generate('v1.1.0', shallow);
assert.notEqual(result.status, 0);
assert.match(result.stderr, /complete Git history/);
assert.equal(existsSync(join(repository.root, '说明 # release.md')), false);
});
+34
View File
@@ -0,0 +1,34 @@
name: Release notes
on:
push:
paths:
- .github/scripts/generate-release-notes.mjs
- .github/tests/release-notes/**
- .github/workflows/release-notes.yml
- .github/workflows/release-publish.yml
pull_request:
paths:
- .github/scripts/generate-release-notes.mjs
- .github/tests/release-notes/**
- .github/workflows/release-notes.yml
- .github/workflows/release-publish.yml
workflow_dispatch:
permissions:
contents: read
jobs:
notes:
runs-on: ${{ matrix.runner }}
timeout-minutes: 5
strategy:
fail-fast: false
matrix:
runner: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v6
with:
node-version: 20.x
- run: node --test .github/tests/release-notes/generate.test.mjs
+7 -210
View File
@@ -11,8 +11,6 @@ on:
permissions: write-all
env:
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "google/gemma-4-26b-a4b-it:free"
RELEASE_NAME: "NapCat"
jobs:
@@ -246,216 +244,15 @@ jobs:
[ -d NapCat.Shell.Windows.Node ] && (cd NapCat.Shell.Windows.Node && zip -qr ../../NapCat.Shell.Windows.Node.zip .)
cd ..
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Generate release note
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
GITHUB_OWNER: "NapNeko"
GITHUB_REPO: "NapCatQQ"
run: |
set -euo pipefail
# 当前 tag
CURRENT_TAG="${{ inputs.version }}"
echo "Current tag: $CURRENT_TAG"
# 从 GitHub API 获取 tag 列表
TAGS_JSON=$(curl -s "https://api.github.com/repos/${GITHUB_OWNER}/${GITHUB_REPO}/tags?per_page=100")
TAGS=( $(echo "$TAGS_JSON" | jq -r '.[].name' | sort -V) )
# 找到上一个 tag
PREV_TAG=""
for i in "${!TAGS[@]}"; do
if [ "${TAGS[$i]}" = "$CURRENT_TAG" ]; then
if [ $i -gt 0 ]; then
PREV_TAG="${TAGS[$((i-1))]}"
fi
break
fi
done
if [ -z "$PREV_TAG" ]; then
echo "Could not find previous tag for $CURRENT_TAG, using first commit"
PREV_TAG=$(git rev-list --max-parents=0 HEAD | head -1)
fi
echo "Previous tag: $PREV_TAG"
# 强制拉取上一个 tag 和当前 tag
git fetch origin "refs/tags/$PREV_TAG:refs/tags/$PREV_TAG" --force || true
git fetch origin "refs/tags/$CURRENT_TAG:refs/tags/$CURRENT_TAG" --force || true
# 获取 commit,使用更清晰的格式
COMMITS=$(git log --pretty=format:'- %s (%h)' "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || git log --pretty=format:'- %s (%h)' -20)
echo "Commit list from $PREV_TAG to $CURRENT_TAG:"
echo "$COMMITS"
# 获取文件变化统计
echo "Getting file change statistics..."
FILE_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || echo "")
# 获取总体统计(最后一行)
SUMMARY_LINE=$(echo "$FILE_STATS" | tail -1)
echo "Summary: $SUMMARY_LINE"
# 获取每个文件的变化(去掉最后一行汇总)
# 截断过长的输出(最多50个文件,每行最多80字符)
FILE_CHANGES=$(echo "$FILE_STATS" | head -n -1 | head -50 | cut -c1-80)
# 如果文件变化太多,进一步精简:只保留主要目录的变化
FILE_COUNT=$(echo "$FILE_STATS" | head -n -1 | wc -l)
if [ "$FILE_COUNT" -gt 50 ]; then
echo "Too many files ($FILE_COUNT), grouping by directory..."
# 按目录分组统计
DIR_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | head -n -1 | \
sed 's/|.*//g' | \
awk -F'/' '{if(NF>1) print $1"/"$2; else print $1}' | \
sort | uniq -c | sort -rn | head -20)
FILE_CHANGES="[按目录分组统计 - 共 $FILE_COUNT 个文件变更]
$DIR_STATS"
fi
echo "File changes:"
echo "$FILE_CHANGES"
# 获取具体代码变化(关键文件的diff)
echo "Getting code diff for key files..."
# 定义关键目录(优先展示这些目录的变化)
KEY_DIRS="packages/napcat-core packages/napcat-onebot packages/napcat-webui-backend"
# 获取变更的关键文件列表(排除测试、配置等)
KEY_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "^packages/napcat-(core|onebot|webui-backend|shell)/" || true | \
grep -E "\.(ts|js)$" || true | \
grep -v -E "(test|spec|\.d\.ts|config)" || true | \
head -15) || true
CODE_DIFF=""
DIFF_CHAR_LIMIT=6000
CURRENT_CHARS=0
if [ -n "$KEY_FILES" ]; then
for file in $KEY_FILES; do
if [ "$CURRENT_CHARS" -ge "$DIFF_CHAR_LIMIT" ]; then
CODE_DIFF="$CODE_DIFF
[... 更多文件变化已截断 ...]"
break
fi
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -50) || true
FILE_DIFF_LEN=${#FILE_DIFF}
if [ "$FILE_DIFF_LEN" -gt 1500 ]; then
FILE_DIFF=$(echo "$FILE_DIFF" | head -c 1500)
FILE_DIFF="$FILE_DIFF
[... 文件 $file 变化已截断 ...]"
fi
if [ -n "$FILE_DIFF" ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
\`\`\`"
CURRENT_CHARS=$((CURRENT_CHARS + FILE_DIFF_LEN))
fi
done
fi
# 如果没有关键文件变化,获取前5个变更文件的diff
if [ -z "$CODE_DIFF" ]; then
echo "No key files changed, getting top changed files..."
TOP_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "\.(ts|js|yml|md)$" | head -5) || true
if [ -n "$TOP_FILES" ]; then
for file in $TOP_FILES; do
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -30) || true
if [ -n "$FILE_DIFF" ] && [ ${#FILE_DIFF} -lt 1000 ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
\`\`\`"
fi
done
fi
fi
# 如果仍然没有代码变化,添加说明
if [ -z "$CODE_DIFF" ]; then
CODE_DIFF="[本次更新主要涉及配置文件和文档变更,无核心代码变化]"
fi
echo "Code diff preview:"
echo "$CODE_DIFF" | head -50
# 读取 prompt
PROMPT_FILE=".github/prompt/release_note_prompt.txt"
SYSTEM_PROMPT=$(<"$PROMPT_FILE")
# 构建用户内容,传递更多上下文(包含文件变化和代码diff)
USER_CONTENT="当前版本: $CURRENT_TAG
上一版本: $PREV_TAG
## 提交列表
$COMMITS
## 文件变化统计
$SUMMARY_LINE
## 变更文件列表
$FILE_CHANGES
## 关键代码变化
$CODE_DIFF"
# 构建请求 JSON,增加 max_tokens 以获取更完整的输出
BODY=$(jq -n \
--arg system "$SYSTEM_PROMPT" \
--arg user "$USER_CONTENT" \
--arg model "$OPENAI_MODEL" \
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:5000}')
echo "=== request body ==="
echo "$BODY" | jq .
if RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
-H "Authorization: Bearer $OPENAI_KEY" \
-H "Content-Type: application/json" \
-d "$BODY"); then
echo "=== raw response ==="
echo "$RESPONSE"
echo "=== parsed response ==="
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
echo "$RESPONSE" | jq .
else
echo "jq failed to parse response"
fi
# 提取生成内容
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
if [ -z "$RELEASE_BODY" ]; then
echo "LLM failed to generate release note, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
else
# 后处理:确保版本号正确,并添加比较链接
echo -e "$RELEASE_BODY" > CHANGELOG.md
sed -i "s/{VERSION}/$CURRENT_TAG/g" CHANGELOG.md
sed -i "s/{PREV_VERSION}/$PREV_TAG/g" CHANGELOG.md
fi
else
echo "Curl failed, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
fi
echo "=== generated release note ==="
cat CHANGELOG.md
CURRENT_TAG: ${{ inputs.version }}
run: node .github/scripts/generate-release-notes.mjs "$CURRENT_TAG" "$GITHUB_REPOSITORY" CHANGELOG.md
- name: Create Release and Upload Artifacts
uses: softprops/action-gh-release@v2