forked from raimon49/pip-licenses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
piplicenses.py
executable file
·1169 lines (969 loc) · 35.2 KB
/
piplicenses.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8 ff=unix ft=python ts=4 sw=4 sts=4 si et
"""
pip-licenses
MIT License
Copyright (c) 2018 raimon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import annotations
import argparse
import codecs
import os
import re
import subprocess
import sys
from collections import Counter
from enum import Enum, auto
from functools import partial
from importlib import metadata as importlib_metadata
from importlib.metadata import Distribution
from pathlib import Path
from typing import TYPE_CHECKING, Iterable, List, Type, cast
import tomli
from prettytable import ALL as RULE_ALL
from prettytable import FRAME as RULE_FRAME
from prettytable import HEADER as RULE_HEADER
from prettytable import NONE as RULE_NONE
from prettytable import PrettyTable
if TYPE_CHECKING:
from email.message import Message
from typing import Callable, Dict, Iterator, Optional, Sequence
open = open # allow monkey patching
__pkgname__ = "pip-licenses"
__version__ = "5.0.0"
__summary__ = (
"Dump the software license list of Python packages installed with pip."
)
FIELD_NAMES = (
"Name",
"Version",
"License",
"LicenseFile",
"LicenseText",
"NoticeFile",
"NoticeText",
"Author",
"Maintainer",
"Description",
"URL",
)
SUMMARY_FIELD_NAMES = (
"Count",
"License",
)
DEFAULT_OUTPUT_FIELDS = (
"Name",
"Version",
)
SUMMARY_OUTPUT_FIELDS = (
"Count",
"License",
)
def extract_homepage(metadata: Message) -> Optional[str]:
"""Extracts the homepage attribute from the package metadata.
Not all python packages have defined a home-page attribute.
As a fallback, the `Project-URL` metadata can be used.
The python core metadata supports multiple (free text) values for
the `Project-URL` field that are comma separated.
Args:
metadata: The package metadata to extract the homepage from.
Returns:
The home page if applicable, None otherwise.
"""
homepage = metadata.get("home-page", None)
if homepage is not None:
return homepage
candidates: Dict[str, str] = {}
for entry in metadata.get_all("Project-URL", []):
key, value = entry.split(",", 1)
candidates[key.strip().lower()] = value.strip()
for priority_key in [
"homepage",
"source",
"repository",
"changelog",
"bug tracker",
]:
if priority_key in candidates:
return candidates[priority_key]
return None
PATTERN_DELIMITER = re.compile(r"[-_.]+")
def normalize_pkg_name(pkg_name: str) -> str:
"""Return normalized name according to PEP specification
See here: https://peps.python.org/pep-0503/#normalized-names
Args:
pkg_name: Package name it is extracted from the package metadata
or specified in the CLI
Returns:
normalized packege name
"""
return PATTERN_DELIMITER.sub("-", pkg_name).lower()
METADATA_KEYS: Dict[str, List[Callable[[Message], Optional[str]]]] = {
"home-page": [extract_homepage],
"author": [
lambda metadata: metadata.get("author"),
lambda metadata: metadata.get("author-email"),
],
"maintainer": [
lambda metadata: metadata.get("maintainer"),
lambda metadata: metadata.get("maintainer-email"),
],
"license": [lambda metadata: metadata.get("license")],
"summary": [lambda metadata: metadata.get("summary")],
}
# Mapping of FIELD_NAMES to METADATA_KEYS where they differ by more than case
FIELDS_TO_METADATA_KEYS = {
"URL": "home-page",
"Description": "summary",
"License-Metadata": "license",
"License-Classifier": "license_classifier",
}
SYSTEM_PACKAGES = (
__pkgname__,
"pip",
"prettytable",
"wcwidth",
"setuptools",
"tomli",
"wheel",
)
LICENSE_UNKNOWN = "UNKNOWN"
def get_packages(
args: CustomNamespace,
) -> Iterator[dict[str, str | list[str]]]:
def get_pkg_included_file(
pkg: Distribution, file_names_rgx: str
) -> tuple[str, str]:
"""
Attempt to find the package's included file on disk and return the
tuple (included_file_path, included_file_contents).
"""
included_file = LICENSE_UNKNOWN
included_text = LICENSE_UNKNOWN
pkg_files = pkg.files or ()
pattern = re.compile(file_names_rgx)
matched_rel_paths = filter(
lambda file: pattern.match(file.name), pkg_files
)
for rel_path in matched_rel_paths:
abs_path = Path(pkg.locate_file(rel_path))
if not abs_path.is_file():
continue
included_file = str(abs_path)
with open(
abs_path, encoding="utf-8", errors="backslashreplace"
) as included_file_handle:
included_text = included_file_handle.read()
break
return (included_file, included_text)
def get_pkg_info(pkg: Distribution) -> dict[str, str | list[str]]:
(license_file, license_text) = get_pkg_included_file(
pkg, "LICEN[CS]E.*|COPYING.*"
)
(notice_file, notice_text) = get_pkg_included_file(pkg, "NOTICE.*")
pkg_info: dict[str, str | list[str]] = {
"name": pkg.metadata["name"],
"version": pkg.version,
"namever": "{} {}".format(pkg.metadata["name"], pkg.version),
"licensefile": license_file,
"licensetext": license_text,
"noticefile": notice_file,
"noticetext": notice_text,
}
metadata = pkg.metadata
for field_name, field_selector_fns in METADATA_KEYS.items():
value = None
for field_selector_fn in field_selector_fns:
# Type hint of `Distribution.metadata` states `PackageMetadata`
# but it's actually of type `email.Message`
value = field_selector_fn(metadata) # type: ignore
if value:
break
pkg_info[field_name] = value or LICENSE_UNKNOWN
classifiers: list[str] = metadata.get_all("classifier", [])
pkg_info["license_classifier"] = find_license_from_classifier(
classifiers
)
if args.filter_strings:
def filter_string(item: str) -> str:
return item.encode(
args.filter_code_page, errors="ignore"
).decode(args.filter_code_page)
for k in pkg_info:
if isinstance(pkg_info[k], list):
pkg_info[k] = list(map(filter_string, pkg_info[k]))
else:
pkg_info[k] = filter_string(cast(str, pkg_info[k]))
return pkg_info
def get_python_sys_path(executable: str) -> list[str]:
script = "import sys; print(' '.join(filter(bool, sys.path)))"
output = subprocess.run(
[executable, "-c", script],
capture_output=True,
env={**os.environ, "PYTHONPATH": "", "VIRTUAL_ENV": ""},
)
return output.stdout.decode().strip().split()
if args.python == sys.executable:
search_paths = sys.path
else:
search_paths = get_python_sys_path(args.python)
pkgs = importlib_metadata.distributions(path=search_paths)
ignore_pkgs_as_normalize = [
normalize_pkg_name(pkg) for pkg in args.ignore_packages
]
pkgs_as_normalize = [normalize_pkg_name(pkg) for pkg in args.packages]
fail_on_licenses = set()
if args.fail_on:
fail_on_licenses = set(map(str.strip, args.fail_on.split(";")))
allow_only_licenses = set()
if args.allow_only:
allow_only_licenses = set(map(str.strip, args.allow_only.split(";")))
for pkg in pkgs:
pkg_name = normalize_pkg_name(pkg.metadata["name"])
pkg_name_and_version = pkg_name + ":" + pkg.metadata["version"]
if (
pkg_name.lower() in ignore_pkgs_as_normalize
or pkg_name_and_version.lower() in ignore_pkgs_as_normalize
):
continue
if pkgs_as_normalize and pkg_name.lower() not in pkgs_as_normalize:
continue
if not args.with_system and pkg_name in SYSTEM_PACKAGES:
continue
pkg_info = get_pkg_info(pkg)
license_names = select_license_by_source(
args.from_,
cast(List[str], pkg_info["license_classifier"]),
cast(str, pkg_info["license"]),
)
if fail_on_licenses:
failed_licenses = set()
if not args.partial_match:
failed_licenses = case_insensitive_set_intersect(
license_names, fail_on_licenses
)
else:
failed_licenses = case_insensitive_partial_match_set_intersect(
license_names, fail_on_licenses
)
if failed_licenses:
sys.stderr.write(
"fail-on license {} was found for package "
"{}:{}\n".format(
"; ".join(sorted(failed_licenses)),
pkg_info["name"],
pkg_info["version"],
)
)
sys.exit(1)
if allow_only_licenses:
uncommon_licenses = set()
if not args.partial_match:
uncommon_licenses = case_insensitive_set_diff(
license_names, allow_only_licenses
)
else:
uncommon_licenses = case_insensitive_partial_match_set_diff(
license_names, allow_only_licenses
)
if len(uncommon_licenses) == len(license_names):
sys.stderr.write(
"license {} not in allow-only licenses was found"
" for package {}:{}\n".format(
"; ".join(sorted(uncommon_licenses)),
pkg_info["name"],
pkg_info["version"],
)
)
sys.exit(1)
yield pkg_info
def create_licenses_table(
args: CustomNamespace,
output_fields: Iterable[str] = DEFAULT_OUTPUT_FIELDS,
) -> PrettyTable:
table = factory_styled_table_with_args(args, output_fields)
for pkg in get_packages(args):
row = []
for field in output_fields:
if field == "License":
license_set = select_license_by_source(
args.from_,
cast(List[str], pkg["license_classifier"]),
cast(str, pkg["license"]),
)
license_str = "; ".join(sorted(license_set))
row.append(license_str)
elif field == "License-Classifier":
row.append(
"; ".join(sorted(pkg["license_classifier"]))
or LICENSE_UNKNOWN
)
elif field.lower() in pkg:
row.append(cast(str, pkg[field.lower()]))
else:
row.append(cast(str, pkg[FIELDS_TO_METADATA_KEYS[field]]))
table.add_row(row)
return table
def create_summary_table(args: CustomNamespace) -> PrettyTable:
counts = Counter(
"; ".join(
sorted(
select_license_by_source(
args.from_,
cast(List[str], pkg["license_classifier"]),
cast(str, pkg["license"]),
)
)
)
for pkg in get_packages(args)
)
table = factory_styled_table_with_args(args, SUMMARY_FIELD_NAMES)
for license, count in counts.items():
table.add_row([count, license])
return table
def case_insensitive_set_intersect(set_a, set_b):
"""Same as set.intersection() but case-insensitive"""
common_items = set()
set_b_lower = {item.lower() for item in set_b}
for elem in set_a:
if elem.lower() in set_b_lower:
common_items.add(elem)
return common_items
def case_insensitive_partial_match_set_intersect(set_a, set_b):
common_items = set()
for item_a in set_a:
for item_b in set_b:
if item_b.lower() in item_a.lower():
common_items.add(item_a)
return common_items
def case_insensitive_partial_match_set_diff(set_a, set_b):
uncommon_items = set_a.copy()
for item_a in set_a:
for item_b in set_b:
if item_b.lower() in item_a.lower():
uncommon_items.remove(item_a)
return uncommon_items
def case_insensitive_set_diff(set_a, set_b):
"""Same as set.difference() but case-insensitive"""
uncommon_items = set()
set_b_lower = {item.lower() for item in set_b}
for elem in set_a:
if not elem.lower() in set_b_lower:
uncommon_items.add(elem)
return uncommon_items
class JsonPrettyTable(PrettyTable):
"""PrettyTable-like class exporting to JSON"""
def _format_row(self, row: Iterable[str]) -> dict[str, str | list[str]]:
resrow: dict[str, str | List[str]] = {}
for field, value in zip(self._field_names, row):
resrow[field] = value
return resrow
def get_string(self, **kwargs: str | list[str]) -> str:
# import included here in order to limit dependencies
# if not interested in JSON output,
# then the dependency is not required
import json
options = self._get_options(kwargs)
rows = self._get_rows(options)
formatted_rows = self._format_rows(rows)
lines = []
for row in formatted_rows:
lines.append(row)
return json.dumps(lines, indent=2, sort_keys=True)
class JsonLicenseFinderTable(JsonPrettyTable):
def _format_row(self, row: Iterable[str]) -> dict[str, str | list[str]]:
resrow: dict[str, str | List[str]] = {}
for field, value in zip(self._field_names, row):
if field == "Name":
resrow["name"] = value
if field == "Version":
resrow["version"] = value
if field == "License":
resrow["licenses"] = [value]
return resrow
def get_string(self, **kwargs: str | list[str]) -> str:
# import included here in order to limit dependencies
# if not interested in JSON output,
# then the dependency is not required
import json
options = self._get_options(kwargs)
rows = self._get_rows(options)
formatted_rows = self._format_rows(rows)
lines = []
for row in formatted_rows:
lines.append(row)
return json.dumps(lines, sort_keys=True)
class CSVPrettyTable(PrettyTable):
"""PrettyTable-like class exporting to CSV"""
def get_string(self, **kwargs: str | list[str]) -> str:
def esc_quotes(val: bytes | str) -> str:
"""
Meta-escaping double quotes
https://tools.ietf.org/html/rfc4180
"""
try:
return cast(str, val).replace('"', '""')
except UnicodeDecodeError: # pragma: no cover
return cast(bytes, val).decode("utf-8").replace('"', '""')
except UnicodeEncodeError: # pragma: no cover
return str(
cast(str, val).encode("unicode_escape").replace('"', '""') # type: ignore[arg-type] # noqa: E501
)
options = self._get_options(kwargs)
rows = self._get_rows(options)
formatted_rows = self._format_rows(rows)
lines = []
formatted_header = ",".join(
['"%s"' % (esc_quotes(val),) for val in self._field_names]
)
lines.append(formatted_header)
for row in formatted_rows:
formatted_row = ",".join(
['"%s"' % (esc_quotes(val),) for val in row]
)
lines.append(formatted_row)
return "\n".join(lines)
class PlainVerticalTable(PrettyTable):
"""PrettyTable for outputting to a simple non-column based style.
When used with --with-license-file, this style is similar to the default
style generated from Angular CLI's --extractLicenses flag.
"""
def get_string(self, **kwargs: str | list[str]) -> str:
options = self._get_options(kwargs)
rows = self._get_rows(options)
output = ""
for row in rows:
for v in row:
output += "{}\n".format(v)
output += "\n"
return output
def factory_styled_table_with_args(
args: CustomNamespace,
output_fields: Iterable[str] = DEFAULT_OUTPUT_FIELDS,
) -> PrettyTable:
table = PrettyTable()
table.field_names = output_fields # type: ignore[assignment]
table.align = "l" # type: ignore[assignment]
table.border = args.format_ in (
FormatArg.MARKDOWN,
FormatArg.RST,
FormatArg.CONFLUENCE,
FormatArg.JSON,
)
table.header = True
if args.format_ == FormatArg.MARKDOWN:
table.junction_char = "|"
table.hrules = RULE_HEADER
elif args.format_ == FormatArg.RST:
table.junction_char = "+"
table.hrules = RULE_ALL
elif args.format_ == FormatArg.CONFLUENCE:
table.junction_char = "|"
table.hrules = RULE_NONE
elif args.format_ == FormatArg.JSON:
table = JsonPrettyTable(table.field_names)
elif args.format_ == FormatArg.JSON_LICENSE_FINDER:
table = JsonLicenseFinderTable(table.field_names)
elif args.format_ == FormatArg.CSV:
table = CSVPrettyTable(table.field_names)
elif args.format_ == FormatArg.PLAIN_VERTICAL:
table = PlainVerticalTable(table.field_names)
return table
def find_license_from_classifier(classifiers: list[str]) -> list[str]:
licenses = []
for classifier in filter(lambda c: c.startswith("License"), classifiers):
license = classifier.split(" :: ")[-1]
# Through the declaration of 'Classifier: License :: OSI Approved'
if license != "OSI Approved":
licenses.append(license)
return licenses
def select_license_by_source(
from_source: FromArg, license_classifier: list[str], license_meta: str
) -> set[str]:
license_classifier_set = set(license_classifier) or {LICENSE_UNKNOWN}
if (
from_source == FromArg.CLASSIFIER
or from_source == FromArg.MIXED
and len(license_classifier) > 0
):
return license_classifier_set
else:
return {license_meta}
def get_output_fields(args: CustomNamespace) -> list[str]:
if args.summary:
return list(SUMMARY_OUTPUT_FIELDS)
output_fields = list(DEFAULT_OUTPUT_FIELDS)
if args.from_ == FromArg.ALL:
output_fields.append("License-Metadata")
output_fields.append("License-Classifier")
else:
output_fields.append("License")
if args.with_authors:
output_fields.append("Author")
if args.with_maintainers:
output_fields.append("Maintainer")
if args.with_urls:
output_fields.append("URL")
if args.with_description:
output_fields.append("Description")
if args.no_version:
output_fields.remove("Version")
if args.with_license_file:
if not args.no_license_path:
output_fields.append("LicenseFile")
output_fields.append("LicenseText")
if args.with_notice_file:
output_fields.append("NoticeText")
if not args.no_license_path:
output_fields.append("NoticeFile")
return output_fields
def get_sortby(args: CustomNamespace) -> str:
if args.summary and args.order == OrderArg.COUNT:
return "Count"
elif args.summary or args.order == OrderArg.LICENSE:
return "License"
elif args.order == OrderArg.NAME:
return "Name"
elif args.order == OrderArg.AUTHOR and args.with_authors:
return "Author"
elif args.order == OrderArg.MAINTAINER and args.with_maintainers:
return "Maintainer"
elif args.order == OrderArg.URL and args.with_urls:
return "URL"
return "Name"
def create_output_string(args: CustomNamespace) -> str:
output_fields = get_output_fields(args)
if args.summary:
table = create_summary_table(args)
else:
table = create_licenses_table(args, output_fields)
sortby = get_sortby(args)
if args.format_ == FormatArg.HTML:
html = table.get_html_string(fields=output_fields, sortby=sortby)
return html.encode("ascii", errors="xmlcharrefreplace").decode("ascii")
else:
return table.get_string(fields=output_fields, sortby=sortby)
def create_warn_string(args: CustomNamespace) -> str:
warn_messages = []
warn = partial(output_colored, "33")
if args.with_license_file and not args.format_ == FormatArg.JSON:
message = warn(
(
"Due to the length of these fields, this option is "
"best paired with --format=json."
)
)
warn_messages.append(message)
if args.summary and (args.with_authors or args.with_urls):
message = warn(
(
"When using this option, only --order=count or "
"--order=license has an effect for the --order "
"option. And using --with-authors and --with-urls "
"will be ignored."
)
)
warn_messages.append(message)
return "\n".join(warn_messages)
class CustomHelpFormatter(argparse.HelpFormatter): # pragma: no cover
def __init__(
self,
prog: str,
indent_increment: int = 2,
max_help_position: int = 24,
width: Optional[int] = None,
) -> None:
max_help_position = 30
super().__init__(
prog,
indent_increment=indent_increment,
max_help_position=max_help_position,
width=width,
)
def _format_action(self, action: argparse.Action) -> str:
flag_indent_argument: bool = False
text = self._expand_help(action)
separator_pos = text[:3].find("|")
if separator_pos != -1 and "I" in text[:separator_pos]:
self._indent()
flag_indent_argument = True
help_str = super()._format_action(action)
if flag_indent_argument:
self._dedent()
return help_str
def _expand_help(self, action: argparse.Action) -> str:
if isinstance(action.default, Enum):
default_value = enum_key_to_value(action.default)
return cast(str, self._get_help_string(action)) % {
"default": default_value
}
return super()._expand_help(action)
def _split_lines(self, text: str, width: int) -> List[str]:
separator_pos = text[:3].find("|")
if separator_pos != -1:
flag_splitlines: bool = "R" in text[:separator_pos]
text = text[separator_pos + 1:] # fmt: skip
if flag_splitlines:
return text.splitlines()
return super()._split_lines(text, width)
class CustomNamespace(argparse.Namespace):
from_: "FromArg"
order: "OrderArg"
format_: "FormatArg"
summary: bool
output_file: str
ignore_packages: List[str]
packages: List[str]
with_system: bool
with_authors: bool
with_urls: bool
with_description: bool
with_license_file: bool
no_license_path: bool
with_notice_file: bool
filter_strings: bool
filter_code_page: str
partial_match: bool
fail_on: Optional[str]
allow_only: Optional[str]
class CompatibleArgumentParser(argparse.ArgumentParser):
def parse_args( # type: ignore[override]
self,
args: None | Sequence[str] = None,
namespace: None | CustomNamespace = None,
) -> CustomNamespace:
args_ = cast(CustomNamespace, super().parse_args(args, namespace))
self._verify_args(args_)
return args_
def _verify_args(self, args: CustomNamespace) -> None:
if args.with_license_file is False and (
args.no_license_path is True or args.with_notice_file is True
):
self.error(
"'--no-license-path' and '--with-notice-file' require "
"the '--with-license-file' option to be set"
)
if args.filter_strings is False and args.filter_code_page != "latin1":
self.error(
"'--filter-code-page' requires the '--filter-strings' "
"option to be set"
)
try:
codecs.lookup(args.filter_code_page)
except LookupError:
self.error(
"invalid code page '%s' given for '--filter-code-page, "
"check https://docs.python.org/3/library/codecs.html"
"#standard-encodings for valid code pages"
% args.filter_code_page
)
class NoValueEnum(Enum):
def __repr__(self) -> str: # pragma: no cover
return "<%s.%s>" % (self.__class__.__name__, self.name)
class FromArg(NoValueEnum):
META = M = auto()
CLASSIFIER = C = auto()
MIXED = MIX = auto()
ALL = auto()
class OrderArg(NoValueEnum):
COUNT = C = auto()
LICENSE = L = auto()
NAME = N = auto()
AUTHOR = A = auto()
MAINTAINER = M = auto()
URL = U = auto()
class FormatArg(NoValueEnum):
PLAIN = P = auto()
PLAIN_VERTICAL = auto()
MARKDOWN = MD = M = auto()
RST = REST = R = auto()
CONFLUENCE = C = auto()
HTML = H = auto()
JSON = J = auto()
JSON_LICENSE_FINDER = JLF = auto()
CSV = auto()
def value_to_enum_key(value: str) -> str:
return value.replace("-", "_").upper()
def enum_key_to_value(enum_key: Enum) -> str:
return enum_key.name.replace("_", "-").lower()
def choices_from_enum(enum_cls: Type[NoValueEnum]) -> List[str]:
return [
key.replace("_", "-").lower() for key in enum_cls.__members__.keys()
]
def get_value_from_enum(
enum_cls: Type[NoValueEnum], value: str
) -> NoValueEnum:
return getattr(enum_cls, value_to_enum_key(value))
MAP_DEST_TO_ENUM = {
"from_": FromArg,
"order": OrderArg,
"format_": FormatArg,
}
class SelectAction(argparse.Action):
def __call__( # type: ignore[override]
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str,
option_string: Optional[str] = None,
) -> None:
enum_cls = MAP_DEST_TO_ENUM[self.dest]
setattr(namespace, self.dest, get_value_from_enum(enum_cls, values))
def load_config_from_file(pyproject_path: str):
if Path(pyproject_path).exists():
with open(pyproject_path, "rb") as f:
return tomli.load(f).get("tool", {}).get(__pkgname__, {})
return {}
def create_parser(
pyproject_path: str = "pyproject.toml",
) -> CompatibleArgumentParser:
parser = CompatibleArgumentParser(
description=__summary__, formatter_class=CustomHelpFormatter
)
config_from_file = load_config_from_file(pyproject_path)
common_options = parser.add_argument_group("Common options")
format_options = parser.add_argument_group("Format options")
verify_options = parser.add_argument_group("Verify options")
parser.add_argument(
"-v", "--version", action="version", version="%(prog)s " + __version__
)
common_options.add_argument(
"--python",
type=str,
default=config_from_file.get("python", sys.executable),
metavar="PYTHON_EXEC",
help="R| path to python executable to search distributions from\n"
"Package will be searched in the selected python's sys.path\n"
"By default, will search packages for current env executable\n"
"(default: sys.executable)",
)
common_options.add_argument(
"--from",
dest="from_",
action=SelectAction,
type=str,
default=get_value_from_enum(
FromArg, config_from_file.get("from", "mixed")
),
metavar="SOURCE",
choices=choices_from_enum(FromArg),
help="R|where to find license information\n"
'"meta", "classifier, "mixed", "all"\n'
"(default: %(default)s)",
)
common_options.add_argument(
"-o",
"--order",
action=SelectAction,
type=str,
default=get_value_from_enum(
OrderArg, config_from_file.get("order", "name")
),
metavar="COL",
choices=choices_from_enum(OrderArg),
help="R|order by column\n"
'"name", "license", "author", "url"\n'
"(default: %(default)s)",
)
common_options.add_argument(
"-f",
"--format",
dest="format_",
action=SelectAction,
type=str,
default=get_value_from_enum(
FormatArg, config_from_file.get("format", "plain")
),
metavar="STYLE",
choices=choices_from_enum(FormatArg),
help="R|dump as set format style\n"
'"plain", "plain-vertical" "markdown", "rst", \n'
'"confluence", "html", "json", \n'
'"json-license-finder", "csv"\n'
"(default: %(default)s)",
)
common_options.add_argument(
"--summary",
action="store_true",
default=config_from_file.get("summary", False),
help="dump summary of each license",
)
common_options.add_argument(
"--output-file",
action="store",
default=config_from_file.get("output-file"),
type=str,
help="save license list to file",
)
common_options.add_argument(
"-i",
"--ignore-packages",