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

pantsbuild / pants / 21772907793

07 Feb 2026 02:50AM UTC coverage: 80.284% (+0.001%) from 80.283%
21772907793

push

github

web-flow
Remove a superfluous field from ParsePythonDependenciesRequest. (#23082)

Nothing was using that field.

Also remove a now-superfluous cardinality check
(the caller checks the cardinality of the return value if
it wishes).

78543 of 97832 relevant lines covered (80.28%)

3.36 hits per line

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

66.67
/src/python/pants/backend/python/dependency_inference/parse_python_dependencies.py
1
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
2
# Licensed under the Apache License, Version 2.0 (see LICENSE).
3
from __future__ import annotations
12✔
4

5
import logging
12✔
6
import os
12✔
7
from collections.abc import Iterable
12✔
8
from dataclasses import dataclass
12✔
9

10
from pants.backend.python.dependency_inference.subsystem import PythonInferSubsystem
12✔
11
from pants.core.util_rules.source_files import SourceFiles
12✔
12
from pants.core.util_rules.stripped_source_files import strip_source_roots
12✔
13
from pants.engine.collection import DeduplicatedCollection
12✔
14
from pants.engine.fs import CreateDigest, Digest, FileContent
12✔
15
from pants.engine.internals.native_engine import NativeDependenciesRequest
12✔
16
from pants.engine.intrinsics import create_digest, parse_python_deps
12✔
17
from pants.engine.rules import collect_rules, rule
12✔
18
from pants.util.frozendict import FrozenDict
12✔
19
from pants.util.logging import LogLevel
12✔
20
from pants.util.resources import read_resource
12✔
21

22
logger = logging.getLogger(__name__)
12✔
23

24

25
@dataclass(frozen=True, order=True)
12✔
26
class ParsedPythonImportInfo:
12✔
27
    lineno: int
12✔
28
    # An import is considered "weak" if we're unsure if a dependency will exist between the parsed
29
    # file and the parsed import.
30
    # Examples of "weak" imports include string imports (if enabled) or those inside a try block
31
    # which has a handler catching ImportError.
32
    weak: bool
12✔
33

34

35
class ParsedPythonImports(FrozenDict[str, ParsedPythonImportInfo]):
12✔
36
    """All the discovered imports from a Python source file mapped to the relevant info."""
37

38

39
class ParsedPythonAssetPaths(DeduplicatedCollection[str]):
12✔
40
    """All the discovered possible assets from a Python source file."""
41

42
    # N.B. Don't set `sort_input`, as the input is already sorted
43

44

45
# TODO: Use the Native* eqivalents of these classes directly? Would require
46
#  conversion to the component classes in Rust code. Might require passing
47
#  the PythonInferSubsystem settings through to Rust and acting on them there.
48

49

50
@dataclass(frozen=True)
12✔
51
class PythonFileDependencies:
12✔
52
    imports: ParsedPythonImports
12✔
53
    assets: ParsedPythonAssetPaths
12✔
54

55

56
@dataclass(frozen=True)
12✔
57
class PythonFilesDependencies:
12✔
58
    path_to_deps: FrozenDict[str, PythonFileDependencies]
12✔
59

60

61
@dataclass(frozen=True)
12✔
62
class ParsePythonDependenciesRequest:
12✔
63
    source: SourceFiles
12✔
64

65

66
@dataclass(frozen=True)
12✔
67
class PythonDependencyVisitor:
12✔
68
    """Wraps a subclass of DependencyVisitorBase."""
69

70
    digest: Digest  # The file contents for the visitor
12✔
71
    classname: str  # The full classname, e.g., _my_custom_dep_parser.MyCustomVisitor
12✔
72
    env: FrozenDict[str, str]  # Set these env vars when invoking the visitor
12✔
73

74

75
@dataclass(frozen=True)
12✔
76
class ParserScript:
12✔
77
    digest: Digest
12✔
78
    env: FrozenDict[str, str]
12✔
79

80

81
_scripts_package = "pants.backend.python.dependency_inference.scripts"
12✔
82

83

84
async def get_scripts_digest(scripts_package: str, filenames: Iterable[str]) -> Digest:
12✔
85
    scripts = [read_resource(scripts_package, filename) for filename in filenames]
×
86
    assert all(script is not None for script in scripts)
×
87
    path_prefix = scripts_package.replace(".", os.path.sep)
×
88
    contents = [
×
89
        FileContent(os.path.join(path_prefix, relpath), script)
90
        for relpath, script in zip(filenames, scripts)
91
    ]
92

93
    # Python 2 requires all the intermediate __init__.py to exist in the sandbox.
94
    package = scripts_package
×
95
    while package:
×
96
        contents.append(
×
97
            FileContent(
98
                os.path.join(package.replace(".", os.path.sep), "__init__.py"),
99
                read_resource(package, "__init__.py"),
100
            )
101
        )
102
        package = package.rpartition(".")[0]
×
103

104
    digest = await create_digest(CreateDigest(contents))
×
105
    return digest
×
106

107

108
@rule(level=LogLevel.DEBUG)
12✔
109
async def parse_python_dependencies(
12✔
110
    request: ParsePythonDependenciesRequest,
111
    python_infer_subsystem: PythonInferSubsystem,
112
) -> PythonFilesDependencies:
113
    stripped_sources = await strip_source_roots(request.source)
×
114
    native_results = await parse_python_deps(
×
115
        NativeDependenciesRequest(stripped_sources.snapshot.digest)
116
    )
117

118
    path_to_deps = {}
×
119
    for path, native_result in native_results.path_to_deps.items():
×
120
        imports = dict(native_result.imports)
×
121
        assets = set()
×
122

123
        if python_infer_subsystem.string_imports or python_infer_subsystem.assets:
×
124
            for string, line in native_result.string_candidates.items():
×
125
                if (
×
126
                    python_infer_subsystem.string_imports
127
                    and string.count(".") >= python_infer_subsystem.string_imports_min_dots
128
                    and all(part.isidentifier() for part in string.split("."))
129
                ):
130
                    imports.setdefault(string, (line, True))
×
131
                if (
×
132
                    python_infer_subsystem.assets
133
                    and string.count("/") >= python_infer_subsystem.assets_min_slashes
134
                ):
135
                    assets.add(string)
×
136

137
        path_to_deps[path] = PythonFileDependencies(
×
138
            ParsedPythonImports(
139
                (key, ParsedPythonImportInfo(*value)) for key, value in imports.items()
140
            ),
141
            ParsedPythonAssetPaths(sorted(assets)),
142
        )
143
    return PythonFilesDependencies(FrozenDict(path_to_deps))
×
144

145

146
def rules():
12✔
147
    return [
12✔
148
        *collect_rules(),
149
    ]
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc