11name : PR Validation
22
33on :
4- pull_request :
4+ pull_request_target : # 修改点 1:支持外部 Fork 获取写权限
55 branches : [main]
66 paths :
77 - ' tools/**'
1414jobs :
1515 validate :
1616 runs-on : ubuntu-latest
17+ # 显式声明权限
1718 permissions :
1819 pull-requests : write
1920 contents : read
2223 - name : Checkout
2324 uses : actions/checkout@v4
2425 with :
26+ # 修改点 2:如果是 PR 触发,强制拉取 PR 的最新提交代码进行校验
27+ ref : ${{ github.event.pull_request.head.sha || github.ref }}
2528 fetch-depth : 0
2629
27- - name : Checkout PR branch
30+ - name : Checkout PR branch (Manual)
2831 if : github.event_name == 'workflow_dispatch'
2932 run : |
3033 cp .github/scripts/validate_pr.py /tmp/validate_pr.py
3942 if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
4043 gh pr diff ${{ inputs.pr_number }} --name-only > changed_files.txt
4144 else
42- git diff --name-only origin/main...HEAD > changed_files.txt
45+ # 使用 pull_request_target 时,对比基础分支
46+ git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} > changed_files.txt
4347 fi
4448 env :
4549 GH_TOKEN : ${{ secrets.GITHUB_TOKEN }}
@@ -56,24 +60,32 @@ jobs:
5660 id : validate
5761 working-directory : ${{ github.workspace }}
5862 run : |
63+ # 确保脚本存在(如果是从 main 分支运行 pull_request_target,脚本默认就在)
5964 python .github/scripts/validate_pr.py changed_files.txt > result.txt 2>&1
6065 echo "exit_code=$?" >> $GITHUB_OUTPUT
6166 cat result.txt
6267
6368 - name : Comment on PR
64- if : always() && (github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch')
69+ if : always()
6570 uses : actions/github-script@v7
6671 with :
6772 script : |
6873 const fs = require('fs');
74+ if (!fs.existsSync('result.txt')) {
75+ console.log('No result.txt found');
76+ return;
77+ }
6978 const result = fs.readFileSync('result.txt', 'utf8');
7079 const exitCode = '${{ steps.validate.outputs.exit_code }}';
7180 const icon = exitCode === '0' ? '✅' : '❌';
7281 const status = exitCode === '0' ? '校验通过' : '校验失败,请修复后重新提交';
82+
83+ // 获取正确的 PR 编号
7384 const prNumber = context.eventName === 'workflow_dispatch'
7485 ? parseInt('${{ inputs.pr_number }}')
7586 : context.payload.pull_request.number;
76- github.rest.issues.createComment({
87+
88+ await github.rest.issues.createComment({
7789 issue_number: prNumber,
7890 owner: context.repo.owner,
7991 repo: context.repo.repo,
0 commit comments