Skip to content

Commit 37159d7

Browse files
committed
tools: add clang-format formatting script for CI
1 parent 1034e5b commit 37159d7

File tree

3 files changed

+296
-8
lines changed

3 files changed

+296
-8
lines changed

.clang-format

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
#
55
# clang-format -style=llvm -dump-config > .clang-format
66
#
7-
---
87
Language: Cpp
98
BasedOnStyle: LLVM
109
AccessModifierOffset: -1
@@ -46,13 +45,13 @@ AlignTrailingComments:
4645
OverEmptyLines: 1
4746
AllowAllArgumentsOnNextLine: false
4847
AllowAllParametersOfDeclarationOnNextLine: false
49-
AllowShortBlocksOnASingleLine: Always
48+
AllowShortBlocksOnASingleLine: false
5049
AllowShortCaseLabelsOnASingleLine: false
5150
AllowShortEnumsOnASingleLine: false
5251
AllowShortFunctionsOnASingleLine: None
53-
AllowShortIfStatementsOnASingleLine: WithoutElse
52+
AllowShortIfStatementsOnASingleLine: false
5453
AllowShortLambdasOnASingleLine: All
55-
AllowShortLoopsOnASingleLine: true
54+
AllowShortLoopsOnASingleLine: false
5655
AlwaysBreakAfterDefinitionReturnType: None
5756
AlwaysBreakAfterReturnType: None
5857
AlwaysBreakBeforeMultilineStrings: false
@@ -62,6 +61,7 @@ AttributeMacros:
6261
BinPackArguments: true
6362
BinPackParameters: true
6463
BitFieldColonSpacing: Both
64+
BreakBeforeBraces: Custom
6565
BraceWrapping:
6666
AfterCaseLabel: false
6767
AfterClass: true
@@ -86,7 +86,6 @@ BreakAfterJavaFieldAnnotations: false
8686
BreakArrays: false
8787
BreakBeforeBinaryOperators: NonAssignment
8888
BreakBeforeConceptDeclarations: Always
89-
BreakBeforeBraces: Custom
9089
BreakBeforeInlineASMColon: OnlyMultiline
9190
BreakBeforeTernaryOperators: true
9291
BreakConstructorInitializers: AfterColon
@@ -237,6 +236,4 @@ WhitespaceSensitiveMacros:
237236
- CF_SWIFT_NAME
238237
- NS_SWIFT_NAME
239238
- PP_STRINGIZE
240-
- STRINGIZE
241-
---
242-
239+
- STRINGIZE
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
name: Code Format with Clang-Format
2+
3+
on:
4+
workflow_dispatch:
5+
inputs:
6+
exclude_patterns:
7+
description: "排除文件/目录 (以逗号间隔)\n Files/Directories to exclude(comma-separated)"
8+
required: false
9+
default: ''
10+
branch:
11+
description: "要格式化的分支 | Branch to format"
12+
required: true
13+
default: ''
14+
15+
permissions:
16+
contents: write
17+
pull-requests: read
18+
19+
jobs:
20+
format-code:
21+
if: |
22+
github.repository_owner != 'RT-Thread'
23+
runs-on: ubuntu-latest
24+
25+
steps:
26+
- name: Checkout code
27+
uses: actions/checkout@v4
28+
with:
29+
ref: ${{ github.event.inputs.branch }}
30+
fetch-depth: 0
31+
token: ${{ secrets.GITHUB_TOKEN }}
32+
# 添加这行确保使用LF行尾符
33+
lfs: false
34+
35+
- name: Install clang-format
36+
run: sudo apt-get update && sudo apt-get install -y clang-format
37+
38+
- name: Check clang-format version
39+
run: |
40+
echo "📋 clang-format version information:"
41+
clang-format --version
42+
echo "📋 Detailed version info:"
43+
clang-format -version
44+
# 检查支持的功能
45+
echo "📋 Checking supported features..."
46+
clang-format --help | grep -i "align\|consecutive" || echo "No align/consecutive options found"
47+
48+
- name: Get changed files from PR
49+
id: changed-files
50+
uses: tj-actions/changed-files@v44
51+
with:
52+
since_last_remote_commit: true
53+
separator: ","
54+
55+
- name: Find source files to format
56+
id: find-files
57+
run: |
58+
# 获取PR中修改的文件
59+
CHANGED_FILES="${{ steps.changed-files.outputs.all_changed_files }}"
60+
echo "PR中修改的文件: $CHANGED_FILES"
61+
62+
# 如果没有修改的文件,退出
63+
if [ -z "$CHANGED_FILES" ]; then
64+
echo "❌ PR中没有修改的文件"
65+
echo "files_count=0" >> $GITHUB_OUTPUT
66+
exit 0
67+
fi
68+
69+
# 过滤出需要格式化的源文件(扩展clang-format支持的文件类型)
70+
FILES=""
71+
IFS=',' read -ra FILE_ARRAY <<< "$CHANGED_FILES"
72+
for file in "${FILE_ARRAY[@]}"; do
73+
if [[ "$file" =~ \.(cpp|h|c|hpp|cc|hh|C|H|cp|cxx|hxx|inc|inl|ipp|tpp|txx)$ ]]; then
74+
FILES="$FILES$file"$'\n'
75+
fi
76+
done
77+
78+
FILES=$(echo "$FILES" | sort | uniq)
79+
80+
# 处理排除模式
81+
EXCLUDE_PATTERNS="${{ github.event.inputs.exclude_patterns }}"
82+
if [ -n "$EXCLUDE_PATTERNS" ] && [ -n "$FILES" ]; then
83+
IFS=',' read -ra PATTERNS <<< "$EXCLUDE_PATTERNS"
84+
for pattern in "${PATTERNS[@]}"; do
85+
pattern=$(echo "$pattern" | xargs) # 去除空格
86+
if [ -n "$pattern" ]; then
87+
# 去除末尾的斜杠(如果有)
88+
pattern=${pattern%/}
89+
echo "排除模式: $pattern"
90+
# 使用 grep 过滤排除模式
91+
FILES=$(echo "$FILES" | grep -v "$pattern" || echo "$FILES")
92+
fi
93+
done
94+
fi
95+
96+
if [ -z "$FILES" ]; then
97+
echo "❌ 没有需要格式化的文件(可能都被排除了)"
98+
echo "files_count=0" >> $GITHUB_OUTPUT
99+
exit 0
100+
fi
101+
102+
# 显示找到的文件用于调试
103+
echo "需要格式化的文件:"
104+
echo "$FILES"
105+
106+
FILE_COUNT=$(echo "$FILES" | wc -l)
107+
echo "找到 $FILE_COUNT 个需要格式化的文件"
108+
echo "files_count=$FILE_COUNT" >> $GITHUB_OUTPUT
109+
110+
# 将文件列表保存为多行输出
111+
echo "files_list<<EOF" >> $GITHUB_OUTPUT
112+
echo "$FILES" >> $GITHUB_OUTPUT
113+
echo "EOF" >> $GITHUB_OUTPUT
114+
115+
- name: Format code with clang-format
116+
if: steps.find-files.outputs.files_count != '0'
117+
run: |
118+
echo "开始格式化代码..."
119+
FILES="${{ steps.find-files.outputs.files_list }}"
120+
121+
# 使用clang-format批量格式化文件
122+
echo "$FILES" | xargs -I {} sh -c '
123+
file="{}"
124+
if [ -f "$file" ]; then
125+
echo "📝 格式化: $file"
126+
clang-format -style=file -i "$file"
127+
if [ $? -eq 0 ]; then
128+
echo "✅ 格式化成功: $file"
129+
else
130+
echo "❌ 格式化失败: $file"
131+
exit 1
132+
fi
133+
else
134+
echo "⚠️ 文件不存在: $file"
135+
fi
136+
'
137+
138+
echo "✅ 代码格式化完成"
139+
140+
- name: Check for changes
141+
id: check-changes
142+
run: |
143+
if git diff --quiet; then
144+
echo "✅ 代码无需格式化"
145+
echo "has_changes=false" >> $GITHUB_OUTPUT
146+
else
147+
echo "📋 检测到格式化更改:"
148+
git diff --name-only
149+
echo "has_changes=true" >> $GITHUB_OUTPUT
150+
fi
151+
152+
- name: Commit and push changes
153+
if: steps.check-changes.outputs.has_changes == 'true'
154+
run: |
155+
git config --local user.email "github-actions[bot]@users.noreply.github.com"
156+
git config --local user.name "github-actions[bot]"
157+
158+
git add -A
159+
git commit -m "style: format code with clang-format [skip ci]"
160+
git push origin HEAD:${{ github.event.inputs.branch }}
161+
162+
echo "✅ 代码格式化完成并已推送到分支 ${{ github.event.inputs.branch }}"
163+
164+
- name: Summary
165+
run: |
166+
echo "=== 格式化总结 ==="
167+
echo "分支: ${{ github.event.inputs.branch }}"
168+
echo "排除模式: ${{ github.event.inputs.exclude_patterns || '无' }}"
169+
echo "处理文件数: ${{ steps.find-files.outputs.files_count }}"
170+
echo "有更改: ${{ steps.check-changes.outputs.has_changes }}"
171+
echo "clang-format 版本: $(clang-format --version | head -1)"

