-
Notifications
You must be signed in to change notification settings - Fork 21
97 lines (85 loc) · 3.28 KB
/
pr-validate.yml
File metadata and controls
97 lines (85 loc) · 3.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
name: PR Validation
on:
pull_request_target: # 修改点 1:支持外部 Fork 获取写权限
branches: [main]
paths:
- 'tools/**'
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to validate'
required: true
jobs:
validate:
runs-on: ubuntu-latest
# 显式声明权限
permissions:
pull-requests: write
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# 修改点 2:如果是 PR 触发,强制拉取 PR 的最新提交代码进行校验
ref: ${{ github.event.pull_request.head.sha || github.ref }}
fetch-depth: 0
- name: Checkout PR branch (Manual)
if: github.event_name == 'workflow_dispatch'
run: |
cp .github/scripts/validate_pr.py /tmp/validate_pr.py
gh pr checkout ${{ inputs.pr_number }}
mkdir -p .github/scripts
cp /tmp/validate_pr.py .github/scripts/validate_pr.py
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Get changed files
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
gh pr diff ${{ inputs.pr_number }} --name-only > changed_files.txt
else
# 使用 pull_request_target 时,对比基础分支
git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} > changed_files.txt
fi
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install pyyaml
- name: Run validation
id: validate
working-directory: ${{ github.workspace }}
run: |
# 确保脚本存在(如果是从 main 分支运行 pull_request_target,脚本默认就在)
python .github/scripts/validate_pr.py changed_files.txt > result.txt 2>&1
echo "exit_code=$?" >> $GITHUB_OUTPUT
cat result.txt
- name: Comment on PR
if: always()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
if (!fs.existsSync('result.txt')) {
console.log('No result.txt found');
return;
}
const result = fs.readFileSync('result.txt', 'utf8');
const exitCode = '${{ steps.validate.outputs.exit_code }}';
const icon = exitCode === '0' ? '✅' : '❌';
const status = exitCode === '0' ? '校验通过' : '校验失败,请修复后重新提交';
// 获取正确的 PR 编号
const prNumber = context.eventName === 'workflow_dispatch'
? parseInt('${{ inputs.pr_number }}')
: context.payload.pull_request.number;
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## ${icon} PR 自动校验结果\n\n**状态**: ${status}\n\n\`\`\`\n${result}\n\`\`\``
});
- name: Fail if validation failed
if: steps.validate.outputs.exit_code != '0'
run: exit 1