forked from aboutcode-org/python-inspector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpypi.py
More file actions
2040 lines (1711 loc) · 68.6 KB
/
pypi.py
File metadata and controls
2040 lines (1711 loc) · 68.6 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/aboutcode-org/scancode-toolkit for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import ast
from configparser import ConfigParser
import copy
import json
import logging
from pathlib import Path
import os
import re
import sys
from typing import NamedTuple
import tempfile
import zipfile
import dparse2
import packvers as packaging
import pip_requirements_parser
import pkginfo2
from commoncode import fileutils
from packvers.specifiers import SpecifierSet
from packageurl import PackageURL
from packvers import markers
from packvers.requirements import Requirement
from packvers.utils import canonicalize_name
from _packagedcode import models
from _packagedcode.utils import build_description
from _packagedcode.utils import combine_expressions
from _packagedcode.utils import yield_dependencies_from_package_data
from _packagedcode.utils import yield_dependencies_from_package_resource
# FIXME: we always want to use the external library rather than the built-in for now
import importlib_metadata
import base64
from commoncode.fileutils import as_posixpath
try:
from zipfile import Path as ZipPath
except ImportError:
from zipp import Path as ZipPath
"""
Detect and collect Python packages information.
"""
# TODO: add support for poetry and setup.cfg and metadata.json
# TODO: add support for pex, pyz, etc.
# TODO: Add missing ABOUT file for Pyserial code
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 print(' '.join(isinstance(a, str) and a or repr(a) for a in args))
class BasePypiHandler(models.DatafileHandler):
@classmethod
def compute_normalized_license(cls, package):
return compute_normalized_license(package.declared_license)
class PythonEggPkgInfoFile(BasePypiHandler):
datasource_id = 'pypi_egg_pkginfo'
default_package_type = 'pypi'
default_primary_language = 'Python'
path_patterns = ('*/EGG-INFO/PKG-INFO',)
description = 'PyPI extracted egg PKG-INFO'
documentation_url = 'https://peps.python.org/pep-0376/'
@classmethod
def parse(cls, location):
yield parse_metadata(
location=location,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
@classmethod
def assign_package_to_resources(cls, package, resource, codebase):
# two levels up
root = resource.parent(codebase).parent(codebase)
if root:
return models.DatafileHandler.assign_package_to_resources(package, root, codebase)
class PythonEditableInstallationPkgInfoFile(BasePypiHandler):
datasource_id = 'pypi_editable_egg_pkginfo'
default_package_type = 'pypi'
default_primary_language = 'Python'
path_patterns = ('*.egg-info/PKG-INFO',)
description = 'PyPI editable local installation PKG-INFO'
documentation_url = 'https://peps.python.org/pep-0376/'
@classmethod
def parse(cls, location):
yield parse_metadata(
location=location,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
@classmethod
def assign_package_to_resources(cls, package, resource, codebase):
# only the parent for now... though it can be more complex
return models.DatafileHandler.assign_package_to_parent_tree(package, resource, codebase)
class BaseExtractedPythonLayout(BasePypiHandler):
"""
Base class for development repos, sdist tarballs and other related extracted
layourt for Python packages that can use and mix multiple datafiles.
"""
@classmethod
def assemble(cls, package_data, resource, codebase):
# a source distribution can have many manifests
datafile_name_patterns = (
'Pipfile.lock',
'Pipfile',
) + PipRequirementsFileHandler.path_patterns
# TODO: we want PKG-INFO first, then (setup.py, setup.cfg), then pyproject.toml for poetry
# then we have the rest of the lock files (pipfile, pipfile.lock, etc.)
package_resource = None
if resource.name == 'PKG-INFO':
package_resource = resource
elif resource.name in datafile_name_patterns:
if resource.has_parent():
siblings = resource.siblings(codebase)
package_resource = [r for r in siblings if r.name == 'PKG-INFO']
if package_resource:
package_resource = package_resource[0]
package = None
if package_resource:
pkg_data = package_resource.package_data[0]
pkg_data = models.PackageData.from_dict(pkg_data)
if pkg_data.purl:
package = models.Package.from_package_data(
package_data=pkg_data,
datafile_path=package_resource.path,
)
package_resource.for_packages.append(package.package_uid)
package_resource.save(codebase)
yield package_resource
yield from yield_dependencies_from_package_data(
package_data=pkg_data,
datafile_path=package_resource.path,
package_uid=package.package_uid
)
else:
setup_resources = []
if resource.has_parent():
siblings = resource.siblings(codebase)
setup_resources = [
r for r in siblings
if r.name in ('setup.py', 'setup.cfg')
and r.package_data
]
setup_package_data = [
(setup_resource, models.PackageData.from_dict(setup_resource.package_data[0]))
for setup_resource in setup_resources
]
setup_package_data = sorted(setup_package_data, key=lambda s: bool(s[1].purl), reverse=True)
for setup_resource, setup_pkg_data in setup_package_data:
if setup_pkg_data.purl:
if not package:
package = models.Package.from_package_data(
package_data=setup_pkg_data,
datafile_path=setup_resource.path,
)
package_resource = setup_resource
else:
package.update(setup_pkg_data, setup_resource.path)
if package:
for setup_resource, setup_pkg_data in setup_package_data:
setup_resource.for_packages.append(package.package_uid)
setup_resource.save(codebase)
yield setup_resource
yield from yield_dependencies_from_package_data(
package_data=setup_pkg_data,
datafile_path=setup_resource.path,
package_uid=package.package_uid
)
if package:
if not package.license_expression:
package.license_expression = compute_normalized_license(package.declared_license)
package_uid = package.package_uid
root = package_resource.parent(codebase)
if root:
for py_res in cls.walk_pypi(resource=root, codebase=codebase):
if py_res.is_dir:
continue
if package_uid and package_uid not in py_res.for_packages:
py_res.for_packages.append(package_uid)
py_res.save(codebase)
yield py_res
elif codebase.has_single_resource:
if package_uid and package_uid not in package_resource.for_packages:
package_resource.for_packages.append(package_uid)
package_resource.save(codebase)
yield package
else:
package_uid = None
if package_resource:
for sibling in package_resource.siblings(codebase):
if sibling and sibling.name in datafile_name_patterns:
yield from yield_dependencies_from_package_resource(
resource=sibling,
package_uid=package_uid
)
if package_uid and package_uid not in sibling.for_packages:
sibling.for_packages.append(package_uid)
sibling.save(codebase)
yield sibling
@classmethod
def walk_pypi(cls, resource, codebase):
"""
Walk the ``codebase`` Codebase top-down, breadth-first starting from the
``resource`` Resource.
Skip the directory named "site-packages": this avoids
reporting nested vendored packages as being part of their parent.
Instead they will be reported on their own.
"""
for child in resource.children(codebase):
if child.name == 'site-packages':
continue
yield child
if child.is_dir:
for subchild in cls.walk_pypi(child, codebase):
yield subchild
class PythonSdistPkgInfoFile(BaseExtractedPythonLayout):
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 is_datafile(cls, location):
return (
super().is_datafile(location) and
not PythonEggPkgInfoFile.is_datafile(location) and
not PythonEditableInstallationPkgInfoFile.is_datafile(location)
)
@classmethod
def parse(cls, location):
yield parse_metadata(
location=location,
datasource_id=cls.datasource_id,
package_type=cls.default_package_type,
)
class PythonInstalledWheelMetadataFile(BasePypiHandler):
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,
)
@classmethod
def assign_package_to_resources(cls, package, resource, codebase):
"""
Assign files to package for an installed wheel. This requires a bit
of navigation around as the files can be in multiple places.
"""
site_packages = resource.parent(codebase).parent(codebase).parent(codebase)
if not site_packages:
return
package_data = resource.package_data
assert len(resource.package_data) == 1, (
f'Unsupported Pypi METADATA wheel structure: {resource.path!r} '
f'with multiple {package_data!r}'
)
package_data = models.PackageData.from_dict(package_data[0])
package_uid = package.package_uid
if package_uid:
# save thyself!
resource.for_packages.append(package_uid)
resource.save(codebase)
# collect actual paths based on the file references
for file_ref in package_data.file_references:
path_ref = file_ref.path
if path_ref.startswith('..'):
# relative paths need special treatment
# most of thense are references to bin ../../../bin/wheel
cannot_resolve = False
ref_resource = None
while path_ref.startswith('..'):
_, _, path_ref.partition('../')
ref_resource = site_packages.parent(codebase)
if not ref_resource:
cannot_resolve = True
break
if cannot_resolve or not ref_resource:
# TODO:w e should log these kind of things
continue
else:
if package_uid:
ref_resource.for_packages.append(package_uid)
ref_resource.save(codebase)
else:
ref_resource = get_resource_for_path(
path=path_ref,
root=site_packages,
codebase=codebase,
)
if ref_resource and package_uid:
ref_resource.for_packages.append(package_uid)
ref_resource.save(codebase)
def get_resource_for_path(path, root, codebase):
"""
Return a resource in ``codebase`` that has a ``path`` relative to the
``root` Resource
For example, say we start from this:
path: this/is/that therefore segments [this, is, that]
root: /usr/foo
We would have these iterations:
iteration1
root = /usr/foo
segments = [this, is, that]
seg this
segments = [is, that]
children = [/usr/foo/this]
root = /usr/foo/this
iteration2
root = /usr/foo/this
segments = [is, that]
seg is
segments = [that]
children = [/usr/foo/this/is]
root = /usr/foo/this/is
iteration3
root = /usr/foo/this/is
segments = [that]
seg that
segments = []
children = [/usr/foo/this/is/that]
root = /usr/foo/this/is/that
finally return root as /usr/foo/this/is/that
"""
segments = path.strip('/').split('/')
while segments:
seg = segments.pop(0)
children = [c for c in root.children(codebase) if c.name == seg]
if len(children) != 1:
return
else:
root = children[0]
return root
# FIXME: Implement me
class PyprojectTomlHandler(models.NonAssemblableDatafileHandler):
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, extra_data = get_urls(metainfo=meta, name=name, version=version)
dependencies = get_dist_dependencies(dist)
file_references = list(get_file_references(dist))
package_data = models.PackageData(
datasource_id=datasource_id,
type=package_type,
primary_language='Python',
name=name,
version=version,
description=get_description(metainfo=meta, location=str(location)),
# TODO: https://github.com/aboutcode-org/scancode-toolkit/issues/3014
declared_license=get_declared_license(meta),
keywords=get_keywords(meta),
parties=get_parties(meta),
dependencies=dependencies,
file_references=file_references,
extra_data=extra_data,
**urls,
)
if not package_data.license_expression and package_data.declared_license:
package_data.license_expression = models.compute_normalized_license(package_data.declared_license)
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)
def get_file_references(dist):
"""
Yield FileReference found in a ``dist`` importlib_metadata.Distribution.
"""
if not dist.files:
return
for filepath in dist.files or []:
# FIXME: the path is relative to the "site-packages" directory or the
# root of a wheel but this should be a scan path
ref = models.FileReference(
path=as_posixpath(str(filepath)),
size=filepath.size,
)
filehash = filepath.hash
if filehash:
algo = filehash.mode
value = filehash.value
if algo in ('sha256', 'sha512'):
# convert back to hex as this is a base64 without padding otherwise
value = urlsafe_b64decode(value).hex()
setattr(ref, algo, value)
yield ref
class PypiWheelHandler(BasePypiHandler):
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):
from python_inspector import lockfile
from python_inspector.utils_pypi import PYINSP_CACHE_LOCK_TIMEOUT
lock_file = os.path.join(f"{location}.lockfile")
with lockfile.FileLock(lock_file).locked(timeout=PYINSP_CACHE_LOCK_TIMEOUT):
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(BasePypiHandler):
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):
from python_inspector import lockfile
from python_inspector.utils_pypi import PYINSP_CACHE_LOCK_TIMEOUT
lock_file = os.path.join(f"{location}.lockfile")
with lockfile.FileLock(lock_file).locked(timeout=PYINSP_CACHE_LOCK_TIMEOUT):
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(BasePypiHandler):
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, extra_data = 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),
extra_data=extra_data,
**urls,
)
class PythonSetupPyHandler(BaseExtractedPythonLayout):
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, extra_data = get_urls(metainfo=setup_args, name=name, version=version)
dependencies = get_setup_py_dependencies(setup_args)
python_requires = get_setup_py_python_requires(setup_args)
extra_data.update(python_requires)
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_setup_parties(setup_args),
declared_license=get_declared_license(setup_args),
dependencies=dependencies,
keywords=get_keywords(setup_args),
extra_data=extra_data,
**urls,
)
class ResolvedPurl(NamedTuple):
"""
A resolved PURL
"""
purl: PackageURL
is_resolved: bool
def create_dependency_for_python_requires(python_requires_specifier):
"""
Return a mock python DependentPackage created from a ``python_requires_specifier``.
"""
purl = PackageURL(type="generic", name="python")
resolved_purl = get_resolved_purl(purl=purl, specifiers=SpecifierSet(python_requires_specifier))
return models.DependentPackage(
purl=str(resolved_purl.purl),
scope="python",
is_runtime=True,
is_optional=False,
is_resolved=resolved_purl.is_resolved,
extracted_requirement=f"python_requires{python_requires_specifier}",
)
class BaseDependencyFileHandler(BasePypiHandler):
"""
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(BaseExtractedPythonLayout):
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()
dependent_packages = []
with open(location) as f:
parser.read_file(f)
for section in parser.values():
if section.name == 'options':
scope_by_sub_section = {
"install_requires": "install",
"tests_require": "test",
"setup_requires": "setup",
"python_requires": "python",
}
for sub_section, scope in scope_by_sub_section.items():
if sub_section not in section:
continue
if scope != "python":
reqs = list(get_requirement_from_section(section=section, sub_section=sub_section))
dependent_packages.extend(cls.parse_reqs(reqs, scope))
continue
python_requires_specifier = section[sub_section]
pd = create_dependency_for_python_requires(python_requires_specifier)
dependent_packages.append(pd)
if section.name == "options.extras_require":
for sub_section in section:
reqs = list(get_requirement_from_section(section=section, sub_section=sub_section))
dependent_packages.extend(cls.parse_reqs(reqs, sub_section))
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'),
)
]
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=dependent_packages,
)
@classmethod
def parse_reqs(cls, reqs, scope):
"""
Parse a list of requirements and return a list of dependencies
"""
dependent_packages = []
for req in reqs:
req_parsed = packaging.requirements.Requirement(str(req))
name = canonicalize_name(req_parsed.name)
purl = PackageURL(type="pypi", name=name)
specifiers = req_parsed.specifier._specs
resolved_purl = get_resolved_purl(purl=purl, specifiers=specifiers)
dependent_packages.append(
models.DependentPackage(
purl=str(resolved_purl.purl),
scope=scope,
is_runtime=True,
is_optional=False,
is_resolved=resolved_purl.is_resolved,
extracted_requirement=req
)
)
return dependent_packages
def get_resolved_purl(purl: PackageURL, specifiers: SpecifierSet):
"""
Check if the purl is resolved and return a ResolvedPurl.
If the purl is resolved, update its version to the pinned version
"""
is_resolved = False
if len(specifiers) == 1:
specifier = list(specifiers)[0]
if specifier.operator in ('==', '==='):
is_resolved = True
purl = purl._replace(version=specifier.version)
return ResolvedPurl(
purl=purl,
is_resolved=is_resolved,
)
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, extra_data = 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,
extra_data=extra_data,
)
# TODO: enable nested load
def get_requirements_txt_dependencies(location, include_nested=False):
"""
Return a two-tuple of (list of deps, mapping of extra data) list of
DependentPackage found in a requirements file at ``location`` or tuple of
([], {})
"""
req_file = pip_requirements_parser.RequirementsFile.from_file(
filename=location,
include_nested=include_nested,
)
if not req_file or not req_file.requirements:
return [], {}
# for now we ignore errors
extra_data = {}
for opt in req_file.options:
for name, value in opt.options.items():
if name not in extra_data:
extra_data[name] = value
else:
if isinstance(value, list):
extra_data[name].extend(value)
else:
extra_data[name] = value
dependent_packages = []
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=canonicalize_name(req.name), version=version)
else:
# this is odd, but this can be null
purl = None
purl = purl and purl.to_string() or None
hash_options = req.hash_options or []
req.hash_options = []
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,
extra_data=dict(
is_editable=req.is_editable,
link=req.link and req.link.url or None,
hash_options=hash_options,
is_constraint=req.is_constraint,
is_archive=req.is_archive,
is_wheel=req.is_wheel,
is_url=req.is_url,
is_vcs_url=req.is_vcs_url,
is_name_at_url=req.is_name_at_url,
is_local_path=req.is_local_path,
),
)
)
return dependent_packages, extra_data
def can_process_dependent_package(dep: models.DependentPackage):
"""
Return True if we can process the dependent package
typically anything that's not a plain standard specifier
can not be processed such as an editable requirement
"""
# copying dep.extra_data to avoid mutating the original
requirement_flags = copy.copy(dep.extra_data or {})