Skip to content

Commit da94bf0

Browse files
authored
[Workflow] Add new code format helper. (#66684)
This helper will format python files with black/darker and C/C++ files with clang-format. The format helper is written so that we can expand it with new formatters in the future like clang-tidy.
1 parent 695a5a6 commit da94bf0

File tree

5 files changed

+342
-39
lines changed

5 files changed

+342
-39
lines changed

.github/workflows/pr-code-format.yml

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
name: "Check code formatting"
2+
on: pull_request
3+
permissions:
4+
pull-requests: write
5+
6+
jobs:
7+
code_formatter:
8+
runs-on: ubuntu-latest
9+
steps:
10+
- name: Fetch LLVM sources
11+
uses: actions/checkout@v4
12+
with:
13+
persist-credentials: false
14+
fetch-depth: 2
15+
16+
- name: Get changed files
17+
id: changed-files
18+
uses: tj-actions/changed-files@v39
19+
with:
20+
separator: ","
21+
22+
- name: "Listed files"
23+
run: |
24+
echo "Formatting files:"
25+
echo "${{ steps.changed-files.outputs.all_changed_files }}"
26+
27+
- name: Install clang-format
28+
uses: aminya/setup-cpp@v1
29+
with:
30+
clangformat: 16.0.6
31+
32+
- name: Setup Python env
33+
uses: actions/setup-python@v4
34+
with:
35+
python-version: '3.11'
36+
cache: 'pip'
37+
cache-dependency-path: 'llvm/utils/git/requirements_formatting.txt'
38+
39+
- name: Install python dependencies
40+
run: pip install -r llvm/utils/git/requirements_formatting.txt
41+
42+
- name: Run code formatter
43+
env:
44+
GITHUB_PR_NUMBER: ${{ github.event.pull_request.number }}
45+
START_REV: ${{ github.event.pull_request.base.sha }}
46+
END_REV: ${{ github.event.pull_request.head.sha }}
47+
CHANGED_FILES: ${{ steps.changed-files.outputs.all_changed_files }}
48+
run: |
49+
python llvm/utils/git/code-format-helper.py \
50+
--token ${{ secrets.GITHUB_TOKEN }} \
51+
--issue-number $GITHUB_PR_NUMBER \
52+
--start-rev $START_REV \
53+
--end-rev $END_REV \
54+
--changed-files "$CHANGED_FILES"

.github/workflows/pr-python-format.yml

-39
This file was deleted.

llvm/utils/git/code-format-helper.py

+233
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
#!/usr/bin/env python3
2+
#
3+
# ====- code-format-helper, runs code formatters from the ci --*- python -*--==#
4+
#
5+
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
6+
# See https://llvm.org/LICENSE.txt for license information.
7+
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8+
#
9+
# ==-------------------------------------------------------------------------==#
10+
11+
import argparse
12+
import os
13+
import subprocess
14+
import sys
15+
from functools import cached_property
16+
17+
import github
18+
from github import IssueComment, PullRequest
19+
20+
21+
class FormatHelper:
22+
COMMENT_TAG = "<!--LLVM CODE FORMAT COMMENT: {fmt}-->"
23+
name = "unknown"
24+
25+
@property
26+
def comment_tag(self) -> str:
27+
return self.COMMENT_TAG.replace("fmt", self.name)
28+
29+
def format_run(self, changed_files: [str], args: argparse.Namespace) -> str | None:
30+
pass
31+
32+
def pr_comment_text(self, diff: str) -> str:
33+
return f"""
34+
{self.comment_tag}
35+
36+
:warning: {self.friendly_name}, {self.name} found issues in your code. :warning:
37+
38+
<details>
39+
<summary>
40+
You can test this locally with the following command:
41+
</summary>
42+
43+
``````````bash
44+
{self.instructions}
45+
``````````
46+
47+
</details>
48+
49+
<details>
50+
<summary>
51+
View the diff from {self.name} here.
52+
</summary>
53+
54+
``````````diff
55+
{diff}
56+
``````````
57+
58+
</details>
59+
"""
60+
61+
def find_comment(
62+
self, pr: PullRequest.PullRequest
63+
) -> IssueComment.IssueComment | None:
64+
for comment in pr.as_issue().get_comments():
65+
if self.comment_tag in comment.body:
66+
return comment
67+
return None
68+
69+
def update_pr(self, diff: str, args: argparse.Namespace):
70+
repo = github.Github(args.token).get_repo(args.repo)
71+
pr = repo.get_issue(args.issue_number).as_pull_request()
72+
73+
existing_comment = self.find_comment(pr)
74+
pr_text = self.pr_comment_text(diff)
75+
76+
if existing_comment:
77+
existing_comment.edit(pr_text)
78+
else:
79+
pr.as_issue().create_comment(pr_text)
80+
81+
def update_pr_success(self, args: argparse.Namespace):
82+
repo = github.Github(args.token).get_repo(args.repo)
83+
pr = repo.get_issue(args.issue_number).as_pull_request()
84+
85+
existing_comment = self.find_comment(pr)
86+
if existing_comment:
87+
existing_comment.edit(
88+
f"""
89+
{self.comment_tag}
90+
:white_check_mark: With the latest revision this PR passed the {self.friendly_name}.
91+
"""
92+
)
93+
94+
def run(self, changed_files: [str], args: argparse.Namespace):
95+
diff = self.format_run(changed_files, args)
96+
if diff:
97+
self.update_pr(diff, args)
98+
return False
99+
else:
100+
self.update_pr_success(args)
101+
return True
102+
103+
104+
class ClangFormatHelper(FormatHelper):
105+
name = "clang-format"
106+
friendly_name = "C/C++ code formatter"
107+
108+
@property
109+
def instructions(self):
110+
return " ".join(self.cf_cmd)
111+
112+
@cached_property
113+
def libcxx_excluded_files(self):
114+
with open("libcxx/utils/data/ignore_format.txt", "r") as ifd:
115+
return [excl.strip() for excl in ifd.readlines()]
116+
117+
def should_be_excluded(self, path: str) -> bool:
118+
if path in self.libcxx_excluded_files:
119+
print(f"Excluding file {path}")
120+
return True
121+
return False
122+
123+
def filter_changed_files(self, changed_files: [str]) -> [str]:
124+
filtered_files = []
125+
for path in changed_files:
126+
_, ext = os.path.splitext(path)
127+
if ext in (".cpp", ".c", ".h", ".hpp", ".hxx", ".cxx"):
128+
if not self.should_be_excluded(path):
129+
filtered_files.append(path)
130+
return filtered_files
131+
132+
def format_run(self, changed_files: [str], args: argparse.Namespace) -> str | None:
133+
cpp_files = self.filter_changed_files(changed_files)
134+
if not cpp_files:
135+
return
136+
cf_cmd = [
137+
"git-clang-format",
138+
"--diff",
139+
args.start_rev,
140+
args.end_rev,
141+
"--",
142+
] + cpp_files
143+
print(f"Running: {' '.join(cf_cmd)}")
144+
self.cf_cmd = cf_cmd
145+
proc = subprocess.run(cf_cmd, capture_output=True)
146+
147+
# formatting needed
148+
if proc.returncode == 1:
149+
return proc.stdout.decode("utf-8")
150+
151+
return None
152+
153+
154+
class DarkerFormatHelper(FormatHelper):
155+
name = "darker"
156+
friendly_name = "Python code formatter"
157+
158+
@property
159+
def instructions(self):
160+
return " ".join(self.darker_cmd)
161+
162+
def filter_changed_files(self, changed_files: [str]) -> [str]:
163+
filtered_files = []
164+
for path in changed_files:
165+
name, ext = os.path.splitext(path)
166+
if ext == ".py":
167+
filtered_files.append(path)
168+
169+
return filtered_files
170+
171+
def format_run(self, changed_files: [str], args: argparse.Namespace) -> str | None:
172+
py_files = self.filter_changed_files(changed_files)
173+
if not py_files:
174+
return
175+
darker_cmd = [
176+
"darker",
177+
"--check",
178+
"--diff",
179+
"-r",
180+
f"{args.start_rev}..{args.end_rev}",
181+
] + py_files
182+
print(f"Running: {' '.join(darker_cmd)}")
183+
self.darker_cmd = darker_cmd
184+
proc = subprocess.run(darker_cmd, capture_output=True)
185+
186+
# formatting needed
187+
if proc.returncode == 1:
188+
return proc.stdout.decode("utf-8")
189+
190+
return None
191+
192+
193+
ALL_FORMATTERS = (DarkerFormatHelper(), ClangFormatHelper())
194+
195+
if __name__ == "__main__":
196+
parser = argparse.ArgumentParser()
197+
parser.add_argument(
198+
"--token", type=str, required=True, help="GitHub authentiation token"
199+
)
200+
parser.add_argument(
201+
"--repo",
202+
type=str,
203+
default=os.getenv("GITHUB_REPOSITORY", "llvm/llvm-project"),
204+
help="The GitHub repository that we are working with in the form of <owner>/<repo> (e.g. llvm/llvm-project)",
205+
)
206+
parser.add_argument("--issue-number", type=int, required=True)
207+
parser.add_argument(
208+
"--start-rev",
209+
type=str,
210+
required=True,
211+
help="Compute changes from this revision.",
212+
)
213+
parser.add_argument(
214+
"--end-rev", type=str, required=True, help="Compute changes to this revision"
215+
)
216+
parser.add_argument(
217+
"--changed-files",
218+
type=str,
219+
help="Comma separated list of files that has been changed",
220+
)
221+
222+
args = parser.parse_args()
223+
224+
changed_files = []
225+
if args.changed_files:
226+
changed_files = args.changed_files.split(",")
227+
228+
exit_code = 0
229+
for fmt in ALL_FORMATTERS:
230+
if not fmt.run(changed_files, args):
231+
exit_code = 1
232+
233+
sys.exit(exit_code)
+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#
2+
# This file is autogenerated by pip-compile with Python 3.11
3+
# by the following command:
4+
#
5+
# pip-compile --output-file=llvm/utils/git/requirements_formatting.txt llvm/utils/git/requirements_formatting.txt.in
6+
#
7+
black==23.9.1
8+
# via
9+
# -r llvm/utils/git/requirements_formatting.txt.in
10+
# darker
11+
certifi==2023.7.22
12+
# via requests
13+
cffi==1.15.1
14+
# via
15+
# cryptography
16+
# pynacl
17+
charset-normalizer==3.2.0
18+
# via requests
19+
click==8.1.7
20+
# via black
21+
cryptography==41.0.3
22+
# via pyjwt
23+
darker==1.7.2
24+
# via -r llvm/utils/git/requirements_formatting.txt.in
25+
deprecated==1.2.14
26+
# via pygithub
27+
idna==3.4
28+
# via requests
29+
mypy-extensions==1.0.0
30+
# via black
31+
packaging==23.1
32+
# via black
33+
pathspec==0.11.2
34+
# via black
35+
platformdirs==3.10.0
36+
# via black
37+
pycparser==2.21
38+
# via cffi
39+
pygithub==1.59.1
40+
# via -r llvm/utils/git/requirements_formatting.txt.in
41+
pyjwt[crypto]==2.8.0
42+
# via pygithub
43+
pynacl==1.5.0
44+
# via pygithub
45+
requests==2.31.0
46+
# via pygithub
47+
toml==0.10.2
48+
# via darker
49+
urllib3==2.0.4
50+
# via requests
51+
wrapt==1.15.0
52+
# via deprecated
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
black~=23.0
2+
darker==1.7.2
3+
PyGithub==1.59.1

0 commit comments

Comments
 (0)