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

pantsbuild / pants / 21920406866

11 Feb 2026 07:44PM UTC coverage: 80.355% (+0.005%) from 80.35%
21920406866

push

github

web-flow
Support for a `# pants: infer-dep(...)` pragma. (#23092)

Allows source files to declare explicit dependencies on other
files without needing a BUILD file.

Currently this is *not* actually used (or documented). The format
of the content of the parents needs to be defined (paths? 
target addresses? JSON?).

This just handles detection and plumbing.

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

1 existing line in 1 file now uncovered.

78778 of 98037 relevant lines covered (80.36%)

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
# Map from argument of `pants: infer-dep(...)` to line number at which it appears.
46
class ExplicitPythonDependencies(FrozenDict[str, int]):
12✔
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)
12✔
56
class PythonFileDependencies:
12✔
57
    imports: ParsedPythonImports
12✔
58
    assets: ParsedPythonAssetPaths
12✔
59
    explicit_dependencies: ExplicitPythonDependencies
12✔
60

61

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

66

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

71

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

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

80

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

86

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

89

90
async def get_scripts_digest(scripts_package: str, filenames: Iterable[str]) -> Digest:
12✔
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)
12✔
115
async def parse_python_dependencies(
12✔
116
    request: ParsePythonDependenciesRequest,
117
    python_infer_subsystem: PythonInferSubsystem,
118
) -> PythonFilesDependencies:
119
    stripped_sources = await strip_source_roots(request.source)
×
120
    native_results = await parse_python_deps(
×
121
        NativeDependenciesRequest(stripped_sources.snapshot.digest)
122
    )
123

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

129
        if python_infer_subsystem.string_imports or python_infer_subsystem.assets:
×
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

NEW
143
        explicit_deps = dict(native_result.explicit_dependencies)
×
144

UNCOV
145
        path_to_deps[path] = PythonFileDependencies(
×
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))
×
153

154

155
def rules():
12✔
156
    return [
12✔
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