-
Notifications
You must be signed in to change notification settings - Fork 134
/
lint.py
354 lines (301 loc) · 11.5 KB
/
lint.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
# SPDX-FileCopyrightText: 2017 Free Software Foundation Europe e.V. <https://fsfe.org>
# SPDX-FileCopyrightText: 2022 Florian Snow <florian@familysnow.net>
# SPDX-FileCopyrightText: 2023 DB Systel GmbH
# SPDX-FileCopyrightText: 2024 Nico Rikken <nico@nicorikken.eu>
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""All linting happens here. The linting here is nothing more than reading
the reports and printing some conclusions.
"""
import json
import sys
from argparse import ArgumentParser, Namespace
from gettext import gettext as _
from io import StringIO
from pathlib import Path
from textwrap import TextWrapper
from typing import IO, Any, Optional
from . import __REUSE_version__
from .project import Project
from .report import ProjectReport
def add_arguments(parser: ArgumentParser) -> None:
"""Add arguments to parser."""
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument(
"-q", "--quiet", action="store_true", help=_("prevents output")
)
mutex_group.add_argument(
"-j", "--json", action="store_true", help=_("formats output as JSON")
)
mutex_group.add_argument(
"-p",
"--plain",
action="store_true",
help=_("formats output as plain text"),
)
mutex_group.add_argument(
"-l",
"--lines",
action="store_true",
help=_("formats output as errors per line"),
)
# pylint: disable=too-many-branches,too-many-statements,too-many-locals
def format_plain(report: ProjectReport) -> str:
"""Formats data dictionary as plaintext string to be printed to sys.stdout
Args:
report: ProjectReport data
Returns:
String (in plaintext) that can be output to sys.stdout
"""
output = StringIO()
if not report.is_compliant:
# Bad licenses
if report.bad_licenses:
output.write("# " + _("BAD LICENSES") + "\n\n")
for lic, files in sorted(report.bad_licenses.items()):
output.write(_("'{}' found in:").format(lic) + "\n")
for file in sorted(files):
output.write(f"* {file}\n")
output.write("\n\n")
# Deprecated licenses
if report.deprecated_licenses:
output.write("# " + _("DEPRECATED LICENSES") + "\n\n")
output.write(
_("The following licenses are deprecated by SPDX:") + "\n"
)
for lic in sorted(report.deprecated_licenses):
output.write(f"* {lic}\n")
output.write("\n\n")
# Licenses without extension
if report.licenses_without_extension:
output.write("# " + _("LICENSES WITHOUT FILE EXTENSION") + "\n\n")
output.write(
_("The following licenses have no file extension:") + "\n"
)
for lic in sorted(report.licenses_without_extension):
output.write(f"* {lic}\n")
output.write("\n\n")
# Missing licenses
if report.missing_licenses:
output.write("# " + _("MISSING LICENSES") + "\n\n")
for lic, files in sorted(report.missing_licenses.items()):
output.write(_("'{}' found in:").format(lic) + "\n")
for file in sorted(files):
output.write(f"* {file}\n")
output.write("\n\n")
# Unused licenses
if report.unused_licenses:
output.write("# " + _("UNUSED LICENSES") + "\n\n")
output.write(_("The following licenses are not used:") + "\n")
for lic in sorted(report.unused_licenses):
output.write(f"* {lic}\n")
output.write("\n\n")
# Read errors
if report.read_errors:
output.write("# " + _("READ ERRORS") + "\n\n")
output.write(_("Could not read:") + "\n")
for path in sorted(report.read_errors):
output.write(f"* {path}\n")
output.write("\n\n")
# Missing copyright and licensing information
files_without_both = report.files_without_copyright.intersection(
report.files_without_licenses
)
files_without_copyright_excl = (
report.files_without_copyright - files_without_both
)
files_without_licenses_excl = (
report.files_without_licenses - files_without_both
)
files_without_either = files_without_copyright_excl.union(
files_without_licenses_excl
)
if files_without_either or files_without_both:
header = (
"# " + _("MISSING COPYRIGHT AND LICENSING INFORMATION") + "\n\n"
)
output.write(header)
if files_without_both:
output.write(
_(
"The following files have no copyright and licensing "
"information:"
)
)
output.write("\n")
for file in sorted(files_without_both):
output.write(f"* {file}\n")
output.write("\n")
if files_without_copyright_excl:
output.write(
_("The following files have no copyright information:")
)
output.write("\n")
for file in sorted(files_without_copyright_excl):
output.write(f"* {file}\n")
output.write("\n")
if files_without_licenses_excl:
output.write(
_("The following files have no licensing information:")
)
output.write("\n")
for file in sorted(files_without_licenses_excl):
output.write(f"* {file}\n")
output.write("\n")
output.write("\n")
output.write("# " + _("SUMMARY"))
output.write("\n\n")
total_files = len(report.file_reports)
summary_contents = {
_("Bad licenses:"): ", ".join(report.bad_licenses),
_("Deprecated licenses:"): ", ".join(report.deprecated_licenses),
_("Licenses without file extension:"): ", ".join(
report.licenses_without_extension
),
_("Missing licenses:"): ", ".join(report.missing_licenses),
_("Unused licenses:"): ", ".join(report.unused_licenses),
_("Used licenses:"): ", ".join(report.used_licenses),
_("Read errors:"): str(len(report.read_errors)),
_(
"Files with copyright information:"
): f"{total_files - len(report.files_without_copyright)}"
f" / {total_files}",
_(
"Files with license information:"
): f"{total_files - len(report.files_without_licenses)}"
f" / {total_files}",
}
# Replace empty values with 0.
summary_contents = {
key: value if value else "0" for key, value in summary_contents.items()
}
for key, value in summary_contents.items():
output.write(f"* {key} {value}\n")
output.write("\n")
if report.is_compliant:
output.write(
_(
"Congratulations! Your project is compliant with version"
" {} of the REUSE Specification :-)"
).format(__REUSE_version__)
)
else:
output.write(
_(
"Unfortunately, your project is not compliant with version "
"{} of the REUSE Specification :-("
).format(__REUSE_version__)
)
# Write recommendations in a nicely wrapped format
output.write("\n\n\n# ")
output.write(_("RECOMMENDATIONS"))
output.write("\n\n")
wrapper = TextWrapper(
width=80,
drop_whitespace=True,
break_long_words=False,
initial_indent="* ",
subsequent_indent=" ",
)
for help_text in report.recommendations:
output.write("\n".join(wrapper.wrap(help_text)))
output.write("\n")
output.write("\n")
return output.getvalue()
def format_json(report: ProjectReport) -> str:
"""Formats data dictionary as JSON string ready to be printed to sys.stdout
Args:
report: Dictionary containing formatted ProjectReport data
Returns:
String (representing JSON) that can be output to sys.stdout
"""
def custom_serializer(obj: Any) -> Any:
"""Custom serializer for the dictionary output of ProjectReport
Args:
obj: Object to be serialized
"""
if isinstance(obj, Path):
return str(obj)
if isinstance(obj, set):
return list(obj)
raise TypeError(
f"Object of type {obj.__class__.__name__} is not JSON serializable"
)
return json.dumps(
report.to_dict_lint(),
indent=2,
# Serialize sets to lists
default=custom_serializer,
)
def format_lines(report: ProjectReport) -> str:
"""Formats data dictionary as plaintext strings to be printed to sys.stdout
Sorting of output is not guaranteed.
Symbolic links can result in multiple entries per file.
Args:
report: ProjectReport data
Returns:
String (in plaintext) that can be output to sys.stdout
"""
output = StringIO()
def license_path(lic: str) -> Optional[Path]:
"""Resolve a license identifier to a license path."""
return report.licenses.get(lic)
if not report.is_compliant:
# Bad licenses
for lic, files in sorted(report.bad_licenses.items()):
for path in sorted(files):
output.write(
_("{path}: bad license {lic}\n").format(path=path, lic=lic)
)
# Deprecated licenses
for lic in sorted(report.deprecated_licenses):
lic_path = license_path(lic)
output.write(
_("{lic_path}: deprecated license\n").format(lic_path=lic_path)
)
# Licenses without extension
for lic in sorted(report.licenses_without_extension):
lic_path = license_path(lic)
output.write(
_("{lic_path}: license without file extension\n").format(
lic_path=lic_path
)
)
# Unused licenses
for lic in sorted(report.unused_licenses):
lic_path = license_path(lic)
output.write(
_("{lic_path}: unused license\n").format(lic_path=lic_path)
)
# Missing licenses
for lic, files in sorted(report.missing_licenses.items()):
for path in sorted(files):
output.write(
_("{path}: missing license {lic}\n").format(
path=path, lic=lic
)
)
# Read errors
for path in sorted(report.read_errors):
output.write(_("{path}: read error\n").format(path=path))
# Without licenses
for path in report.files_without_licenses:
output.write(_("{path}: no license identifier\n").format(path=path))
# Without copyright
for path in report.files_without_copyright:
output.write(_("{path}: no copyright notice\n").format(path=path))
return output.getvalue()
def run(args: Namespace, project: Project, out: IO[str] = sys.stdout) -> int:
"""List all non-compliant files."""
report = ProjectReport.generate(
project, do_checksum=False, multiprocessing=not args.no_multiprocessing
)
if args.quiet:
pass
elif args.json:
out.write(format_json(report))
elif args.lines:
out.write(format_lines(report))
else:
out.write(format_plain(report))
return 0 if report.is_compliant else 1