-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathpypi.py
More file actions
1329 lines (1095 loc) · 41.1 KB
/
Copy pathpypi.py
File metadata and controls
1329 lines (1095 loc) · 41.1 KB
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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import ast
import base64
import io
import json
import logging
import os
import re
import sys
import zipfile
from configparser import ConfigParser
from pathlib import Path
import dparse2
import importlib_metadata
import pip_requirements_parser
import pkginfo2
from commoncode import fileutils
from packageurl import PackageURL
from packaging import markers
from packaging.requirements import Requirement
from packaging.utils import canonicalize_name
from _packagedcode import models
from _packagedcode.utils import build_description
# FIXME: we always want to use the external library rather than the built-in for now
try:
from zipfile import Path as ZipPath
except ImportError:
from zipp import Path as ZipPath
"""
Detect and collect Python packages information.
Originally vendored from scancode-toolkit packagedcode.pypi
"""
# TODO: add support for poetry and setup.cfg and metadata.json
# TODO: add support for pex, pyz, etc.
TRACE = False
def logger_debug(*args):
pass
logger = logging.getLogger(__name__)
if TRACE:
logging.basicConfig(stream=sys.stdout)
logger.setLevel(logging.DEBUG)
def logger_debug(*args):
return logger.debug(" ".join(isinstance(a, str) and a or repr(a) for a in args))
class PythonSdistPkgInfoFile(models.DatafileHandler):
datasource_id = "pypi_sdist_pkginfo"
default_package_type = "pypi"
default_primary_language = "Python"
path_patterns = ("*/PKG-INFO",)
description = "PyPI extracted sdist PKG-INFO"
documentation_url = "https://peps.python.org/pep-0314/"
@classmethod
def parse(cls, location):
yield parse_metadata(
location=location,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
class PythonInstalledWheelMetadataFile(models.DatafileHandler):
datasource_id = "pypi_wheel_metadata"
path_patterns = ("*.dist-info/METADATA",)
default_package_type = "pypi"
default_primary_language = "Python"
description = "PyPI installed wheel METADATA"
documentation_url = "https://packaging.python.org/en/latest/specifications/core-metadata/"
@classmethod
def parse(cls, location):
yield parse_metadata(
location=location,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
# FIXME: Implement me
class PyprojectTomlHandler(models.DatafileHandler):
datasource_id = "pypi_pyproject_toml"
path_patterns = ("*pyproject.toml",)
default_package_type = "pypi"
default_primary_language = "Python"
description = "Python pyproject.toml"
documentation_url = "https://peps.python.org/pep-0621/"
META_DIR_SUFFIXES = (
".dist-info",
".egg-info",
"EGG-INFO",
)
def parse_metadata(location, datasource_id, package_type):
"""
Return a PackageData object from a PKG-INFO or METADATA file at ``location``
which is a path string or pathlib.Path-like object (including a possible zip
file ZipPath for a wheel)
Looks in neighboring files as needed when an installed layout is found.
"""
path = location
if not isinstance(location, (Path, ZipPath)):
path = Path(location)
# build from dir if we are an installed distro
parent = path.parent
if parent.name.endswith(META_DIR_SUFFIXES):
path = parent
dist = importlib_metadata.PathDistribution(path)
meta = dist.metadata
name = get_attribute(meta, "Name")
version = get_attribute(meta, "Version")
urls = get_urls(metainfo=meta, name=name, version=version)
dependencies = get_dist_dependencies(dist)
package_data = models.PackageData(
datasource_id=datasource_id,
type=package_type,
primary_language="Python",
name=name,
version=version,
description=get_description(meta, location),
declared_license=get_declared_license(meta),
keywords=get_keywords(meta),
parties=get_parties(meta),
dependencies=dependencies,
**urls,
)
return package_data
def urlsafe_b64decode(data):
"""
urlsafe_b64decode without padding
SPDX-License-Identifier: MIT
Copyright (c) 2012-2014 Daniel Holth <dholth@fastmail.fm> and contributors.
From: https://github.com/pypa/wheel/blob/66208910ab51f4008b034ef4833acfdc920f7606/src/wheel/util.py#L23
"""
pad = b"=" * (4 - (len(data) & 3))
return base64.urlsafe_b64decode(data.encode("ASCII") + pad)
class PypiWheelHandler(models.DatafileHandler):
datasource_id = "pypi_wheel"
path_patterns = ("*.whl",)
# filetypes = ('zip archive',)
default_package_type = "pypi"
default_primary_language = "Python"
description = "PyPI wheel"
documentation_url = "https://peps.python.org/pep-0427/"
@classmethod
def parse(cls, location):
with zipfile.ZipFile(location) as zf:
for path in ZipPath(zf).iterdir():
if not path.name.endswith(META_DIR_SUFFIXES):
continue
for metapath in path.iterdir():
if not metapath.name.endswith("METADATA"):
continue
yield parse_metadata(
location=metapath,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
class PypiEggHandler(models.DatafileHandler):
datasource_id = "pypi_egg"
path_patterns = ("*.egg",)
# filetypes = ('zip archive',)
default_package_type = "pypi"
default_primary_language = "Python"
description = "PyPI egg"
documentation_url = "https://web.archive.org/web/20210604075235/http://peak.telecommunity.com/DevCenter/PythonEggs"
@classmethod
def parse(cls, location):
with zipfile.ZipFile(location) as zf:
for path in ZipPath(zf).iterdir():
if not path.name.endswith(META_DIR_SUFFIXES):
continue
for metapath in path.iterdir():
if not metapath.name.endswith("PKG-INFO"):
continue
yield parse_metadata(
location=metapath,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
class PypiSdistArchiveHandler(models.DatafileHandler):
datasource_id = "pypi_sdist"
path_patterns = (
"*.tar.gz",
"*.tar.bz2",
"*.zip",
)
default_package_type = "pypi"
default_primary_language = "Python"
description = "Python source distribution"
documentation_url = "https://peps.python.org/pep-0643/"
@classmethod
def is_datafile(cls, location, filetypes=tuple()):
if super().is_datafile(location, filetypes=filetypes):
# TODO: there is a structure to an sdists name: aboutcode-toolkit-7.0.0.tar.gz
# TODO: there is more to it than this... based on actual listing of files inside
return True
@classmethod
def parse(cls, location):
# FIXME: add dependencies
try:
sdist = pkginfo2.SDist(location)
except ValueError:
return
name = sdist.name
version = sdist.version
urls = get_urls(metainfo=sdist, name=name, version=version)
yield models.PackageData(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
primary_language=cls.default_primary_language,
name=name,
version=version,
description=get_description(sdist, location=location),
declared_license=get_declared_license(sdist),
keywords=get_keywords(sdist),
parties=get_parties(sdist),
**urls,
)
class PythonSetupPyHandler(models.DatafileHandler):
datasource_id = "pypi_setup_py"
path_patterns = ("*setup.py",)
default_package_type = "pypi"
default_primary_language = "Python"
description = "Python setup.py"
documentation_url = "https://docs.python.org/3/distutils/setupscript.html"
@classmethod
def parse(cls, location):
setup_args = get_setup_py_args(location)
# it may be legit to have a name-less package?
# in anycase we do not want to fail because of that
name = setup_args.get("name")
version = setup_args.get("version")
if not version:
# search for possible dunder versions here and elsewhere
version = detect_version_attribute(location)
urls = get_urls(metainfo=setup_args, name=name, version=version)
yield models.PackageData(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
primary_language=cls.default_primary_language,
name=name,
version=version,
description=get_description(setup_args),
parties=get_parties(setup_args),
declared_license=get_declared_license(setup_args),
dependencies=get_setup_py_dependencies(setup_args),
keywords=get_keywords(setup_args),
**urls,
)
class BaseDependencyFileHandler(models.DatafileHandler):
"""
Base class for a dependency files parsed with the same library
"""
@classmethod
def parse(cls, location):
file_name = fileutils.file_name(location)
dependency_type = get_dparse2_supported_file_name(file_name)
if not dependency_type:
return
dependencies = parse_with_dparse2(
location=location,
file_name=dependency_type,
)
yield models.PackageData(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
primary_language=cls.default_primary_language,
dependencies=dependencies,
)
class SetupCfgHandler(models.DatafileHandler):
datasource_id = "pypi_setup_cfg"
path_patterns = ("*setup.cfg",)
default_package_type = "pypi"
default_primary_language = "Python"
description = "Python setup.cfg"
documentation_url = "https://peps.python.org/pep-0390/"
@classmethod
def parse(cls, location):
file_name = fileutils.file_name(location)
metadata = {}
parser = ConfigParser()
with open(location) as f:
parser.read_file(f)
for section in parser.values():
if section.name == "metadata":
options = (
"name",
"version",
"license",
"url",
"author",
"author_email",
)
for name in options:
content = section.get(name)
if not content:
continue
metadata[name] = content
parties = []
author = metadata.get("author")
if author:
parties = [
models.Party(
type=models.party_person,
name=author,
role="author",
email=metadata.get("author_email"),
)
]
dependency_type = get_dparse2_supported_file_name(file_name)
if not dependency_type:
return
dependencies = parse_with_dparse2(
location=location,
file_name=dependency_type,
)
yield models.PackageData(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
name=metadata.get("name"),
version=metadata.get("version"),
parties=parties,
homepage_url=metadata.get("url"),
primary_language=cls.default_primary_language,
dependencies=dependencies,
)
class PipfileHandler(BaseDependencyFileHandler):
datasource_id = "pipfile"
path_patterns = ("*Pipfile",)
default_package_type = "pypi"
default_primary_language = "Python"
description = "Pipfile"
documentation_url = "https://github.com/pypa/pipfile"
class PipfileLockHandler(BaseDependencyFileHandler):
datasource_id = "pipfile_lock"
path_patterns = ("*Pipfile.lock",)
default_package_type = "pypi"
default_primary_language = "Python"
description = "Pipfile.lock"
documentation_url = "https://github.com/pypa/pipfile"
@classmethod
def parse(cls, location):
with open(location) as f:
content = f.read()
data = json.loads(content)
sha256 = None
if "_meta" in data:
for name, meta in data["_meta"].items():
if name == "hash":
sha256 = meta.get("sha256")
dependent_packages = parse_with_dparse2(
location=location,
file_name="Pipfile.lock",
)
yield models.PackageData(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
primary_language=cls.default_primary_language,
sha256=sha256,
dependencies=dependent_packages,
)
class PipRequirementsFileHandler(BaseDependencyFileHandler):
datasource_id = "pip_requirements"
path_patterns = (
"*requirement*.txt",
"*requirement*.pip",
"*requirement*.in",
"*requires.txt",
"*requirements/*.txt",
"*requirements/*.pip",
"*requirements/*.in",
"*reqs.txt",
)
default_package_type = "pypi"
default_primary_language = "Python"
description = "pip requirements file"
documentation_url = "https://pip.pypa.io/en/latest/reference/requirements-file-format/"
@classmethod
def parse(cls, location):
dependencies = get_requirements_txt_dependencies(location=location)
yield models.PackageData(
datasource_id=cls.datasource_id,
type=cls.default_package_type,
primary_language=cls.default_primary_language,
dependencies=dependencies,
)
# TODO: enable nested load
def get_requirements_txt_dependencies(location, include_nested=False):
"""
Return a list of DependentPackage found in a requirements file at
``location`` or an empty list.
"""
req_file = pip_requirements_parser.RequirementsFile.from_file(
filename=location,
include_nested=include_nested,
)
if not req_file or not req_file.requirements:
return []
dependent_packages = []
# for now we ignore plain options and errors
for req in req_file.requirements:
if req.name:
# will be None if not pinned
version = req.get_pinned_version
purl = PackageURL(type="pypi", name=req.name, version=version)
else:
# this is odd, but this can be null
purl = None
purl = purl and purl.to_string() or None
if req.is_editable:
requirement = req.dumps(with_name=False)
else:
requirement = req.dumps()
if location.endswith(
(
"dev.txt",
"test.txt",
"tests.txt",
)
):
scope = "development"
is_runtime = False
is_optional = True
else:
scope = "install"
is_runtime = True
is_optional = False
dependent_packages.append(
models.DependentPackage(
purl=purl,
scope=scope,
is_runtime=is_runtime,
is_optional=is_optional,
is_resolved=req.is_pinned or False,
extracted_requirement=requirement,
)
)
return dependent_packages
def get_attribute(metainfo, name, multiple=False):
"""
Return the value for the attribute ``name`` in the ``metainfo`` mapping,
pkginfo object or email object. Treat the value as a list of multiple values
if ``multiple`` is True. Return None or an empty list (if multiple is True)
if no value is found or the attribute ``name`` does not exist.
Ignore case (but returns the value for the original case if present.
"""
# note: the approach for this function is to be used with the various
# metainfo objects and dictionsaries we use that can be a
# pkginfo.Distribution, an email.message.EmailMessage or a dict.
# Because of that, the key can be obtained as a plain named attribute,
# either as-is or lowercased (and with dash replaced by dunder) or we
# can use a get on dicts of emails.
def attr_getter(_aname, default):
_aname = _aname.replace("-", "_")
return getattr(metainfo, _aname, default) or getattr(metainfo, _aname.lower(), default)
def item_getter(_iname, getter, default):
getter = getattr(metainfo, getter, None)
if getter:
return getter(_iname, default) or getter(_iname.lower(), default)
return default
if multiple:
return (
attr_getter(name, [])
or item_getter(name, "get_all", [])
or item_getter(name, "get", [])
or []
)
else:
return attr_getter(name, None) or item_getter(name, "get", None) or None
def get_description(metainfo, location=None):
"""
Return a list of keywords found in a ``metainfo`` object or mapping.
"""
description = None
# newer metadata versions use the payload for the description
if hasattr(metainfo, "get_payload"):
description = metainfo.get_payload()
description = description and description.strip() or None
if not description:
# legacymetadata versions use the Description for the description
description = get_attribute(metainfo, "Description")
if not description and location:
# older metadata versions can use a DESCRIPTION.rst file
description = get_legacy_description(location=fileutils.parent_directory(location))
summary = get_attribute(metainfo, "Summary")
description = clean_description(description)
return build_description(summary, description)
def clean_description(description):
"""
Return a cleaned description text, removing extra leading whitespaces if
needed. Some metadata formats padd each description line with 8 spaces. Some
do not. We check first and cleanup if needed.
"""
# TODO: verify what is the impact of Description-Content-Type: if any
description = description or ""
description = description.strip()
lines = description.splitlines(False)
space_padding = " " * 8
# we need cleaning if any of the first two lines starts with 8 spaces
need_cleaning = any(l.startswith(space_padding) for l in lines[:2])
if not need_cleaning:
return description
cleaned_lines = [line[8:] if line.startswith(space_padding) else line for line in lines]
return "\n".join(cleaned_lines)
def get_legacy_description(location):
"""
Return the text of a legacy DESCRIPTION.rst file.
"""
location = os.path.join(location, "DESCRIPTION.rst")
if os.path.exists(location):
with open(location) as i:
return i.read()
def get_declared_license(metainfo):
"""
Return a mapping of declared license information found in a ``metainfo``
object or mapping.
"""
declared_license = {}
# TODO: We should make the declared license as it is, this should be
# updated in scancode to parse a pure string
lic = get_attribute(metainfo, "License")
if lic and not lic == "UNKNOWN":
declared_license["license"] = lic
license_classifiers, _ = get_classifiers(metainfo)
if license_classifiers:
declared_license["classifiers"] = license_classifiers
return declared_license
def get_classifiers(metainfo):
"""
Return a two tuple of lists of (license_classifiers, other_classifiers)
found in a ``metainfo`` object or mapping.
"""
classifiers = get_attribute(metainfo, "Classifier", multiple=True) or get_attribute(
metainfo, "Classifiers", multiple=True
)
if not classifiers:
return [], []
license_classifiers = []
other_classifiers = []
for classifier in classifiers:
if classifier.startswith("License"):
license_classifiers.append(classifier)
else:
other_classifiers.append(classifier)
return license_classifiers, other_classifiers
def get_keywords(metainfo):
"""
Return a list of keywords found in a ``metainfo`` object or mapping.
"""
keywords = []
kws = get_attribute(metainfo, "Keywords") or []
if kws:
if isinstance(kws, str):
kws = kws.split(",")
elif isinstance(kws, (list, tuple)):
pass
else:
kws = [repr(kws)]
kws = [k.strip() for k in kws if k and k.strip()]
keywords.extend(kws)
# we are calling this again and ignoring licenses
_, other_classifiers = get_classifiers(metainfo)
keywords.extend(other_classifiers)
return keywords
def get_parties(metainfo):
"""
Return a list of parties found in a ``metainfo`` object or mapping.
"""
parties = []
author = get_attribute(metainfo, "Author")
author_email = get_attribute(metainfo, "Author-email")
if author or author_email:
parties.append(
models.Party(
type=models.party_person,
name=author or None,
role="author",
email=author_email or None,
)
)
maintainer = get_attribute(metainfo, "Maintainer")
maintainer_email = get_attribute(metainfo, "Maintainer-email")
if maintainer or maintainer_email:
parties.append(
models.Party(
type=models.party_person,
name=maintainer or None,
role="maintainer",
email=maintainer_email or None,
)
)
return parties
def get_setup_py_dependencies(setup_args):
"""
Return a list of DependentPackage found in a ``setup_args`` mapping of
setup.py arguments or an empty list.
"""
dependencies = []
python_requires = setup_args.get("python_requires")
if python_requires:
# FIXME: handle python_requires = >=3.6.*
pass
install_requires = setup_args.get("install_requires")
dependencies.extend(get_requires_dependencies(install_requires, default_scope="install"))
tests_requires = setup_args.get("tests_requires")
dependencies.extend(get_requires_dependencies(tests_requires, default_scope="tests"))
setup_requires = setup_args.get("setup_requires")
dependencies.extend(get_requires_dependencies(setup_requires, default_scope="setup"))
extras_require = setup_args.get("extras_require", {})
for scope, requires in extras_require.items():
dependencies.extend(get_requires_dependencies(requires, default_scope=scope))
return dependencies
def is_simple_requires(requires):
"""
Return True if ``requires`` is a sequence of strings.
"""
return requires and isinstance(requires, list) and all(isinstance(i, str) for i in requires)
def get_dist_dependencies(dist):
"""
Return a list of DependentPackage found in a ``dist`` Distribution object or
an empty list.
"""
# we treat extras as scopes
# TODO: use these for verification?
scopes = dist.metadata.get_all("Provides-Extra") or []
return get_requires_dependencies(requires=dist.requires)
def get_requires_dependencies(requires, default_scope="install"):
"""
Return a list of DependentPackage found in a ``requires`` list of
requirement strings or an empty list.
"""
if not is_simple_requires(requires):
# FIXME: when does this happen? should we log this?
return []
dependent_packages = []
for req in requires or []:
req = Requirement(req)
name = canonicalize_name(req.name)
is_resolved = False
purl = PackageURL(type="pypi", name=name)
# note: packaging.requirements.Requirement.specifier is a
# packaging.specifiers.SpecifierSet object and a SpecifierSet._specs is
# a set of either: packaging.specifiers.Specifier or
# packaging.specifiers.LegacySpecifier and each of these have a
# .operator and .version property
# a packaging.specifiers.SpecifierSet
specifiers_set = req.specifier # a list of packaging.specifiers.Specifier
specifiers = specifiers_set._specs
requirement = None
if specifiers:
# SpecifierSet stringifies to comma-separated sorted Specifiers
requirement = str(specifiers_set)
# are we pinned e.g. resolved? this is true if we have a single
# equality specifier
if len(specifiers) == 1:
specifier = list(specifiers)[0]
if specifier.operator in ("==", "==="):
is_resolved = True
purl = purl._replace(version=specifier.version)
# we use the extra as scope if avialble
scope = get_extra(req.marker) or default_scope
dependent_packages.append(
models.DependentPackage(
purl=purl.to_string(),
scope=scope,
is_runtime=True,
is_optional=False,
is_resolved=is_resolved,
extracted_requirement=str(req),
)
)
return dependent_packages
def get_extra(marker):
"""
Return the "extra" value of a ``marker`` requirement Marker or None.
"""
if not marker or not isinstance(marker, markers.Marker):
return
marks = getattr(marker, "_markers", [])
for mark in marks:
# filter for variable(extra) == value tuples of (Variable, Op, Value)
if not isinstance(mark, tuple) and not len(mark) == 3:
continue
variable, operator, value = mark
if (
isinstance(variable, markers.Variable)
and variable.value == "extra"
and isinstance(operator, markers.Op)
and operator.value == "=="
and isinstance(value, markers.Value)
):
return value.value
def get_dparse2_supported_file_name(file_name):
"""
Return the file_name if this is supported or None given a `file_name`
string.
"""
# this is kludgy but the upstream data structure and API needs this
dfile_names = (
"Pipfile.lock",
"Pipfile",
"conda.yml",
"setup.cfg",
)
for dfile_name in dfile_names:
if file_name.endswith(dfile_name):
return file_name
def parse_with_dparse2(location, file_name=None):
"""
Return a list of DependentPackage built from a dparse2-supported dependency
manifest such as Conda manifest or Pipfile.lock files, or return an empty
list.
"""
with open(location) as f:
content = f.read()
dep_file = dparse2.parse(content, file_name=file_name)
if not dep_file:
return []
dependent_packages = []
for dependency in dep_file.dependencies:
requirement = dependency.name
is_resolved = False
purl = PackageURL(type="pypi", name=dependency.name)
# note: dparse2.dependencies.Dependency.specs comes from
# packaging.requirements.Requirement.specifier
# which in turn is a packaging.specifiers.SpecifierSet objects
# and a SpecifierSet._specs is a set of either:
# packaging.specifiers.Specifier or packaging.specifiers.LegacySpecifier
# and each of these have a .operator and .version property
# a packaging.specifiers.SpecifierSet
specifiers_set = dependency.specs
# a list of packaging.specifiers.Specifier
specifiers = specifiers_set._specs
if specifiers:
# SpecifierSet stringifies to comma-separated sorted Specifiers
requirement = str(specifiers_set)
# are we pinned e.g. resolved?
if len(specifiers) == 1:
specifier = list(specifiers)[0]
if specifier.operator in ("==", "==="):
is_resolved = True
purl = purl._replace(version=specifier.version)
dependent_packages.append(
models.DependentPackage(
purl=purl.to_string(),
# are we always this scope? what if we have requirements-dev.txt?
scope="install",
is_runtime=True,
is_optional=False,
is_resolved=is_resolved,
extracted_requirement=requirement,
)
)
return dependent_packages
def get_setup_py_args(location):
"""
Return a mapping of arguments passed to a setup.py setup() function.
"""
with open(location) as inp:
setup_text = inp.read()
setup_args = {}
# Parse setup.py file and traverse the AST
tree = ast.parse(setup_text)
for statement in tree.body:
# We only care about function calls or assignments to functions named
# `setup` or `main`
if not (
isinstance(statement, (ast.Expr, ast.Call, ast.Assign))
and isinstance(statement.value, ast.Call)
and isinstance(statement.value.func, ast.Name)
# we also look for main as sometimes this is used instead of setup()
and statement.value.func.id in ("setup", "main")
):
continue
# Process the arguments to the setup function
for kw in getattr(statement.value, "keywords", []):
arg_name = kw.arg
if isinstance(kw.value, ast.Str):
setup_args[arg_name] = kw.value.s
elif isinstance(
kw.value,
(
ast.List,
ast.Tuple,
ast.Set,
),
):
# We collect the elements of a list if the element
# and tag function calls
value = [elt.s for elt in kw.value.elts if not isinstance(elt, ast.Call)]
setup_args[arg_name] = value
# TODO: what if isinstance(kw.value, ast.Dict)
# or an expression like a call to version=get_version or version__version__
return setup_args
def get_pypi_urls(name, version):
"""
Return a mapping of computed Pypi URLs for this package
"""
api_data_url = None
if name and version:
api_data_url = f"https://pypi.org/pypi/{name}/{version}/json"
else:
api_data_url = name and f"https://pypi.org/pypi/{name}/json"
repository_download_url = (
name
and version
and f"https://pypi.org/packages/source/{name[0]}/{name}/{name}-{version}.tar.gz"
)
repository_homepage_url = name and f"https://pypi.org/project/{name}"
return dict(
repository_homepage_url=repository_homepage_url,
repository_download_url=repository_download_url,
api_data_url=api_data_url,
)
def get_urls(metainfo, name, version, extra_data=None):
"""
Return a mapping for URLs of this package:
- as plain name/values for URL attributes known in PackageData