forked from platisd/duplicate-code-detection-tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_action.py
executable file
·203 lines (163 loc) · 6.18 KB
/
run_action.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
#!/usr/bin/env python
import os
import sys
import json
import requests
import argparse
import duplicate_code_detection
WARNING_SUFFIX = " ⚠️"
def make_markdown_table(array):
"""Input: Python list with rows of table as lists
First element as header.
Output: String to put into a .md file
Ex Input:
[["Name", "Age", "Height"],
["Jake", 20, 5'10],
["Mary", 21, 5'7]]
Adopted from: https://gist.github.com/m0neysha/219bad4b02d2008e0154
"""
markdown = "\n" + str("| ")
for e in array[0]:
to_add = " " + str(e) + str(" |")
markdown += to_add
markdown += "\n"
markdown += "|"
for i in range(len(array[0])):
markdown += str("-------------- | ")
markdown += "\n"
markdown_characters = 0
max_characters = 65000
for entry in array[1:]:
markdown += str("| ")
for e in entry:
to_add = str(e) + str(" | ")
markdown += to_add
markdown += "\n"
markdown_characters += len(markdown)
if markdown_characters > max_characters:
markdown += "\n" + WARNING_SUFFIX + " "
markdown += "Results were omitted because the report was too large. "
markdown += "Please consider ignoring results below a certain threshold.\n"
break
return markdown + "\n"
def get_markdown_link(file, url):
return "[%s](%s%s)" % (file, url, file)
def get_warning(similarity, warn_threshold):
return (
str(similarity)
if similarity < int(warn_threshold)
else str(similarity) + WARNING_SUFFIX
)
def similarities_to_markdown(similarities, url_prefix, warn_threshold):
markdown = str()
for checked_file in similarities.keys():
markdown += "<details><summary>%s</summary>\n\n" % checked_file
markdown += "### 📄 %s\n" % get_markdown_link(checked_file, url_prefix)
table_header = ["File", "Similarity (%)"]
table_contents = [
[get_markdown_link(f, url_prefix), get_warning(s, warn_threshold)]
for (f, s) in similarities[checked_file].items()
]
# Sort table contents based on similarity
table_contents.sort(
reverse=True, key=lambda row: float(row[1].replace(WARNING_SUFFIX, ""))
)
entire_table = [[] for _ in range(len(table_contents) + 1)]
entire_table[0] = table_header
for i in range(1, len(table_contents) + 1):
entire_table[i] = table_contents[i - 1]
markdown += make_markdown_table(entire_table)
markdown += "</details>\n"
return markdown
def split_and_trim(input_list):
return [token.strip() for token in input_list.split(",")]
def to_absolute_path(paths):
return [os.path.abspath(path) for path in paths]
def main():
parser = argparse.ArgumentParser(
description="Duplicate code detection action runner"
)
parser.add_argument(
"--latest-head",
type=str,
default="master",
help="The latest commit hash or branch",
)
parser.add_argument(
"--pull-request-id", type=str, required=True, help="The pull request id"
)
args = parser.parse_args()
fail_threshold = os.environ.get("INPUT_FAIL_ABOVE")
directories = os.environ.get("INPUT_DIRECTORIES")
ignore_directories = os.environ.get("INPUT_IGNORE_DIRECTORIES")
project_root_dir = os.environ.get("INPUT_PROJECT_ROOT_DIR")
file_extensions = os.environ.get("INPUT_FILE_EXTENSIONS")
ignore_threshold = os.environ.get("INPUT_IGNORE_BELOW")
only_code = os.environ.get("INPUT_ONLY_CODE")
directories_list = split_and_trim(directories)
directories_list = to_absolute_path(directories_list)
ignore_directories_list = (
split_and_trim(ignore_directories) if ignore_directories != "" else list()
)
ignore_directories_list = to_absolute_path(ignore_directories_list)
file_extensions_list = split_and_trim(file_extensions)
project_root_dir = os.path.abspath(project_root_dir)
files_list = None
ignore_files_list = None
json_output = True
csv_output_path = "" # No CSV output by default for now in GitHub Actions
show_loc = False
detection_result, code_similarity = duplicate_code_detection.run(
int(fail_threshold),
directories_list,
files_list,
ignore_directories_list,
ignore_files_list,
json_output,
project_root_dir,
file_extensions_list,
int(ignore_threshold),
bool(only_code),
csv_output_path,
show_loc,
)
if detection_result == duplicate_code_detection.ReturnCode.BAD_INPUT:
print("Action aborted due to bad user input")
return detection_result.value
elif detection_result == duplicate_code_detection.ReturnCode.THRESHOLD_EXCEEDED:
print(
"Action failed due to maximum similarity threshold exceeded, check the report"
)
repo = os.environ.get("GITHUB_REPOSITORY")
files_url_prefix = "https://github.com/%s/blob/%s/" % (repo, args.latest_head)
warn_threshold = os.environ.get("INPUT_WARN_ABOVE")
message = "## 📌 Duplicate code detection tool report\n"
message += "The [tool](https://github.com/platisd/duplicate-code-detection-tool)"
message += " analyzed your source code and found the following degree of"
message += " similarity between the files:\n"
message += similarities_to_markdown(
code_similarity, files_url_prefix, warn_threshold
)
github_token = os.environ.get("INPUT_GITHUB_TOKEN")
github_api_url = os.environ.get("GITHUB_API_URL")
request_url = "%s/repos/%s/issues/%s/comments" % (
github_api_url,
repo,
args.pull_request_id,
)
with open("message.md", "w") as f:
f.write(message)
post_result = requests.post(
request_url,
json={"body": message},
headers={"Authorization": "token %s" % github_token},
)
if post_result.status_code != 201:
print(
"Posting results to GitHub failed with code: "
+ str(post_result.status_code)
)
print(post_result.text)
return detection_result.value
if __name__ == "__main__":
sys.exit(main())