summaryrefslogtreecommitdiff
path: root/llvm/utils/git/code-lint-helper.py
blob: 1232f3ab0d3707c636eb2c8f714b76688e2b6489 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
#!/usr/bin/env python3
#
# ====- clang-tidy-helper, runs clang-tidy from the ci --*- python -*-------==#
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ==-------------------------------------------------------------------------==#
"""A helper script to run clang-tidy linter in GitHub actions

This script is run by GitHub actions to ensure that the code in PR's conform to
the coding style of LLVM. The canonical source of this script is in the LLVM
source tree under llvm/utils/git.

You can learn more about the LLVM coding style on llvm.org:
https://llvm.org/docs/CodingStandards.html
"""

import argparse
import os
import subprocess
import sys
from typing import List, Optional


class LintArgs:
    start_rev: str = None
    end_rev: str = None
    repo: str = None
    changed_files: List[str] = []
    token: str = None
    verbose: bool = True
    issue_number: int = 0
    build_path: str = "build"
    clang_tidy_binary: str = "clang-tidy"

    def __init__(self, args: argparse.Namespace = None) -> None:
        if not args is None:
            self.start_rev = args.start_rev
            self.end_rev = args.end_rev
            self.repo = args.repo
            self.token = args.token
            self.changed_files = args.changed_files
            self.issue_number = args.issue_number
            self.verbose = args.verbose
            self.build_path = args.build_path
            self.clang_tidy_binary = args.clang_tidy_binary


COMMENT_TAG = "<!--LLVM CODE LINT COMMENT: clang-tidy-->"


def get_instructions(cpp_files: List[str]) -> str:
    files_str = " ".join(cpp_files)
    return f"""
git diff -U0 origin/main...HEAD -- {files_str} |
python3 clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py \\
  -path build -p1 -quiet"""


def clean_clang_tidy_output(output: str) -> Optional[str]:
    """
    - Remove 'Running clang-tidy in X threads...' line
    - Remove 'N warnings generated.' line
    - Strip leading workspace path from file paths
    """
    if not output or output == "No relevant changes found.":
        return None

    lines = output.split("\n")
    cleaned_lines = []

    for line in lines:
        if line.startswith("Running clang-tidy in") or line.endswith("generated."):
            continue

        # Remove everything up to rightmost "llvm-project/" for correct files names
        idx = line.rfind("llvm-project/")
        if idx != -1:
            line = line[idx + len("llvm-project/") :]

        cleaned_lines.append(line)

    if cleaned_lines:
        return "\n".join(cleaned_lines)
    return None


# TODO: Add more rules when enabling other projects to use clang-tidy in CI.
def should_lint_file(filepath: str) -> bool:
    return filepath.startswith("clang-tools-extra/clang-tidy/")


def filter_changed_files(changed_files: List[str]) -> List[str]:
    filtered_files = []
    for filepath in changed_files:
        _, ext = os.path.splitext(filepath)
        if ext not in (".cpp", ".c", ".h", ".hpp", ".hxx", ".cxx"):
            continue
        if not should_lint_file(filepath):
            continue
        if os.path.exists(filepath):
            filtered_files.append(filepath)

    return filtered_files


def create_comment_text(warning: str, cpp_files: List[str]) -> str:
    instructions = get_instructions(cpp_files)
    return f"""
:warning: C/C++ code linter clang-tidy found issues in your code. :warning:

<details>
<summary>
You can test this locally with the following command:
</summary>

```bash
{instructions}
```

</details>

<details>
<summary>
View the output from clang-tidy here.
</summary>

```
{warning}
```

</details>
"""


def find_comment(pr: any) -> any:
    for comment in pr.as_issue().get_comments():
        if COMMENT_TAG in comment.body:
            return comment
    return None


def create_comment(
    comment_text: str, args: LintArgs, create_new: bool
) -> Optional[dict]:
    import github

    repo = github.Github(args.token).get_repo(args.repo)
    pr = repo.get_issue(args.issue_number).as_pull_request()

    comment_text = COMMENT_TAG + "\n\n" + comment_text

    existing_comment = find_comment(pr)

    comment = None
    if create_new or existing_comment:
        comment = {"body": comment_text}
    if existing_comment:
        comment["id"] = existing_comment.id
    return comment


def run_clang_tidy(changed_files: List[str], args: LintArgs) -> Optional[str]:
    if not changed_files:
        print("no c/c++ files found")
        return None

    git_diff_cmd = [
        "git",
        "diff",
        "-U0",
        f"{args.start_rev}...{args.end_rev}",
        "--",
    ] + changed_files

    diff_proc = subprocess.run(
        git_diff_cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        check=False,
    )

    if diff_proc.returncode != 0:
        print(f"Git diff failed: {diff_proc.stderr}")
        return None

    diff_content = diff_proc.stdout
    if not diff_content.strip():
        print("No diff content found")
        return None

    tidy_diff_cmd = [
        "clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py",
        "-path",
        args.build_path,
        "-p1",
        "-quiet",
    ]

    if args.verbose:
        print(f"Running clang-tidy-diff: {' '.join(tidy_diff_cmd)}")

    proc = subprocess.run(
        tidy_diff_cmd,
        input=diff_content,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        check=False,
    )

    return clean_clang_tidy_output(proc.stdout.strip())


def run_linter(changed_files: List[str], args: LintArgs) -> tuple[bool, Optional[dict]]:
    changed_files = [arg for arg in changed_files if "third-party" not in arg]

    cpp_files = filter_changed_files(changed_files)

    tidy_result = run_clang_tidy(cpp_files, args)
    should_update_gh = args.token is not None and args.repo is not None

    comment = None
    if tidy_result is None:
        if should_update_gh:
            comment_text = (
                ":white_check_mark: With the latest revision "
                "this PR passed the C/C++ code linter."
            )
            comment = create_comment(comment_text, args, create_new=False)
        return True, comment
    elif len(tidy_result) > 0:
        if should_update_gh:
            comment_text = create_comment_text(tidy_result, cpp_files)
            comment = create_comment(comment_text, args, create_new=True)
        else:
            print(
                "Warning: C/C++ code linter, clang-tidy detected "
                "some issues with your code..."
            )
        return False, comment
    else:
        # The linter failed but didn't output a result (e.g. some sort of
        # infrastructure failure).
        comment_text = (
            ":warning: The C/C++ code linter failed without printing "
            "an output. Check the logs for output. :warning:"
        )
        comment = create_comment(comment_text, args, create_new=False)
        return False, comment


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--token", type=str, required=True, help="GitHub authentication token"
    )
    parser.add_argument("--issue-number", type=int, required=True)
    parser.add_argument(
        "--repo",
        type=str,
        default=os.getenv("GITHUB_REPOSITORY", "llvm/llvm-project"),
        help="The GitHub repository that we are working with in the form of <owner>/<repo> (e.g. llvm/llvm-project)",
    )
    parser.add_argument(
        "--start-rev",
        type=str,
        required=True,
        help="Compute changes from this revision.",
    )
    parser.add_argument(
        "--end-rev", type=str, required=True, help="Compute changes to this revision"
    )
    parser.add_argument(
        "--changed-files",
        type=str,
        help="Comma separated list of files that has been changed",
    )
    parser.add_argument(
        "--build-path",
        type=str,
        default="build",
        help="Path to build directory with compile_commands.json",
    )
    parser.add_argument(
        "--clang-tidy-binary",
        type=str,
        default="clang-tidy",
        help="Path to clang-tidy binary",
    )
    parser.add_argument(
        "--verbose", action="store_true", default=True, help="Verbose output"
    )

    parsed_args = parser.parse_args()
    args = LintArgs(parsed_args)

    changed_files = []
    if args.changed_files:
        changed_files = args.changed_files.split(",")

    if args.verbose:
        print(f"got changed files: {changed_files}")

    if args.verbose:
        print("running linter clang-tidy")

    success, comment = run_linter(changed_files, args)

    if not success:
        if args.verbose:
            print("linter clang-tidy failed")

    # Write comments file if we have a comment
    if comment:
        if args.verbose:
            print(f"linter clang-tidy has comment: {comment}")

        with open("comments", "w") as f:
            import json

            json.dump([comment], f)

    if not success:
        print("error: some linters failed: clang-tidy")
        sys.exit(1)