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

pantsbuild / pants / 22740642519

05 Mar 2026 11:00PM UTC coverage: 52.677% (-40.3%) from 92.931%
22740642519

Pull #23157

github

web-flow
Merge 2aa18e6d4 into f0030f5e7
Pull Request #23157: [pants ng] Partition source files by config.

31678 of 60136 relevant lines covered (52.68%)

0.53 hits per line

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

80.0
/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
1✔
4

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

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

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

24

25
@dataclass(frozen=True, order=True)
1✔
26
class ParsedPythonImportInfo:
1✔
27
    lineno: int
1✔
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
1✔
33

34

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

38

39
class ParsedPythonAssetPaths(DeduplicatedCollection[str]):
1✔
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
# Map from argument of `pants: infer-dep(...)` to line number at which it appears.
46
class ExplicitPythonDependencies(FrozenDict[str, int]):
1✔
47
    """Dependencies provided via the # pants: infer-dep() pragma."""
48

49

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

54

55
@dataclass(frozen=True)
1✔
56
class PythonFileDependencies:
1✔
57
    imports: ParsedPythonImports
1✔
58
    assets: ParsedPythonAssetPaths
1✔
59
    explicit_dependencies: ExplicitPythonDependencies
1✔
60

61

62
@dataclass(frozen=True)
1✔
63
class PythonFilesDependencies:
1✔
64
    path_to_deps: FrozenDict[str, PythonFileDependencies]
1✔
65

66

67
@dataclass(frozen=True)
1✔
68
class ParsePythonDependenciesRequest:
1✔
69
    source: SourceFiles
1✔
70

71

72
@dataclass(frozen=True)
1✔
73
class PythonDependencyVisitor:
1✔
74
    """Wraps a subclass of DependencyVisitorBase."""
75

76
    digest: Digest  # The file contents for the visitor
1✔
77
    classname: str  # The full classname, e.g., _my_custom_dep_parser.MyCustomVisitor
1✔
78
    env: FrozenDict[str, str]  # Set these env vars when invoking the visitor
1✔
79

80

81
@dataclass(frozen=True)
1✔
82
class ParserScript:
1✔
83
    digest: Digest
1✔
84
    env: FrozenDict[str, str]
1✔
85

86

87
_scripts_package = "pants.backend.python.dependency_inference.scripts"
1✔
88

89

90
async def get_scripts_digest(scripts_package: str, filenames: Iterable[str]) -> Digest:
1✔
91
    scripts = [read_resource(scripts_package, filename) for filename in filenames]
×
92
    assert all(script is not None for script in scripts)
×
93
    path_prefix = scripts_package.replace(".", os.path.sep)
×
94
    contents = [
×
95
        FileContent(os.path.join(path_prefix, relpath), script)
96
        for relpath, script in zip(filenames, scripts)
97
    ]
98

99
    # Python 2 requires all the intermediate __init__.py to exist in the sandbox.
100
    package = scripts_package
×
101
    while package:
×
102
        contents.append(
×
103
            FileContent(
104
                os.path.join(package.replace(".", os.path.sep), "__init__.py"),
105
                read_resource(package, "__init__.py"),
106
            )
107
        )
108
        package = package.rpartition(".")[0]
×
109

110
    digest = await create_digest(CreateDigest(contents))
×
111
    return digest
×
112

113

114
@rule(level=LogLevel.DEBUG)
1✔
115
async def parse_python_dependencies(
1✔
116
    request: ParsePythonDependenciesRequest,
117
    python_infer_subsystem: PythonInferSubsystem,
118
) -> PythonFilesDependencies:
119
    stripped_sources = await strip_source_roots(request.source)
1✔
120
    native_results = await parse_python_deps(
1✔
121
        NativeDependenciesRequest(stripped_sources.snapshot.digest)
122
    )
123

124
    path_to_deps = {}
1✔
125
    for path, native_result in native_results.path_to_deps.items():
1✔
126
        imports = dict(native_result.imports)
1✔
127
        assets = set()
1✔
128

129
        if python_infer_subsystem.string_imports or python_infer_subsystem.assets:
1✔
130
            for string, line in native_result.string_candidates.items():
×
131
                if (
×
132
                    python_infer_subsystem.string_imports
133
                    and string.count(".") >= python_infer_subsystem.string_imports_min_dots
134
                    and all(part.isidentifier() for part in string.split("."))
135
                ):
136
                    imports.setdefault(string, (line, True))
×
137
                if (
×
138
                    python_infer_subsystem.assets
139
                    and string.count("/") >= python_infer_subsystem.assets_min_slashes
140
                ):
141
                    assets.add(string)
×
142

143
        explicit_deps = dict(native_result.explicit_dependencies)
1✔
144

145
        path_to_deps[path] = PythonFileDependencies(
1✔
146
            ParsedPythonImports(
147
                (key, ParsedPythonImportInfo(*value)) for key, value in imports.items()
148
            ),
149
            ParsedPythonAssetPaths(sorted(assets)),
150
            ExplicitPythonDependencies(FrozenDict(explicit_deps)),
151
        )
152
    return PythonFilesDependencies(FrozenDict(path_to_deps))
1✔
153

154

155
def rules():
1✔
156
    return [
1✔
157
        *collect_rules(),
158
    ]
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