• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kivy / python-for-android / 46363471995

30 Nov 2026 06:01AM UTC coverage: 62.914%. First build
46363471995

push

github

web-flow
Handle un-downloadable pinned dependencies in dependency resolution (#3418)

1925 of 3301 branches covered (58.32%)

Branch coverage included in aggregate %.

19 of 25 new or added lines in 2 files covered. (76.0%)

5580 of 8628 relevant lines covered (64.67%)

3.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.64
/pythonforandroid/pythonpackage.py
1
""" This module offers highlevel functions to get package metadata
2
    like the METADATA file, the name, or a list of dependencies.
3

4
    Usage examples:
5

6
       # Getting package name from pip reference:
7
       from pythonforandroid.pythonpackage import get_package_name
8
       print(get_package_name("pillow"))
9
       # Outputs: "Pillow" (note the spelling!)
10

11
       # Getting package dependencies:
12
       from pythonforandroid.pythonpackage import get_package_dependencies
13
       print(get_package_dependencies("pep517"))
14
       # Outputs: "['pytoml']"
15

16
       # Get package name from arbitrary package source:
17
       from pythonforandroid.pythonpackage import get_package_name
18
       print(get_package_name("/some/local/project/folder/"))
19
       # Outputs package name
20

21
    NOTE:
22

23
    Yes, this module doesn't fit well into python-for-android, but this
24
    functionality isn't available ANYWHERE ELSE, and upstream (pip, ...)
25
    currently has no interest in taking this over, so it has no other place
26
    to go.
27
    (Unless someone reading this puts it into yet another packaging lib)
28

29
    Reference discussion/upstream inclusion attempt:
30

31
    https://github.com/pypa/packaging-problems/issues/247
32

33
"""
34

35

36
import functools
6 ✔
37
import os
6 ✔
38
import shutil
6 ✔
39
import subprocess
6 ✔
40
import sys
6 ✔
41
import tarfile
6 ✔
42
import tempfile
6 ✔
43
import time
6 ✔
44
from urllib.parse import unquote as urlunquote
6 ✔
45
from urllib.parse import urlparse
6 ✔
46
import zipfile
6 ✔
47

48
import toml
6 ✔
49
import build.util
6 ✔
50
from packaging.requirements import Requirement, InvalidRequirement
6 ✔
51

52
from pythonforandroid.util import rmdir, ensure_dir
6 ✔
53

54

55
def _parse_requirement_name(dependency):
6 ✔
56
    """Return the PEP 508 requirement name if parseable, else None."""
57
    try:
6 ✔
58
        return Requirement(dependency).name
6 ✔
NEW
59
    except InvalidRequirement:
×
NEW
60
        return None
×
61

62

63
def transform_dep_for_pip(dependency):
6 ✔
64
    if dependency.find("@") > 0 and (
6 ✔
65
            dependency.find("@") < dependency.find("://") or
66
            "://" not in dependency
67
            ):
68
        # WORKAROUND FOR UPSTREAM BUG:
69
        # https://github.com/pypa/pip/issues/6097
70
        # (Please REMOVE workaround once that is fixed & released upstream!)
71
        #
72
        # Basically, setup_requires() can contain a format pip won't install
73
        # from a requirements.txt (PEP 508 URLs).
74
        # To avoid this, translate to an #egg= reference:
75
        if dependency.endswith("#"):
6 ✔
76
            dependency = dependency[:-1]
6 ✔
77
        url = (dependency.partition("@")[2].strip().partition("#egg")[0] +
6 ✔
78
               "#egg=" +
79
               dependency.partition("@")[0].strip()
80
              )
81
        return url
6 ✔
82
    return dependency
6 ✔
83

84

85
def extract_metainfo_files_from_package(
6 ✔
86
        package,
87
        output_folder,
88
        debug=False
89
        ):
90
    """ Extracts metadata files from the given package to the given folder,
91
        which may be referenced in any way that is permitted in
92
        a requirements.txt file or install_requires=[] listing.
93

94
        Current supported metadata files that will be extracted:
95

96
        - pytoml.yml  (only if package wasn't obtained as wheel)
97
        - METADATA
98
    """
99

100
    if package is None:
6 !
101
        raise ValueError("package cannot be None")
×
102

103
    if not os.path.exists(output_folder) or os.path.isfile(output_folder):
6 !
104
        raise ValueError("output folder needs to be existing folder")
×
105

106
    if debug:
6 ✔
107
        print("extract_metainfo_files_from_package: extracting for " +
6 ✔
108
              "package: " + str(package))
109

110
    # A temp folder for making a package copy in case it's a local folder,
111
    # because extracting metadata might modify files
112
    # (creating sdists/wheels...)
113
    temp_folder = tempfile.mkdtemp(prefix="pythonpackage-package-copy-")
6 ✔
114
    try:
6 ✔
115
        # Package is indeed a folder! Get a temp copy to work on:
116
        if is_filesystem_path(package):
6 ✔
117
            shutil.copytree(
6 ✔
118
                parse_as_folder_reference(package),
119
                os.path.join(temp_folder, "package"),
120
                ignore=shutil.ignore_patterns(".tox")
121
            )
122
            package = os.path.join(temp_folder, "package")
6 ✔
123

124
        _extract_metainfo_files_from_package_unsafe(package, output_folder)
6 ✔
125
    finally:
126
        rmdir(temp_folder)
6 ✔
127

128

129
def _get_system_python_executable():
6 ✔
130
    """ Returns the path the system-wide python binary.
131
        (In case we're running in a virtualenv or venv)
132
    """
133
    # This function is required by get_package_as_folder() to work
134
    # inside a virtualenv, since venv creation will fail with
135
    # the virtualenv's local python binary.
136
    # (venv/virtualenv incompatibility)
137

138
    # Abort if not in virtualenv or venv:
139
    if not hasattr(sys, "real_prefix") and (
6 !
140
            not hasattr(sys, "base_prefix") or
141
            os.path.normpath(sys.base_prefix) ==
142
            os.path.normpath(sys.prefix)):
143
        return sys.executable
×
144

145
    # Extract prefix we need to look in:
146
    if hasattr(sys, "real_prefix"):
6 !
147
        search_prefix = sys.real_prefix  # virtualenv
×
148
    else:
149
        search_prefix = sys.base_prefix  # venv
6 ✔
150

151
    def python_binary_from_folder(path):
6 ✔
152
        def binary_is_usable(python_bin):
6 ✔
153
            """ Helper function to see if a given binary name refers
154
                to a usable python interpreter binary
155
            """
156

157
            # Abort if path isn't present at all or a directory:
158
            if not os.path.exists(
6 ✔
159
                os.path.join(path, python_bin)
160
            ) or os.path.isdir(os.path.join(path, python_bin)):
161
                return
6 ✔
162
            # We should check file not found anyway trying to run it,
163
            # since it might be a dead symlink:
164
            try:
6 ✔
165
                # Run it and see if version output works with no error:
166
                subprocess.check_output([
6 ✔
167
                    os.path.join(path, python_bin), "--version"
168
                ], stderr=subprocess.STDOUT)
169
                return True
6 ✔
170
            except (subprocess.CalledProcessError, FileNotFoundError):
×
171
                return False
×
172

173
        python_name = "python" + sys.version
6 ✔
174
        while (not binary_is_usable(python_name) and
6 ✔
175
               python_name.find(".") > 0):
176
            # Try less specific binary name:
177
            python_name = python_name.rpartition(".")[0]
6 ✔
178
        if binary_is_usable(python_name):
6 ✔
179
            return os.path.join(path, python_name)
6 ✔
180
        return None
6 ✔
181

182
    # Return from sys.real_prefix if present:
183
    result = python_binary_from_folder(search_prefix)
6 ✔
184
    if result is not None:
6 !
185
        return result
×
186

187
    # Check out all paths in $PATH:
188
    bad_candidates = []
6 ✔
189
    good_candidates = []
6 ✔
190
    ever_had_nonvenv_path = False
6 ✔
191
    ever_had_path_starting_with_prefix = False
6 ✔
192
    for p in os.environ.get("PATH", "").split(":"):
6 ✔
193
        # Skip if not possibly the real system python:
194
        if not os.path.normpath(p).startswith(
6 ✔
195
                os.path.normpath(search_prefix)
196
                ):
197
            continue
6 ✔
198

199
        ever_had_path_starting_with_prefix = True
6 ✔
200

201
        # First folders might be virtualenv/venv we want to avoid:
202
        if not ever_had_nonvenv_path:
6 ✔
203
            sep = os.path.sep
6 ✔
204
            if (
6 ✔
205
                ("system32" not in p.lower() and
206
                 "usr" not in p and
207
                 not p.startswith("/opt/python")) or
208
                {"home", ".tox"}.intersection(set(p.split(sep))) or
209
                "users" in p.lower()
210
            ):
211
                # Doesn't look like bog-standard system path.
212
                if (p.endswith(os.path.sep + "bin") or
5 ✔
213
                        p.endswith(os.path.sep + "bin" + os.path.sep)):
214
                    # Also ends in "bin" -> likely virtualenv/venv.
215
                    # Add as unfavorable / end of candidates:
216
                    bad_candidates.append(p)
5 ✔
217
                    continue
5 ✔
218
            ever_had_nonvenv_path = True
6 ✔
219

220
        good_candidates.append(p)
6 ✔
221

222
    # If we have a bad env with PATH not containing any reference to our
223
    # real python (travis, why would you do that to me?) then just guess
224
    # based from the search prefix location itself:
225
    if not ever_had_path_starting_with_prefix:
6 !
226
        # ... and yes we're scanning all the folders for that, it's dumb
227
        # but i'm not aware of a better way: (@JonasT)
228
        for root, dirs, files in os.walk(search_prefix, topdown=True):
×
229
            for name in dirs:
×
230
                bad_candidates.append(os.path.join(root, name))
×
231

232
    # Sort candidates by length (to prefer shorter ones):
233
    def candidate_cmp(a, b):
6 ✔
234
        return len(a) - len(b)
1 ✔
235
    good_candidates = sorted(
6 ✔
236
        good_candidates, key=functools.cmp_to_key(candidate_cmp)
237
    )
238
    bad_candidates = sorted(
6 ✔
239
        bad_candidates, key=functools.cmp_to_key(candidate_cmp)
240
    )
241

242
    # See if we can now actually find the system python:
243
    for p in good_candidates + bad_candidates:
6 !
244
        result = python_binary_from_folder(p)
6 ✔
245
        if result is not None:
6 ✔
246
            return result
6 ✔
247

248
    raise RuntimeError(
×
249
        "failed to locate system python in: {}"
250
        " - checked candidates were: {}, {}"
251
        .format(sys.real_prefix, good_candidates, bad_candidates)
252
    )
253

254

255
def get_package_as_folder(dependency):
6 ✔
256
    """ This function downloads the given package / dependency and extracts
257
        the raw contents into a folder.
258

259
        Afterwards, it returns a tuple with the type of distribution obtained,
260
        and the temporary folder it extracted to. It is the caller's
261
        responsibility to delete the returned temp folder after use.
262

263
        Examples of returned values:
264

265
        ("source", "/tmp/pythonpackage-venv-e84toiwjw")
266
        ("wheel", "/tmp/pythonpackage-venv-85u78uj")
267

268
        What the distribution type will be depends on what pip decides to
269
        download.
270
    """
271

272
    venv_parent = tempfile.mkdtemp(
6 ✔
273
        prefix="pythonpackage-venv-"
274
    )
275
    try:
6 ✔
276
        # Create a venv to install into:
277
        try:
6 ✔
278
            subprocess.check_output([
6 ✔
279
                _get_system_python_executable(), "-m", "venv",
280
                os.path.join(venv_parent, 'venv')
281
            ], cwd=venv_parent)
282
        except subprocess.CalledProcessError as e:
×
283
            output = e.output.decode('utf-8', 'replace')
×
284
            raise ValueError(
×
285
                'venv creation unexpectedly ' +
286
                'failed. error output: ' + str(output)
287
            )
288
        venv_path = os.path.join(venv_parent, "venv")
6 ✔
289

290
        # Update pip and wheel in venv for latest feature support:
291
        try:
6 ✔
292
            subprocess.check_output([
6 ✔
293
                os.path.join(venv_path, "bin", "pip"),
294
                "install", "-U", "pip", "wheel",
295
            ])
296
        except FileNotFoundError:
×
297
            raise RuntimeError(
×
298
                "venv appears to be missing pip. "
299
                "did we fail to use a proper system python??\n"
300
                "system python path detected: {}\n"
301
                "os.environ['PATH']: {}".format(
302
                    _get_system_python_executable(),
303
                    os.environ.get("PATH", "")
304
                )
305
            )
306

307
        # Create download subfolder:
308
        ensure_dir(os.path.join(venv_path, "download"))
6 ✔
309

310
        # Write a requirements.txt with our package and download:
311
        with open(os.path.join(venv_path, "requirements.txt"),
6 ✔
312
                  "w", encoding="utf-8"
313
                 ) as f:
314
            f.write(transform_dep_for_pip(dependency))
6 ✔
315
        try:
6 ✔
316
            subprocess.check_output(
6 ✔
317
                [
318
                    os.path.join(venv_path, "bin", "pip"),
319
                    "download", "--no-deps", "-r", "../requirements.txt",
320
                    "-d", os.path.join(venv_path, "download")
321
                ],
322
                stderr=subprocess.STDOUT,
323
                cwd=os.path.join(venv_path, "download")
324
            )
325
        except subprocess.CalledProcessError as e:
×
326
            raise RuntimeError("package download failed: " + str(e.output))
×
327

328
        if len(os.listdir(os.path.join(venv_path, "download"))) == 0:
6 !
329
            # No download. This can happen if the dependency has a condition
330
            # which prohibits install in our environment.
331
            # (the "package ; ... conditional ... " type of condition)
332
            return (None, None)
×
333

334
        # Get the result and make sure it's an extracted directory:
335
        result_folder_or_file = os.path.join(
6 ✔
336
            venv_path, "download",
337
            os.listdir(os.path.join(venv_path, "download"))[0]
338
        )
339
        dl_type = "source"
6 ✔
340
        if not os.path.isdir(result_folder_or_file):
6 !
341
            # Must be an archive.
342
            if result_folder_or_file.endswith((".zip", ".whl")):
6 ✔
343
                if result_folder_or_file.endswith(".whl"):
6 !
344
                    dl_type = "wheel"
6 ✔
345
                with zipfile.ZipFile(result_folder_or_file) as f:
6 ✔
346
                    f.extractall(os.path.join(venv_path,
6 ✔
347
                                              "download", "extracted"
348
                                             ))
349
                    result_folder_or_file = os.path.join(
6 ✔
350
                        venv_path, "download", "extracted"
351
                    )
352
            elif result_folder_or_file.find(".tar.") > 0:
6 !
353
                # Probably a tarball.
354
                with tarfile.open(result_folder_or_file) as f:
6 ✔
355
                    f.extractall(os.path.join(venv_path,
6 ✔
356
                                              "download", "extracted"
357
                                             ))
358
                    result_folder_or_file = os.path.join(
6 ✔
359
                        venv_path, "download", "extracted"
360
                    )
361
            else:
362
                raise RuntimeError(
×
363
                    "unknown archive or download " +
364
                    "type: " + str(result_folder_or_file)
365
                )
366

367
        # If the result is hidden away in an additional subfolder,
368
        # descend into it:
369
        while os.path.isdir(result_folder_or_file) and \
6 ✔
370
                len(os.listdir(result_folder_or_file)) == 1 and \
371
                os.path.isdir(os.path.join(
372
                    result_folder_or_file,
373
                    os.listdir(result_folder_or_file)[0]
374
                )):
375
            result_folder_or_file = os.path.join(
6 ✔
376
                result_folder_or_file,
377
                os.listdir(result_folder_or_file)[0]
378
            )
379

380
        # Copy result to new dedicated folder so we can throw away
381
        # our entire virtualenv nonsense after returning:
382
        result_path = tempfile.mkdtemp()
6 ✔
383
        rmdir(result_path)
6 ✔
384
        shutil.copytree(result_folder_or_file, result_path)
6 ✔
385
        return (dl_type, result_path)
6 ✔
386
    finally:
387
        rmdir(venv_parent)
6 ✔
388

389

390
def _extract_metainfo_files_from_package_unsafe(
6 ✔
391
        package,
392
        output_path
393
        ):
394
    # This is the unwrapped function that will
395
    # 1. make lots of stdout/stderr noise
396
    # 2. possibly modify files (if the package source is a local folder)
397
    # Use extract_metainfo_files_from_package_folder instead which avoids
398
    # these issues.
399

400
    clean_up_path = False
6 ✔
401
    path_type = "source"
6 ✔
402
    path = parse_as_folder_reference(package)
6 ✔
403
    if path is None:
6 ✔
404
        # This is not a path. Download it:
405
        (path_type, path) = get_package_as_folder(package)
6 ✔
406
        if path_type is None:
6 !
407
            # Download failed.
408
            raise ValueError(
×
409
                "cannot get info for this package, " +
410
                "pip says it has no downloads (conditional dependency?)"
411
            )
412
        clean_up_path = True
6 ✔
413

414
    try:
6 ✔
415
        metadata_path = None
6 ✔
416

417
        if path_type != "wheel":
6 ✔
418
            # Use a build helper function to fetch the metadata directly
419
            metadata = build.util.project_wheel_metadata(path)
6 ✔
420
            # And write it to a file
421
            metadata_path = os.path.join(output_path, "built_metadata")
6 ✔
422
            with open(metadata_path, 'w') as f:
6 ✔
423
                for key in metadata.keys():
6 ✔
424
                    for value in metadata.get_all(key):
6 ✔
425
                        f.write("{}: {}\n".format(key, value))
6 ✔
426
        else:
427
            # This is a wheel, so metadata should be in *.dist-info folder:
428
            metadata_path = os.path.join(
6 ✔
429
                path,
430
                [f for f in os.listdir(path) if f.endswith(".dist-info")][0],
431
                "METADATA"
432
            )
433

434
        # Store type of metadata source. Can be "wheel", "source" for source
435
        # distribution, and others get_package_as_folder() may support
436
        # in the future.
437
        with open(os.path.join(output_path, "metadata_source"), "w") as f:
6 ✔
438
            f.write(path_type)
6 ✔
439

440
        # Copy the metadata file:
441
        shutil.copyfile(metadata_path, os.path.join(output_path, "METADATA"))
6 ✔
442
    finally:
443
        if clean_up_path:
6 ✔
444
            rmdir(path)
6 ✔
445

446

447
def is_filesystem_path(dep):
6 ✔
448
    """ Convenience function around parse_as_folder_reference() to
449
        check if a dependency refers to a folder path or something remote.
450

451
        Returns True if local, False if remote.
452
    """
453
    return (parse_as_folder_reference(dep) is not None)
6 ✔
454

455

456
def parse_as_folder_reference(dep):
6 ✔
457
    """ See if a dependency reference refers to a folder path.
458
        If it does, return the folder path (which parses and
459
        resolves file:// urls in the process).
460
        If it doesn't, return None.
461
    """
462
    # Special case: pep508 urls
463
    if dep.find("@") > 0 and (
6 ✔
464
            (dep.find("@") < dep.find("/") or "/" not in dep) and
465
            (dep.find("@") < dep.find(":") or ":" not in dep)
466
            ):
467
        # This should be a 'pkgname @ https://...' style path, or
468
        # 'pkname @ /local/file/path'.
469
        return parse_as_folder_reference(dep.partition("@")[2].lstrip())
6 ✔
470

471
    # Check if this is either not an url, or a file URL:
472
    if dep.startswith(("/", "file://")) or (
6 ✔
473
            dep.find("/") > 0 and
474
            dep.find("://") < 0) or (dep in ["", "."]):
475
        if dep.startswith("file://"):
6 ✔
476
            dep = urlunquote(urlparse(dep).path)
6 ✔
477
        return dep
6 ✔
478
    return None
6 ✔
479

480

481
def _extract_info_from_package(dependency,
6 ✔
482
                               extract_type=None,
483
                               debug=False,
484
                               include_build_requirements=False
485
                               ):
486
    """ Internal function to extract metainfo from a package.
487
        Currently supported info types:
488

489
        - name
490
        - dependencies  (a list of dependencies)
491
    """
492
    if debug:
6 ✔
493
        print("_extract_info_from_package called with "
6 ✔
494
              "extract_type={} include_build_requirements={}".format(
495
                  extract_type, include_build_requirements,
496
              ))
497
    output_folder = tempfile.mkdtemp(prefix="pythonpackage-metafolder-")
6 ✔
498
    try:
6 ✔
499
        extract_metainfo_files_from_package(
6 ✔
500
            dependency, output_folder, debug=debug
501
        )
502

503
        # Extract the type of data source we used to get the metadata:
504
        with open(os.path.join(output_folder,
6 ✔
505
                               "metadata_source"), "r") as f:
506
            metadata_source_type = f.read().strip()
6 ✔
507

508
        # Extract main METADATA file:
509
        with open(os.path.join(output_folder, "METADATA"),
6 ✔
510
                  "r", encoding="utf-8"
511
                 ) as f:
512
            # Get metadata and cut away description (is after 2 linebreaks)
513
            metadata_entries = f.read().partition("\n\n")[0].splitlines()
6 ✔
514

515
        if extract_type == "name":
6 ✔
516
            name = None
6 ✔
517
            for meta_entry in metadata_entries:
6 !
518
                if meta_entry.lower().startswith("name:"):
6 ✔
519
                    return meta_entry.partition(":")[2].strip()
6 ✔
520
            if name is None:
×
521
                raise ValueError("failed to obtain package name")
×
522
            return name
×
523
        elif extract_type == "dependencies":
6 !
524
            # First, make sure we don't attempt to return build requirements
525
            # for wheels since they usually come without pyproject.toml
526
            # and we haven't implemented another way to get them:
527
            if include_build_requirements and \
6 ✔
528
                    metadata_source_type == "wheel":
529
                if debug:
6 ✔
530
                    print("_extract_info_from_package: was called "
6 ✔
531
                          "with include_build_requirements=True on "
532
                          "package obtained as wheel, raising error...")
533
                raise NotImplementedError(
534
                    "fetching build requirements for "
535
                    "wheels is not implemented"
536
                )
537

538
            # Get build requirements from pyproject.toml if requested:
539
            requirements = []
6 ✔
540
            pyproject_toml_path = os.path.join(output_folder, 'pyproject.toml')
6 ✔
541
            if os.path.exists(pyproject_toml_path) and include_build_requirements:
6 !
542
                # Read build system from pyproject.toml file: (PEP518)
543
                with open(pyproject_toml_path) as f:
×
544
                    build_sys = toml.load(f)['build-system']
×
545
                    if "requires" in build_sys:
×
546
                        requirements += build_sys["requires"]
×
547
            elif include_build_requirements:
6 ✔
548
                # For legacy packages with no pyproject.toml, we have to
549
                # add setuptools as default build system.
550
                requirements.append("setuptools")
6 ✔
551

552
            # Add requirements from metadata:
553
            requirements += [
6 ✔
554
                entry.rpartition("Requires-Dist:")[2].strip()
555
                for entry in metadata_entries
556
                if entry.startswith("Requires-Dist")
557
            ]
558

559
            return list(set(requirements))  # remove duplicates
6 ✔
560
    finally:
561
        rmdir(output_folder)
6 ✔
562

563

564
package_name_cache = dict()
6 ✔
565

566

567
def get_package_name(dependency,
6 ✔
568
                     use_cache=True):
569
    try:
6 ✔
570
        value = package_name_cache[dependency]
6 ✔
571
        if value[0] + 600.0 > time.monotonic() and use_cache:
6 !
572
            return value[1]
6 ✔
573
    except KeyError:
6 ✔
574
        pass
6 ✔
575
    result = _extract_info_from_package(dependency, extract_type="name")
6 ✔
576
    package_name_cache[dependency] = (time.monotonic(), result)
6 ✔
577
    return result
6 ✔
578

579

580
def get_package_dependencies(package,
6 ✔
581
                             recursive=False,
582
                             verbose=False,
583
                             include_build_requirements=False):
584
    """ Obtain the dependencies from a package. Please note this
585
        function is possibly SLOW, especially if you enable
586
        the recursive mode.
587
    """
588
    packages_processed = set()
6 ✔
589
    package_queue = [package]
6 ✔
590
    reqs = set()
6 ✔
591
    reqs_as_names = set()
6 ✔
592
    while len(package_queue) > 0:
6 ✔
593
        current_queue = package_queue
6 ✔
594
        package_queue = []
6 ✔
595
        for package_dep in current_queue:
6 ✔
596
            new_reqs = set()
6 ✔
597
            if verbose:
6 ✔
598
                print("get_package_dependencies: resolving dependency "
6 ✔
599
                      f"to package name: {package_dep}")
600
            package = get_package_name(package_dep)
6 ✔
601
            if package.lower() in packages_processed:
6 !
602
                continue
×
603
            if verbose:
6 ✔
604
                print("get_package_dependencies: "
6 ✔
605
                      "processing package: {}".format(package))
606
                print("get_package_dependencies: "
6 ✔
607
                      "Packages seen so far: {}".format(
608
                          packages_processed
609
                      ))
610
            packages_processed.add(package.lower())
6 ✔
611

612
            # Use our regular folder processing to examine:
613
            new_reqs = new_reqs.union(_extract_info_from_package(
6 ✔
614
                package_dep, extract_type="dependencies",
615
                debug=verbose,
616
                include_build_requirements=include_build_requirements,
617
            ))
618

619
            # Process new requirements:
620
            if verbose:
6 ✔
621
                print('get_package_dependencies: collected '
6 ✔
622
                      "deps of '{}': {}".format(
623
                          package_dep, str(new_reqs),
624
                      ))
625
            for new_req in new_reqs:
6 ✔
626
                try:
6 ✔
627
                    req_name = get_package_name(new_req)
6 ✔
628
                except RuntimeError as e:
6 !
629
                    req_name = _parse_requirement_name(new_req)
6 ✔
630
                    if req_name is None:
6 !
NEW
631
                        raise
×
632
                    if verbose:
6 !
633
                        print(
6 ✔
634
                            f"get_package_dependencies: failed to download "
635
                            f"'{new_req}' ({e}); using parsed name '{req_name}'"
636
                        )
637
                    if req_name.lower() not in reqs_as_names:
6 !
638
                        reqs.add(new_req)
6 ✔
639
                        reqs_as_names.add(req_name.lower())
6 ✔
640
                    continue
6 ✔
641
                except ValueError as e:
×
642
                    if new_req.find(";") >= 0:
×
643
                        # Conditional dep where condition isn't met?
644
                        # --> ignore it
645
                        continue
×
646
                    if verbose:
×
647
                        print("get_package_dependencies: " +
×
648
                              "unexpected failure to get name " +
649
                              "of '" + str(new_req) + "': " +
650
                              str(e))
651
                    raise RuntimeError(
×
652
                        "failed to get " +
653
                        "name of dependency: " + str(e)
654
                    )
655
                if req_name.lower() in reqs_as_names:
6 !
656
                    continue
×
657
                if req_name.lower() not in packages_processed:
6 !
658
                    package_queue.append(new_req)
6 ✔
659
                reqs.add(new_req)
6 ✔
660
                reqs_as_names.add(req_name.lower())
6 ✔
661

662
            # Bail out here if we're not scanning recursively:
663
            if not recursive:
6 ✔
664
                package_queue[:] = []  # wipe queue
6 ✔
665
                break
6 ✔
666
    if verbose:
6 ✔
667
        print("get_package_dependencies: returning result: {}".format(reqs))
6 ✔
668
    return reqs
6 ✔
669

670

671
def get_dep_names_of_package(
6 ✔
672
        package,
673
        keep_version_pins=False,
674
        recursive=False,
675
        verbose=False,
676
        include_build_requirements=False
677
        ):
678
    """ Gets the dependencies from the package in the given folder,
679
        then attempts to deduce the actual package name resulting
680
        from each dependency line, stripping away everything else.
681
    """
682

683
    # First, obtain the dependencies:
684
    dependencies = get_package_dependencies(
6 ✔
685
        package, recursive=recursive, verbose=verbose,
686
        include_build_requirements=include_build_requirements,
687
    )
688
    if verbose:
6 ✔
689
        print("get_dep_names_of_package_folder: " +
6 ✔
690
              "processing dependency list to names: " +
691
              str(dependencies))
692

693
    # Transform dependencies to their stripped down names:
694
    # (they can still have version pins/restrictions, conditionals, ...)
695
    dependency_names = set()
6 ✔
696
    for dep in dependencies:
6 ✔
697
        # If we are supposed to keep exact version pins, extract first:
698
        pin_to_append = ""
6 ✔
699
        if keep_version_pins and "(==" in dep and dep.endswith(")"):
6 !
700
            # This is a dependency of the format: 'pkg (==1.0)'
701
            pin_to_append = "==" + dep.rpartition("==")[2][:-1]
×
702
        elif keep_version_pins and "==" in dep and not dep.endswith(")"):
6 ✔
703
            # This is a dependency of the format: 'pkg==1.0'
704
            pin_to_append = "==" + dep.rpartition("==")[2]
6 ✔
705
        # Now get true (and e.g. case-corrected) dependency name:
706
        try:
6 ✔
707
            dep_name = get_package_name(dep)
6 ✔
708
        except RuntimeError:
6 ✔
709
            dep_name = _parse_requirement_name(dep)
6 ✔
710
            if dep_name is None:
6 !
NEW
711
                raise
×
712
        dep_name += pin_to_append
6 ✔
713
        dependency_names.add(dep_name)
6 ✔
714
    return dependency_names
6 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc