tools: add clang-format formatting script for CI (#10684)

* tools: add clang-format formatting script for CI

* improve[ci]: standardize the naming of CI files related to clang-format
This commit is contained in:
Yuqiang Wang
2025-09-23 17:38:09 +08:00
committed by GitHub
parent 35672cd5cb
commit 4123daf00c
3 changed files with 385 additions and 8 deletions

View File

@@ -4,7 +4,6 @@
#
# clang-format -style=llvm -dump-config > .clang-format
#
---
Language: Cpp
BasedOnStyle: LLVM
AccessModifierOffset: -1
@@ -46,13 +45,13 @@ AlignTrailingComments:
OverEmptyLines: 1
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortIfStatementsOnASingleLine: false
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
@@ -62,6 +61,7 @@ AttributeMacros:
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: false
AfterClass: true
@@ -86,7 +86,6 @@ BreakAfterJavaFieldAnnotations: false
BreakArrays: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Custom
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: AfterColon
@@ -238,5 +237,3 @@ WhitespaceSensitiveMacros:
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
---

265
.github/workflows/pr_clang_format.yaml vendored Normal file
View File

@@ -0,0 +1,265 @@
name: Code Format with Clang-Format
on:
workflow_dispatch:
inputs:
exclude_patterns:
description: "排除文件/目录 (以逗号间隔)\n Files/Directories to exclude(comma-separated)"
required: false
default: ''
branch:
description: "要格式化的分支 | Branch to format"
required: true
default: ''
pr_number:
description: "PR编号 | PR Number"
required: true
default: ''
permissions:
contents: write
pull-requests: read
jobs:
format-code:
if: |
github.repository_owner != 'RT-Thread'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.branch }}
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
lfs: false
- name: Install clang-format
run: sudo apt-get update && sudo apt-get install -y clang-format
- name: Check clang-format version
run: |
echo "📋 clang-format version information:"
clang-format --version
echo "📋 Detailed version info:"
clang-format -version
# 检查支持的功能
echo "📋 Checking supported features..."
clang-format --help | grep -i "align\|consecutive" || echo "No align/consecutive options found"
- name: Get changed files from PR
id: get-pr-files
run: |
max_retries=3
retry_count=0
changed_files=""
api_response=""
# 获取PR编号workflow_dispatch时需要手动输入
PR_NUMBER="${{ github.event.inputs.pr_number }}"
if [ -z "$PR_NUMBER" ]; then
echo "Error: PR number is required"
exit 1
fi
echo "Fetching changed files for PR #$PR_NUMBER..."
while [ $retry_count -lt $max_retries ]; do
# 使用一个curl调用同时获取响应内容和状态码
api_response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github.v3+json" \
"https://api.github.com/repos/RT-Thread/rt-thread/pulls/$PR_NUMBER/files")
# 分离HTTP状态码和响应内容
http_status=$(echo "$api_response" | tail -1)
api_response=$(echo "$api_response" | sed '$d')
echo "HTTP Status: $http_status"
# 检查HTTP状态码
if [ "$http_status" -ne 200 ]; then
echo "Retry $((retry_count+1)): HTTP $http_status - API response error"
echo "API Response: $api_response"
sleep 5
((retry_count++))
continue
fi
# 验证响应是否为有效JSON且包含文件数组
if jq -e 'if type=="array" then .[0].filename else empty end' <<<"$api_response" >/dev/null 2>&1; then
changed_files=$(jq -r '.[].filename' <<<"$api_response")
break
else
echo "Retry $((retry_count+1)): API response not ready or invalid format"
echo "API Response: $api_response"
sleep 5
((retry_count++))
fi
done
if [ -z "$changed_files" ]; then
echo "Error: Failed to get changed files after $max_retries attempts"
echo "Final API Response: $api_response"
exit 1
fi
# 将文件列表转换为逗号分隔格式
changed_files_comma=$(echo "$changed_files" | tr '\n' ',' | sed 's/,$//')
echo "Successfully fetched $(echo "$changed_files" | wc -l) changed files"
# 设置输出
echo "all_changed_files=$changed_files_comma" >> $GITHUB_OUTPUT
echo "changed_files_count=$(echo "$changed_files" | wc -l)" >> $GITHUB_OUTPUT
- name: Find source files to format
id: find-files
run: |
# 获取PR中修改的文件
CHANGED_FILES="${{ steps.get-pr-files.outputs.all_changed_files }}"
# 将逗号分隔的文件列表转换为换行分隔
CHANGED_FILES_LINES=$(echo "$CHANGED_FILES" | tr ',' '\n')
# 美化打印PR中修改的文件
echo "📋 PR中修改的文件列表:"
echo "┌───────────────────────────────────────────────────────"
count=1
while IFS= read -r file; do
if [ -n "$file" ]; then
echo "│ $count. $file"
((count++))
fi
done <<< "$CHANGED_FILES_LINES"
echo "└───────────────────────────────────────────────────────"
echo "总共修改了 $((count-1)) 个文件"
# 如果没有修改的文件,退出
if [ -z "$CHANGED_FILES" ]; then
echo "❌ PR中没有修改的文件"
echo "files_count=0" >> $GITHUB_OUTPUT
exit 0
fi
# 继续使用CHANGED_FILES进行后续处理
CHANGED_FILES="$CHANGED_FILES_LINES"
# 过滤出需要格式化的源文件扩展clang-format支持的文件类型
FILES=""
while IFS= read -r file; do
if [ -n "$file" ] && [[ "$file" =~ \.(cpp|h|c|hpp|cc|hh|C|H|cp|cxx|hxx|inc|inl|ipp|tpp|txx)$ ]]; then
FILES="$FILES$file"$'\n'
fi
done <<< "$CHANGED_FILES"
FILES=$(echo "$FILES" | sort | uniq)
# 处理排除模式
EXCLUDE_PATTERNS="${{ github.event.inputs.exclude_patterns }}"
if [ -n "$EXCLUDE_PATTERNS" ] && [ -n "$FILES" ]; then
IFS=',' read -ra PATTERNS <<< "$EXCLUDE_PATTERNS"
for pattern in "${PATTERNS[@]}"; do
pattern=$(echo "$pattern" | xargs) # 去除空格
if [ -n "$pattern" ]; then
# 去除末尾的斜杠(如果有)
pattern=${pattern%/}
echo "排除模式: $pattern"
# 使用 grep 过滤排除模式
FILES=$(echo "$FILES" | grep -v "$pattern" || echo "$FILES")
fi
done
fi
if [ -z "$FILES" ]; then
echo "❌ 没有需要格式化的文件(可能都被排除了)"
echo "files_count=0" >> $GITHUB_OUTPUT
exit 0
fi
# 显示找到的文件用于调试
echo "🎯 需要格式化的文件:"
echo "┌───────────────────────────────────────────────────────"
count=1
while IFS= read -r file; do
if [ -n "$file" ]; then
echo "│ $count. $file"
((count++))
fi
done <<< "$FILES"
echo "└───────────────────────────────────────────────────────"
FILE_COUNT=$(echo "$FILES" | wc -l)
echo "找到 $FILE_COUNT 个需要格式化的文件"
echo "files_count=$FILE_COUNT" >> $GITHUB_OUTPUT
# 将文件列表保存为多行输出
echo "files_list<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Clean up temporary files
run: |
rm -f changed_files.txt
rm -f format_files.sh
echo "✅ 临时文件清理完成"
- name: Format code with clang-format
if: steps.find-files.outputs.files_count != '0'
run: |
echo "开始格式化代码..."
FILES="${{ steps.find-files.outputs.files_list }}"
# 使用clang-format批量格式化文件
echo "$FILES" | xargs -I {} sh -c '
file="{}"
if [ -f "$file" ]; then
echo "📝 格式化: $file"
clang-format -style=file -i "$file"
if [ $? -eq 0 ]; then
echo "✅ 格式化成功: $file"
else
echo "❌ 格式化失败: $file"
exit 1
fi
else
echo "⚠️ 文件不存在: $file"
fi
'
echo "✅ 代码格式化完成"
- name: Check for changes
id: check-changes
run: |
if git diff --quiet; then
echo "✅ 代码无需格式化"
echo "has_changes=false" >> $GITHUB_OUTPUT
else
echo "📋 检测到格式化更改:"
git diff --name-only
echo "has_changes=true" >> $GITHUB_OUTPUT
fi
- name: Commit and push changes
if: steps.check-changes.outputs.has_changes == 'true'
run: |
git config --local user.email "github-actions[bot]@users.noreply.github.com"
git config --local user.name "github-actions[bot]"
git add -A
git commit -m "style: format code with clang-format [skip ci]"
git push origin HEAD:${{ github.event.inputs.branch }}
echo "✅ 代码格式化完成并已推送到分支 ${{ github.event.inputs.branch }}"
- name: Summary
run: |
echo "=== 格式化总结 ==="
echo "分支: ${{ github.event.inputs.branch }}"
echo "排除模式: ${{ github.event.inputs.exclude_patterns || '无' }}"
echo "处理文件数: ${{ steps.find-files.outputs.files_count }}"
echo "有更改: ${{ steps.check-changes.outputs.has_changes }}"
echo "clang-format 版本: $(clang-format --version | head -1)"

