forked from ZedThree/clang-tidy-review
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
1185 lines (935 loc) · 36.7 KB
/
__init__.py
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# clang-tidy review
# Copyright (c) 2020 Peter Hill
# SPDX-License-Identifier: MIT
# See LICENSE for more information
import argparse
import base64
import fnmatch
import itertools
import json
import os
from operator import itemgetter
import pprint
import pathlib
import subprocess
import textwrap
import unidiff
import urllib3
import yaml
import contextlib
import datetime
import re
import io
import zipfile
from github import Github, Auth
from github.GithubException import GithubException
from github.Requester import Requester
from github.PaginatedList import PaginatedList
from github.WorkflowRun import WorkflowRun
from typing import Any, List, Optional, TypedDict
DIFF_HEADER_LINE_LENGTH = 5
FIXES_FILE = "clang_tidy_review.yaml"
METADATA_FILE = "clang-tidy-review-metadata.json"
REVIEW_FILE = "clang-tidy-review-output.json"
MAX_ANNOTATIONS = 10
class Metadata(TypedDict):
"""Loaded from `METADATA_FILE`
Contains information necessary to post a review without pull request knowledge
"""
pr_number: int
class PRReviewComment(TypedDict):
path: str
position: Optional[int]
body: str
line: Optional[int]
side: Optional[str]
start_line: Optional[int]
start_side: Optional[str]
class PRReview(TypedDict):
body: str
event: str
comments: List[PRReviewComment]
class HashableComment:
def __init__(self, body: str, line: int, path: str, side: str, **kwargs):
self.body = body
self.line = line
self.path = path
self.side = side
def __hash__(self):
return hash(
(
self.body,
self.line,
self.path,
self.side,
)
)
def __eq__(self, other):
return (
type(self) is type(other)
and self.body == other.body
and self.line == self.line
and other.path == other.path
and self.side == other.side
)
def __lt__(self, other):
if self.path != other.path:
return self.path < other.path
if self.line != other.line:
return self.line < other.line
if self.side != other.side:
return self.side < other.side
if self.body != other.body:
return self.body < other.body
return id(self) < id(other)
def add_auth_arguments(parser: argparse.ArgumentParser):
# Token
parser.add_argument("--token", help="github auth token")
# App
group_app = parser.add_argument_group(
"""Github app installation authentication
Permissions required: Contents (Read) and Pull requests (Read and Write)"""
)
group_app.add_argument("--app-id", type=int, help="app ID")
group_app.add_argument(
"--private-key", type=str, help="app private key as a string"
)
group_app.add_argument(
"--private-key-base64",
type=str,
help="app private key as a string encoded as base64",
)
group_app.add_argument(
"--private-key-file-path",
type=pathlib.Path,
help="app private key .pom file path",
)
group_app.add_argument("--installation-id", type=int, help="app installation ID")
def get_auth_from_arguments(args: argparse.Namespace) -> Auth:
if args.token:
return Auth.Token(args.token)
if (
args.app_id
and (args.private_key or args.private_key_file_path or args.private_key_base64)
and args.installation_id
):
if args.private_key:
private_key = args.private_key
elif args.private_key_base64:
private_key = base64.b64decode(args.private_key_base64).decode("ascii")
else:
private_key = open(args.private_key_file_path).read()
return Auth.AppAuth(args.app_id, private_key).get_installation_auth(
args.installation_id
)
elif (
args.app_id
or args.private_key
or args.private_key_file_path
or args.private_key_base64
or args.installation_id
):
raise argparse.ArgumentError(
None,
"--app-id, --private-key[-file-path|-base64] and --installation-id must be supplied together",
)
raise argparse.ArgumentError(None, "authentication method not supplied")
def build_clang_tidy_warnings(
line_filter,
build_dir,
clang_tidy_checks,
clang_tidy_binary: pathlib.Path,
config_file,
files,
username: str,
) -> None:
"""Run clang-tidy on the given files and save output into FIXES_FILE"""
config = config_file_or_checks(clang_tidy_binary, clang_tidy_checks, config_file)
args = [
clang_tidy_binary,
f"-p={build_dir}",
f"-line-filter={line_filter}",
f"--export-fixes={FIXES_FILE}",
]
if config:
print(f"Using config: {config}")
args.append(config)
else:
print("Using recursive directory config")
args += files
start = datetime.datetime.now()
try:
with message_group(f"Running:\n\t{args}"):
env = dict(os.environ)
env["USER"] = username
subprocess.run(
args,
capture_output=True,
check=True,
encoding="utf-8",
env=env,
)
except subprocess.CalledProcessError as e:
print(
f"\n\nclang-tidy failed with return code {e.returncode} and error:\n{e.stderr}\nOutput was:\n{e.stdout}"
)
end = datetime.datetime.now()
print(f"Took: {end - start}")
def clang_tidy_version(clang_tidy_binary: pathlib.Path):
try:
version_out = subprocess.run(
[clang_tidy_binary, "--version"],
capture_output=True,
check=True,
text=True,
).stdout
except subprocess.CalledProcessError as e:
print(f"\n\nWARNING: Couldn't get clang-tidy version, error was: {e}")
return 0
if version := re.search(r"version (\d+)", version_out):
return int(version.group(1))
print(
f"\n\nWARNING: Couldn't get clang-tidy version number, '{clang_tidy_binary} --version' reported: {version_out}"
)
return 0
def config_file_or_checks(
clang_tidy_binary: pathlib.Path, clang_tidy_checks: str, config_file: str
) -> Optional[str]:
version = clang_tidy_version(clang_tidy_binary)
if config_file == "":
if clang_tidy_checks:
return f"--checks={clang_tidy_checks}"
return None
if version >= 12:
return f"--config-file={config_file}"
if config_file != ".clang-tidy":
print(
f"\n\nWARNING: non-default config file name '{config_file}' will be ignored for "
"selected clang-tidy version {version}. This version expects exactly '.clang-tidy'\n"
)
return "--config"
def load_clang_tidy_warnings():
"""Read clang-tidy warnings from FIXES_FILE. Can be produced by build_clang_tidy_warnings"""
try:
with open(FIXES_FILE, "r") as fixes_file:
return yaml.safe_load(fixes_file)
except FileNotFoundError:
return {}
class PullRequest:
"""Add some convenience functions not in PyGithub"""
def __init__(self, repo: str, pr_number: Optional[int], auth: Auth) -> None:
self.repo_name = repo
self.pr_number = pr_number
self.auth = auth
# Choose API URL, default to public GitHub
self.api_url = os.environ.get("GITHUB_API_URL", "https://api.github.com")
github = Github(auth=self.auth, base_url=self.api_url)
self.repo = github.get_repo(f"{repo}")
self._pull_request = None
@property
def token(self):
return self.auth.token
@property
def pull_request(self):
if self._pull_request is None:
if self.pr_number is None:
raise RuntimeError("Missing PR number")
self._pull_request = self.repo.get_pull(int(self.pr_number))
return self._pull_request
def get_pr_diff(self) -> List[unidiff.PatchSet]:
"""Download the PR diff, return a list of PatchedFile"""
_, data = self.repo._requester.requestJsonAndCheck(
"GET",
self.pull_request.url,
headers={"Accept": f"application/vnd.github.{'v3.diff'}"},
)
diffs = data["data"]
# PatchSet is the easiest way to construct what we want, but the
# diff_line_no property on lines is counted from the top of the
# whole PatchSet, whereas GitHub is expecting the "position"
# property to be line count within each file's diff. So we need to
# do this little bit of faff to get a list of file-diffs with
# their own diff_line_no range
diff = [unidiff.PatchSet(str(file))[0] for file in unidiff.PatchSet(diffs)]
return diff
def get_pr_author(self) -> str:
"""Get the username of the PR author. This is used in google-readability-todo"""
return self.pull_request.user.login
def get_pr_comments(self):
"""Download the PR review comments using the comfort-fade preview headers"""
def get_element(
requester: Requester, headers: dict, element: dict, completed: bool
):
return element
return PaginatedList(
get_element,
self.pull_request._requester,
self.pull_request.review_comments_url,
None,
)
def post_lgtm_comment(self, body: str):
"""Post a "LGTM" comment if everything's clean, making sure not to spam"""
if not body:
return
comments = self.get_pr_comments()
for comment in comments:
if comment["body"] == body:
print("Already posted, no need to update")
return
self.pull_request.create_issue_comment(body)
def post_review(self, review: PRReview):
"""Submit a completed review"""
self.pull_request.create_review(**review)
def post_annotations(self, review):
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {self.token}",
}
url = f"{self.api_url}/repos/{self.repo_name}/check-runs"
self.repo._requester.requestJsonAndCheck(
"POST", url, parameters=review, headers=headers
)
@contextlib.contextmanager
def message_group(title: str):
print(f"::group::{title}", flush=True)
try:
yield
finally:
print("::endgroup::", flush=True)
def make_file_line_lookup(diff):
"""Get a lookup table for each file in diff, to convert between source
line number to line number in the diff
"""
lookup = {}
for file in diff:
filename = file.target_file[2:]
lookup[filename] = {}
for hunk in file:
for line in hunk:
if line.diff_line_no is None:
continue
if not line.is_removed:
lookup[filename][line.target_line_no] = (
line.diff_line_no - DIFF_HEADER_LINE_LENGTH
)
return lookup
def make_file_offset_lookup(filenames):
"""Create a lookup table to convert between character offset and line
number for the list of files in `filenames`.
This is a dict of the cumulative sum of the line lengths for each file.
"""
lookup = {}
for filename in filenames:
with open(filename, "r") as file:
lines = file.readlines()
# Length of each line
line_lengths = map(len, lines)
# Cumulative sum of line lengths => offset at end of each line
lookup[os.path.abspath(filename)] = [0] + list(
itertools.accumulate(line_lengths)
)
return lookup
def get_diagnostic_file_path(clang_tidy_diagnostic, build_dir):
# Sometimes, clang-tidy gives us an absolute path, so everything is fine.
# Sometimes however it gives us a relative path that is realtive to the
# build directory, so we prepend that.
# Modern clang-tidy
if ("DiagnosticMessage" in clang_tidy_diagnostic) and (
"FilePath" in clang_tidy_diagnostic["DiagnosticMessage"]
):
file_path = clang_tidy_diagnostic["DiagnosticMessage"]["FilePath"]
if file_path == "":
return ""
elif os.path.isabs(file_path):
return os.path.normpath(os.path.abspath(file_path))
else:
# Make the relative path absolute with the build dir
if "BuildDirectory" in clang_tidy_diagnostic:
return os.path.normpath(
os.path.abspath(
os.path.join(clang_tidy_diagnostic["BuildDirectory"], file_path)
)
)
else:
return os.path.normpath(os.path.abspath(file_path))
# Pre-clang-tidy-9 format
elif "FilePath" in clang_tidy_diagnostic:
file_path = clang_tidy_diagnostic["FilePath"]
if file_path == "":
return ""
else:
return os.path.normpath(os.path.abspath(os.path.join(build_dir, file_path)))
else:
return ""
def find_line_number_from_offset(offset_lookup, filename, offset):
"""Work out which line number `offset` corresponds to using `offset_lookup`.
The line number (0-indexed) is the index of the first line offset
which is larger than `offset`.
"""
name = str(pathlib.Path(filename).resolve().absolute())
if name not in offset_lookup:
# Let's make sure we've the file offsets for this other file
offset_lookup.update(make_file_offset_lookup([name]))
for line_num, line_offset in enumerate(offset_lookup[name]):
if line_offset > offset:
return line_num - 1
return -1
def read_one_line(filename, line_offset):
"""Read a single line from a source file"""
# Could cache the files instead of opening them each time?
with open(filename, "r") as file:
file.seek(line_offset)
return file.readline().rstrip("\n")
def collate_replacement_sets(diagnostic, offset_lookup):
"""Return a dict of replacements on the same or consecutive lines, indexed by line number
We need this as we have to apply all the replacements on one line at the same time
This could break if there are replacements in with the same line
number but in different files.
"""
# First, make sure each replacement contains "LineNumber", and
# "EndLineNumber" in case it spans multiple lines
for replacement in diagnostic["Replacements"]:
# Sometimes, the FilePath may include ".." in "." as a path component
# However, file paths are stored in the offset table only after being
# converted to an abs path, in which case the stored path will differ
# from the FilePath and we'll end up looking for a path that's not in
# the lookup dict
# To fix this, we'll convert all the FilePaths to absolute paths
replacement["FilePath"] = os.path.abspath(replacement["FilePath"])
# It's possible the replacement is needed in another file?
# Not really sure how that could come about, but let's
# cover our behinds in case it does happen:
if replacement["FilePath"] not in offset_lookup:
# Let's make sure we've the file offsets for this other file
offset_lookup.update(make_file_offset_lookup([replacement["FilePath"]]))
replacement["LineNumber"] = find_line_number_from_offset(
offset_lookup, replacement["FilePath"], replacement["Offset"]
)
replacement["EndLineNumber"] = find_line_number_from_offset(
offset_lookup,
replacement["FilePath"],
replacement["Offset"] + replacement["Length"],
)
# Now we can group them into consecutive lines
groups = []
for index, replacement in enumerate(diagnostic["Replacements"]):
if index == 0:
# First one starts a new group, always
groups.append([replacement])
elif (
replacement["LineNumber"] == groups[-1][-1]["LineNumber"]
or replacement["LineNumber"] - 1 == groups[-1][-1]["LineNumber"]
):
# Same or adjacent line to the last line in the last group
# goes in the same group
groups[-1].append(replacement)
else:
# Otherwise, start a new group
groups.append([replacement])
# Turn the list into a dict
return {g[0]["LineNumber"]: g for g in groups}
def replace_one_line(replacement_set, line_num, offset_lookup):
"""Apply all the replacements in replacement_set at the same time"""
filename = replacement_set[0]["FilePath"]
# File offset at the start of the first line
line_offset = offset_lookup[filename][line_num]
# List of (start, end) offsets from line_offset
insert_offsets = [(0, 0)]
# Read all the source lines into a dict so we only get one copy of
# each line, though we might read the same line in multiple times
source_lines = {}
for replacement in replacement_set:
start = replacement["Offset"] - line_offset
end = start + replacement["Length"]
insert_offsets.append((start, end))
# Make sure to read any extra lines we need too
for replacement_line_num in range(
replacement["LineNumber"], replacement["EndLineNumber"] + 1
):
replacement_line_offset = offset_lookup[filename][replacement_line_num]
source_lines[replacement_line_num] = (
read_one_line(filename, replacement_line_offset) + "\n"
)
# Replacements might cross multiple lines, so squash them all together
source_line = "".join(source_lines.values()).rstrip("\n")
insert_offsets.append((None, None))
fragments = []
for (_, start), (end, _) in zip(insert_offsets[:-1], insert_offsets[1:]):
fragments.append(source_line[start:end])
new_line = ""
for fragment, replacement in zip(fragments, replacement_set):
new_line += fragment + replacement["ReplacementText"]
return source_line, new_line + fragments[-1]
def format_ordinary_line(source_line, line_offset):
"""Format a single C++ line with a diagnostic indicator"""
return textwrap.dedent(
f"""\
```cpp
{source_line}
{line_offset * " " + "^"}
```
"""
)
def format_diff_line(diagnostic, offset_lookup, source_line, line_offset, line_num):
"""Format a replacement as a Github suggestion or diff block"""
end_line = line_num
# We're going to be appending to this
code_blocks = ""
replacement_sets = collate_replacement_sets(diagnostic, offset_lookup)
for replacement_line_num, replacement_set in replacement_sets.items():
old_line, new_line = replace_one_line(
replacement_set, replacement_line_num, offset_lookup
)
print(f"----------\n{old_line=}\n{new_line=}\n----------")
# If the replacement is for the same line as the
# diagnostic (which is where the comment will be), then
# format the replacement as a suggestion. Otherwise,
# format it as a diff
if replacement_line_num == line_num:
code_blocks += f"""
```suggestion
{new_line}
```
"""
end_line = replacement_set[-1]["EndLineNumber"]
else:
# Prepend each line in the replacement line with "+ "
# in order to make a nice diff block. The extra
# whitespace is so the multiline dedent-ed block below
# doesn't come out weird.
whitespace = "\n "
new_line = whitespace.join([f"+ {line}" for line in new_line.splitlines()])
old_line = whitespace.join([f"- {line}" for line in old_line.splitlines()])
rel_path = try_relative(replacement_set[0]["FilePath"])
code_blocks += textwrap.dedent(
f"""\
{rel_path}:{replacement_line_num}:
```diff
{old_line}
{new_line}
```
"""
)
return code_blocks, end_line
def try_relative(path) -> pathlib.Path:
"""Try making `path` relative to current directory, otherwise make it an absolute path"""
try:
here = pathlib.Path.cwd()
return pathlib.Path(path).relative_to(here)
except ValueError:
return pathlib.Path(path).resolve()
def fix_absolute_paths(build_compile_commands, base_dir):
"""Update absolute paths in compile_commands.json to new location, if
compile_commands.json was created outside the Actions container
"""
basedir = pathlib.Path(base_dir).resolve()
newbasedir = pathlib.Path(".").resolve()
if basedir == newbasedir:
return
print(f"Found '{build_compile_commands}', updating absolute paths")
# We might need to change some absolute paths if we're inside
# a docker container
with open(build_compile_commands, "r") as f:
compile_commands = json.load(f)
print(f"Replacing '{basedir}' with '{newbasedir}'", flush=True)
modified_compile_commands = json.dumps(compile_commands).replace(
str(basedir), str(newbasedir)
)
with open(build_compile_commands, "w") as f:
f.write(modified_compile_commands)
def format_notes(notes, offset_lookup):
"""Format an array of notes into a single string"""
code_blocks = ""
for note in notes:
filename = note["FilePath"]
if filename == "":
return note["Message"]
resolved_path = str(pathlib.Path(filename).resolve().absolute())
line_num = find_line_number_from_offset(
offset_lookup, resolved_path, note["FileOffset"]
)
line_offset = note["FileOffset"] - offset_lookup[resolved_path][line_num]
source_line = read_one_line(
resolved_path, offset_lookup[resolved_path][line_num]
)
path = try_relative(resolved_path)
message = f"**{path}:{line_num}:** {note['Message']}"
code = format_ordinary_line(source_line, line_offset)
code_blocks += f"{message}\n{code}"
if notes:
code_blocks = f"<details>\n<summary>Additional context</summary>\n\n{code_blocks}\n</details>\n"
return code_blocks
def make_comment_from_diagnostic(
diagnostic_name, diagnostic, filename, offset_lookup, notes
):
"""Create a comment from a diagnostic
Comment contains the diagnostic message, plus its name, along with
code block(s) containing either the exact location of the
diagnostic, or suggested fix(es).
"""
line_num = find_line_number_from_offset(
offset_lookup, filename, diagnostic["FileOffset"]
)
line_offset = diagnostic["FileOffset"] - offset_lookup[filename][line_num]
source_line = read_one_line(filename, offset_lookup[filename][line_num])
end_line = line_num
print(
f"""{diagnostic}
{line_num=}; {line_offset=}; {source_line=}
"""
)
if diagnostic["Replacements"]:
code_blocks, end_line = format_diff_line(
diagnostic, offset_lookup, source_line, line_offset, line_num
)
else:
# No fixit, so just point at the problem
code_blocks = format_ordinary_line(source_line, line_offset)
code_blocks += format_notes(notes, offset_lookup)
comment_body = (
f"warning: {diagnostic['Message']} [{diagnostic_name}]\n{code_blocks}"
)
return comment_body, end_line + 1
def create_review_file(
clang_tidy_warnings, diff_lookup, offset_lookup, build_dir
) -> Optional[PRReview]:
"""Create a Github review from a set of clang-tidy diagnostics"""
if "Diagnostics" not in clang_tidy_warnings:
return None
comments: List[PRReviewComment] = []
for diagnostic in clang_tidy_warnings["Diagnostics"]:
try:
diagnostic_message = diagnostic["DiagnosticMessage"]
except KeyError:
# Pre-clang-tidy-9 format
diagnostic_message = diagnostic
if diagnostic_message["FilePath"] == "":
continue
comment_body, end_line = make_comment_from_diagnostic(
diagnostic["DiagnosticName"],
diagnostic_message,
get_diagnostic_file_path(diagnostic, build_dir),
offset_lookup,
notes=diagnostic.get("Notes", []),
)
rel_path = try_relative(
get_diagnostic_file_path(diagnostic, build_dir)
).as_posix()
# diff lines are 1-indexed
source_line = 1 + find_line_number_from_offset(
offset_lookup,
get_diagnostic_file_path(diagnostic, build_dir),
diagnostic_message["FileOffset"],
)
if rel_path not in diff_lookup or end_line not in diff_lookup[rel_path]:
print(
f"WARNING: Skipping comment for file '{rel_path}' not in PR changeset. Comment body is:\n{comment_body}"
)
continue
comments.append(
{
"path": rel_path,
"body": comment_body,
"side": "RIGHT",
"line": end_line,
}
)
# If this is a multiline comment, we need a couple more bits:
if end_line != source_line:
comments[-1].update(
{
"start_side": "RIGHT",
"start_line": source_line,
}
)
review: PRReview = {
"body": "clang-tidy made some suggestions",
"event": "COMMENT",
"comments": comments,
}
return review
def filter_files(diff, include: List[str], exclude: List[str]) -> List:
changed_files = [filename.target_file[2:] for filename in diff]
files = []
for pattern in include:
files.extend(fnmatch.filter(changed_files, pattern))
print(f"include: {pattern}, file list now: {files}")
for pattern in exclude:
files = [f for f in files if not fnmatch.fnmatch(f, pattern)]
print(f"exclude: {pattern}, file list now: {files}")
return files
def create_review(
pull_request: PullRequest,
build_dir: str,
clang_tidy_checks: str,
clang_tidy_binary: pathlib.Path,
config_file: str,
include: List[str],
exclude: List[str],
) -> Optional[PRReview]:
"""Given the parameters, runs clang-tidy and creates a review.
If no files were changed, or no warnings could be found, None will be returned.
"""
diff = pull_request.get_pr_diff()
print(f"\nDiff from GitHub PR:\n{diff}\n")
files = filter_files(diff, include, exclude)
if files == []:
with message_group("No files to check!"):
with open(REVIEW_FILE, "w") as review_file:
json.dump(
{
"body": "clang-tidy found no files to check",
"event": "COMMENT",
"comments": [],
},
review_file,
)
return None
print(f"Checking these files: {files}", flush=True)
line_ranges = get_line_ranges(diff, files)
if line_ranges == "[]":
with message_group("No lines added in this PR!"):
with open(REVIEW_FILE, "w") as review_file:
json.dump(
{
"body": "clang-tidy found no lines added",
"event": "COMMENT",
"comments": [],
},
review_file,
)
return None
print(f"Line filter for clang-tidy:\n{line_ranges}\n")
username = pull_request.get_pr_author() or "your name here"
# Run clang-tidy with the configured parameters and produce the CLANG_TIDY_FIXES file
build_clang_tidy_warnings(
line_ranges,
build_dir,
clang_tidy_checks,
clang_tidy_binary,
config_file,
files,
username,
)
# Read and parse the CLANG_TIDY_FIXES file
clang_tidy_warnings = load_clang_tidy_warnings()
print("clang-tidy had the following warnings:\n", clang_tidy_warnings, flush=True)
diff_lookup = make_file_line_lookup(diff)
offset_lookup = make_file_offset_lookup(files)
with message_group("Creating review from warnings"):
review = create_review_file(
clang_tidy_warnings, diff_lookup, offset_lookup, build_dir
)
with open(REVIEW_FILE, "w") as review_file:
json.dump(review, review_file)
return review
def download_artifacts(pull: PullRequest, workflow_id: int):
"""Attempt to automatically download the artifacts from a previous
run of the review Action"""
# workflow id is an input: ${{github.event.workflow_run.id }}
workflow: WorkflowRun = pull.repo.get_workflow_run(workflow_id)
# I don't understand why mypy complains about the next line!
for artifact in workflow.get_artifacts():
if artifact.name == "clang-tidy-review":
break
else:
# Didn't find the artefact, so bail
print(
f"Couldn't find 'clang-tidy-review' artifact for workflow '{workflow_id}'. "
f"Available artifacts are: {list(workflow.get_artifacts())}"
)
return None, None
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {pull.token}",
}
r = urllib3.request("GET", artifact.archive_download_url, headers=headers)
if r.status is not 200:
print(
f"WARNING: Couldn't automatically download artifacts for workflow '{workflow_id}', response was: {r}: {r.reason}"
)
return None, None
data = zipfile.ZipFile(io.BytesIO(r.data))
filenames = data.namelist()
metadata = (
json.loads(data.read(METADATA_FILE)) if METADATA_FILE in filenames else None
)
review = json.loads(data.read(REVIEW_FILE)) if REVIEW_FILE in filenames else None
return metadata, review
def load_metadata() -> Optional[Metadata]:
"""Load metadata from the METADATA_FILE path"""
if not pathlib.Path(METADATA_FILE).exists():
print(f"WARNING: Could not find metadata file ('{METADATA_FILE}')", flush=True)
return None
with open(METADATA_FILE, "r") as metadata_file:
return json.load(metadata_file)
def save_metadata(pr_number: int) -> None:
"""Save metadata to the METADATA_FILE path"""
metadata: Metadata = {"pr_number": pr_number}
with open(METADATA_FILE, "w") as metadata_file:
json.dump(metadata, metadata_file)
def load_review(review_file: pathlib.Path) -> Optional[PRReview]:
"""Load review output"""
if not review_file.exists():
print(f"WARNING: Could not find review file ('{review_file}')", flush=True)
return None
with open(review_file, "r") as review_file_handle:
payload = json.load(review_file_handle)
return payload or None
def load_and_merge_reviews(review_files: List[pathlib.Path]) -> Optional[PRReview]:
reviews = []
for file in review_files:
review = load_review(file)
if review is not None and len(review.get("comments", [])) > 0:
reviews.append(review)
if not reviews:
return None
result = reviews[0]
comments = set()
for review in reviews:
comments.update(map(lambda c: HashableComment(**c), review["comments"]))
result["comments"] = [c.__dict__ for c in sorted(comments)]
return result