1+ # .github/workflows/auto-autofix.yml
2+ name : Auto Copilot Autofix (High & Medium Only)
3+
4+ on :
5+ workflow_run :
6+ workflows : ["CodeQL"]
7+ types : [completed]
8+
9+ jobs :
10+ auto-fix :
11+ runs-on : ubuntu-latest
12+ permissions :
13+ security-events : read
14+ contents : write
15+ pull-requests : write
16+
17+ steps :
18+ - name : Trigger Autofix for High & Medium alerts
19+ env :
20+ GH_TOKEN : ${{ secrets.GITHUB_TOKEN }}
21+ OWNER : ${{ github.repository_owner }}
22+ REPO : ${{ github.event.repository.name }}
23+ run : |
24+ for SEVERITY in "error" "warning"; do
25+ echo "====== Processing severity: $SEVERITY ======"
26+
27+ # 只获取 high(error)和 medium(warning)级别的 open alerts
28+ ALERTS=$(gh api \
29+ "/repos/$OWNER/$REPO/code-scanning/alerts?severity=$SEVERITY&state=open&per_page=100" \
30+ --jq '[.[] | .number]')
31+
32+ COUNT=$(echo $ALERTS | jq 'length')
33+ echo "Found $COUNT alerts with severity: $SEVERITY"
34+
35+ if [ "$COUNT" -eq 0 ]; then
36+ continue
37+ fi
38+
39+ for NUMBER in $(echo $ALERTS | jq -r '.[]'); do
40+ echo "--- Alert #$NUMBER ($SEVERITY) ---"
41+
42+ # 检查是否已经有 autofix
43+ EXISTING=$(gh api \
44+ /repos/$OWNER/$REPO/code-scanning/alerts/$NUMBER/autofix \
45+ --jq '.status' 2>/dev/null || echo "none")
46+
47+ if [ "$EXISTING" = "succeeded" ]; then
48+ echo "✅ Fix already exists, committing directly..."
49+ else
50+ echo "⏳ Generating fix..."
51+ gh api -X POST \
52+ /repos/$OWNER/$REPO/code-scanning/alerts/$NUMBER/autofix || {
53+ echo "⚠️ Failed to trigger autofix for #$NUMBER, skipping"
54+ continue
55+ }
56+
57+ # 轮询等待 fix 生成(最多等 90 秒)
58+ for i in 1 2 3; do
59+ sleep 30
60+ EXISTING=$(gh api \
61+ /repos/$OWNER/$REPO/code-scanning/alerts/$NUMBER/autofix \
62+ --jq '.status' 2>/dev/null || echo "none")
63+ echo " Attempt $i: status = $EXISTING"
64+ [ "$EXISTING" = "succeeded" ] && break
65+ done
66+ fi
67+
68+ if [ "$EXISTING" = "succeeded" ]; then
69+ BRANCH="autofix/${SEVERITY}/alert-${NUMBER}"
70+
71+ # 提交 fix 到新分支
72+ gh api -X POST \
73+ /repos/$OWNER/$REPO/code-scanning/alerts/$NUMBER/autofix/commits \
74+ -f target_ref="$BRANCH" && \
75+ echo "✅ Committed fix to branch: $BRANCH" || \
76+ echo "❌ Failed to commit fix for alert #$NUMBER"
77+ else
78+ echo "⚠️ Autofix not available for alert #$NUMBER (status: $EXISTING), skipping"
79+ fi
80+
81+ done
82+ done
0 commit comments