115
.github/workflows/pr_format_bot.yml vendored Normal file
View File

@@ -0,0 +1,115 @@
name: PR Format Notification
on:
pull_request_target:
types: [opened, synchronize]
permissions:
pull-requests: write
contents: read
jobs:
notify-format:
if: github.repository_owner == 'RT-Thread'
runs-on: ubuntu-latest
steps:
- name: Check if first commit and add comment
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
echo "Event action: ${{ github.event.action }}"
# 获取 PR 的提交信息
commits=$(curl -s \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/commits")
# 检查 API 响应是否为数组
if echo "$commits" | jq -e 'type == "array"' > /dev/null; then
commit_count=$(echo "$commits" | jq '. | length')
echo "PR commit count: $commit_count"
should_comment=false
if [ "${{ github.event.action }}" = "opened" ]; then
should_comment=true
elif [ "${{ github.event.action }}" = "synchronize" ] && [ "$commit_count" -eq 1 ]; then
should_comment=true
fi
if [ "$should_comment" = true ]; then
echo "Adding format notification comment..."
# 构建工作流链接
branch="${{ github.event.pull_request.head.ref }}"
fork_repo="${{ github.event.pull_request.head.repo.full_name }}"
workflow_url="https://github.com/${fork_repo}/actions/workflows/clang-format.yml"
direct_link="${workflow_url}?branch=${branch}"
# 使用数组存储多行消息
message_lines=(
"**👋 感谢您对 RT-Thread 的贡献Thank you for your contribution to RT-Thread!**"
""
"为确保代码符合 RT-Thread 的编码规范,请在你的仓库中执行以下步骤运行代码格式化工作流。"
"To ensure your code complies with RT-Thread's coding style, please run the code formatting workflow by following the steps below."
""
"---"
""
"### 🛠 操作步骤 | Steps"
""
"1. **前往 Actions 页面 | Go to the Actions page**"
"[点击进入工作流 → | Click to open workflow →](${direct_link})"
""
"2. **点击 \`Run workflow\` | Click \`Run workflow\`**"
"- 设置需排除的文件/目录(目录请以\"/\"结尾)"
"Set files/directories to exclude (directories should end with \"/\")"
"- 将目标分支设置为 \ Set the target branch to**\`${branch}\`**"
"- 设置PR number为 \ Set the PR number to**\`${{ github.event.number }}\`**"
""
"3. **等待工作流完成 | Wait for the workflow to complete**"
"格式化后的代码将自动推送至你的分支。"
"The formatted code will be automatically pushed to your branch."
""
"完成后,提交将自动更新至 \`${branch}\` 分支,关联的 Pull Request 也会同步更新。"
"Once completed, commits will be pushed to the \`${branch}\` branch automatically, and the related Pull Request will be updated."
""
"如有问题欢迎联系我们,再次感谢您的贡献!💐"
"If you have any questions, feel free to reach out. Thanks again for your contribution!"
)
# 拼接数组为多行字符串
message=$(printf "%s\n" "${message_lines[@]}")
echo "Message content:"
echo "$message"
# 使用 jq 安全地构建 JSON 负载
json_payload=$(jq -n --arg body "$message" '{"body": $body}')
# 发送评论到 PR
response=$(curl -s -w "\n%{http_code}" \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \
-d "$json_payload")
# 提取 HTTP 状态码和响应体
http_code=$(echo "$response" | tail -n1)
response_body=$(echo "$response" | sed '$d')
if [ "$http_code" -eq 201 ]; then
echo "Format notification comment added successfully"
echo "Comment URL: $(echo "$response_body" | jq -r '.html_url')"
else
echo "Failed to add comment. HTTP status: $http_code"
echo "Response: $response_body"
exit 1
fi
else
echo "Not the first commit, skipping comment"
fi
else
echo "Failed to get commits from GitHub API"
echo "Response: $commits"
exit 1
fi