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

pantsbuild / pants / 21883587496

10 Feb 2026 09:45PM UTC coverage: 80.342% (-0.008%) from 80.35%
21883587496

Pull #23092

github

web-flow
Merge c4a3852cf into 9a67b81d3
Pull Request #23092: Support for a `# pants: infer-dep(...)` pragma.

9 of 11 new or added lines in 3 files covered. (81.82%)

9 existing lines in 2 files now uncovered.

78765 of 98037 relevant lines covered (80.34%)

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
    # N.B. Don't set `sort_input`, as the input is already sorted
42

43
class ExplicitPythonDependencies(FrozenDict[str, int]):
12✔
44
    """Dependencies provided via the # pants: infer-dep() pragma (mapped to lineno)."""
45

46

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

51

52
@dataclass(frozen=True)
12✔
53
class PythonFileDependencies:
12✔
54
    imports: ParsedPythonImports
12✔
55
    assets: ParsedPythonAssetPaths
12✔
56
    explicit_dependencies: ExplicitPythonDependencies
12✔
57

58

59
@dataclass(frozen=True)
12✔
60
class PythonFilesDependencies:
12✔
61
    path_to_deps: FrozenDict[str, PythonFileDependencies]
12✔
62

63

64
@dataclass(frozen=True)
12✔
65
class ParsePythonDependenciesRequest:
12✔
66
    source: SourceFiles
12✔
67

68

69
@dataclass(frozen=True)
12✔
70
class PythonDependencyVisitor:
12✔
71
    """Wraps a subclass of DependencyVisitorBase."""
72

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

77

78
@dataclass(frozen=True)
12✔
79
class ParserScript:
12✔
80
    digest: Digest
12✔
81
    env: FrozenDict[str, str]
12✔
82

83

84
_scripts_package = "pants.backend.python.dependency_inference.scripts"
12✔
85

86

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

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

107
    digest = await create_digest(CreateDigest(contents))
×
108
    return digest
×
109

110

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

121
    path_to_deps = {}
×
122
    for path, native_result in native_results.path_to_deps.items():
×
123
        imports = dict(native_result.imports)
×
124
        assets = set()
×
125

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

NEW
140
        explicit_deps = dict(native_result.explicit_dependencies)
×
141

UNCOV
142
        path_to_deps[path] = PythonFileDependencies(
×
143
            ParsedPythonImports(
144
                (key, ParsedPythonImportInfo(*value)) for key, value in imports.items()
145
            ),
146
            ParsedPythonAssetPaths(sorted(assets)),
147
            ExplicitPythonDependencies(FrozenDict(explicit_deps))
148
        )
149
    return PythonFilesDependencies(FrozenDict(path_to_deps))
×
150

151

152
def rules():
12✔
153
    return [
12✔
154
        *collect_rules(),
155
    ]
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