.github/workflows/pr-notify.yml

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
name: PR Format Notification
2+
on:
3+
pull_request_target:
4+
types: [opened, synchronize]
5+
6+
permissions:
7+
pull-requests: write
8+
contents: read
9+
10+
jobs:
11+
notify-format:
12+
if: github.repository_owner == 'RT-Thread'
13+
runs-on: ubuntu-latest
14+
steps:
15+
- name: Check if first commit and add comment
16+
env:
17+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
18+
run: |
19+
echo "Event action: ${{ github.event.action }}"
20+
21+
# 获取 PR 的提交信息
22+
commits=$(curl -s \
23+
-H "Accept: application/vnd.github.v3+json" \
24+
-H "Authorization: Bearer $GITHUB_TOKEN" \
25+
"https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/commits")
26+
27+
# 检查 API 响应是否为数组
28+
if echo "$commits" | jq -e 'type == "array"' > /dev/null; then
29+
commit_count=$(echo "$commits" | jq '. | length')
30+
echo "PR commit count: $commit_count"
31+
32+
should_comment=false
33+
if [ "${{ github.event.action }}" = "opened" ]; then
34+
should_comment=true
35+
elif [ "${{ github.event.action }}" = "synchronize" ] && [ "$commit_count" -eq 1 ]; then
36+
should_comment=true
37+
fi
38+
39+
if [ "$should_comment" = true ]; then
40+
echo "Adding format notification comment..."
41+
42+
# 构建工作流链接
43+
branch="${{ github.event.pull_request.head.ref }}"
44+
fork_repo="${{ github.event.pull_request.head.repo.full_name }}"
45+
workflow_url="https://github.com/${fork_repo}/actions/workflows/clang-format.yml"
46+
direct_link="${workflow_url}?branch=${branch}"
47+
48+
# 使用数组存储多行消息
49+
message_lines=(
50+
"**👋 感谢您对 RT-Thread 的贡献!Thank you for your contribution to RT-Thread!**"
51+
""
52+
"为确保代码符合 RT-Thread 的编码规范,请在你的仓库中执行以下步骤运行代码格式化工作流。"
53+
"To ensure your code complies with RT-Thread's coding style, please run the code formatting workflow by following the steps below."
54+
""
55+
"---"
56+
""
57+
"### 🛠 操作步骤 | Steps"
58+
""
59+
"1. **前往 Actions 页面 | Go to the Actions page**"
60+
"[点击进入工作流 → | Click to open workflow →](${direct_link})"
61+
""
62+
"2. **点击 \`Run workflow\` | Click \`Run workflow\`**"
63+
"- 设置需排除的文件/目录(目录请以\"/\"结尾)"
64+
"Set files/directories to exclude (directories should end with \"/\")"
65+
"- 将目标分支设置为:**\`${branch}\`**"
66+
"Set the target branch to: **\`${branch}\`**"
67+
""
68+
"3. **等待工作流完成 | Wait for the workflow to complete**"
69+
"格式化后的代码将自动推送至你的分支。"
70+
"The formatted code will be automatically pushed to your branch."
71+
""
72+
"---"
73+
""
74+
"🔗 **快速链接 | Quick Link**:"
75+
"[👉 运行格式化工作流 | Run Format Workflow](${direct_link})"
76+
""
77+
"完成后,提交将自动更新至 \`${branch}\` 分支,关联的 Pull Request 也会同步更新。"
78+
"Once completed, commits will be pushed to the \`${branch}\` branch automatically, and the related Pull Request will be updated."
79+
""
80+
"如有问题欢迎联系我们,再次感谢您的贡献!💐"
81+
"If you have any questions, feel free to reach out. Thanks again for your contribution!"
82+
)
83+
84+
# 拼接数组为多行字符串
85+
message=$(printf "%s\n" "${message_lines[@]}")
86+
87+
echo "Message content:"
88+
echo "$message"
89+
90+
# 使用 jq 安全地构建 JSON 负载
91+
json_payload=$(jq -n --arg body "$message" '{"body": $body}')
92+
93+
# 发送评论到 PR
94+
response=$(curl -s -w "\n%{http_code}" \
95+
-X POST \
96+
-H "Accept: application/vnd.github.v3+json" \
97+
-H "Authorization: Bearer $GITHUB_TOKEN" \
98+
"https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \
99+
-d "$json_payload")
100+
101+
# 提取 HTTP 状态码和响应体
102+
http_code=$(echo "$response" | tail -n1)
103+
response_body=$(echo "$response" | sed '$d')
104+
105+
if [ "$http_code" -eq 201 ]; then
106+
echo "Format notification comment added successfully"
107+
echo "Comment URL: $(echo "$response_body" | jq -r '.html_url')"
108+
else
109+
echo "Failed to add comment. HTTP status: $http_code"
110+
echo "Response: $response_body"
111+
exit 1
112+
fi
113+
else
114+
echo "Not the first commit, skipping comment"
115+
fi
116+
else
117+
echo "Failed to get commits from GitHub API"
118+
echo "Response: $commits"
119+
exit 1
120+
fi

0 commit comments

Comments
 (0)