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

pantsbuild / pants / 21538902371

31 Jan 2026 04:39AM UTC coverage: 80.332% (+0.001%) from 80.331%
21538902371

Pull #23060

github

web-flow
Merge b2da87474 into 89e424102
Pull Request #23060: Simplify API of Python dep inference.

6 of 8 new or added lines in 3 files covered. (75.0%)

7 existing lines in 3 files now uncovered.

78561 of 97796 relevant lines covered (80.33%)

3.36 hits per line

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

68.12
/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.backend.python.util_rules.interpreter_constraints import InterpreterConstraints
12✔
12
from pants.core.util_rules.source_files import SourceFiles
12✔
13
from pants.core.util_rules.stripped_source_files import strip_source_roots
12✔
14
from pants.engine.collection import DeduplicatedCollection
12✔
15
from pants.engine.fs import CreateDigest, Digest, FileContent
12✔
16
from pants.engine.internals.native_engine import NativeDependenciesRequest
12✔
17
from pants.engine.intrinsics import create_digest, parse_python_deps
12✔
18
from pants.engine.rules import collect_rules, rule
12✔
19
from pants.util.frozendict import FrozenDict
12✔
20
from pants.util.logging import LogLevel
12✔
21
from pants.util.resources import read_resource
12✔
22

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

25

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

35

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

39

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

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

45

46
@dataclass(frozen=True)
12✔
47
class ParsedPythonDependencies:
12✔
48
    imports: ParsedPythonImports
12✔
49
    assets: ParsedPythonAssetPaths
12✔
50

51

52
@dataclass(frozen=True)
12✔
53
class ParsePythonDependenciesRequest:
12✔
54
    source: SourceFiles
12✔
55
    interpreter_constraints: InterpreterConstraints
12✔
56

57

58
@dataclass(frozen=True)
12✔
59
class PythonDependencyVisitor:
12✔
60
    """Wraps a subclass of DependencyVisitorBase."""
61

62
    digest: Digest  # The file contents for the visitor
12✔
63
    classname: str  # The full classname, e.g., _my_custom_dep_parser.MyCustomVisitor
12✔
64
    env: FrozenDict[str, str]  # Set these env vars when invoking the visitor
12✔
65

66

67
@dataclass(frozen=True)
12✔
68
class ParserScript:
12✔
69
    digest: Digest
12✔
70
    env: FrozenDict[str, str]
12✔
71

72

73
_scripts_package = "pants.backend.python.dependency_inference.scripts"
12✔
74

75

76
async def get_scripts_digest(scripts_package: str, filenames: Iterable[str]) -> Digest:
12✔
77
    scripts = [read_resource(scripts_package, filename) for filename in filenames]
×
78
    assert all(script is not None for script in scripts)
×
79
    path_prefix = scripts_package.replace(".", os.path.sep)
×
80
    contents = [
×
81
        FileContent(os.path.join(path_prefix, relpath), script)
82
        for relpath, script in zip(filenames, scripts)
83
    ]
84

85
    # Python 2 requires all the intermediate __init__.py to exist in the sandbox.
86
    package = scripts_package
×
87
    while package:
×
88
        contents.append(
×
89
            FileContent(
90
                os.path.join(package.replace(".", os.path.sep), "__init__.py"),
91
                read_resource(package, "__init__.py"),
92
            )
93
        )
94
        package = package.rpartition(".")[0]
×
95

96
    digest = await create_digest(CreateDigest(contents))
×
97
    return digest
×
98

99

100
@rule(level=LogLevel.DEBUG)
12✔
101
async def parse_python_dependencies(
12✔
102
    request: ParsePythonDependenciesRequest,
103
    python_infer_subsystem: PythonInferSubsystem,
104
) -> ParsedPythonDependencies:
NEW
105
    stripped_sources = await strip_source_roots(request.source)
×
106
    # We operate on PythonSourceField, which should be one file.
107
    assert len(stripped_sources.snapshot.files) == 1
×
108

109
    native_result = await parse_python_deps(
×
110
        NativeDependenciesRequest(stripped_sources.snapshot.digest)
111
    )
112
    imports = dict(native_result.imports)
×
113
    assets = set()
×
114

115
    if python_infer_subsystem.string_imports or python_infer_subsystem.assets:
×
116
        for string, line in native_result.string_candidates.items():
×
117
            if (
×
118
                python_infer_subsystem.string_imports
119
                and string.count(".") >= python_infer_subsystem.string_imports_min_dots
120
                and all(part.isidentifier() for part in string.split("."))
121
            ):
122
                imports.setdefault(string, (line, True))
×
123
            if (
×
124
                python_infer_subsystem.assets
125
                and string.count("/") >= python_infer_subsystem.assets_min_slashes
126
            ):
127
                assets.add(string)
×
128

129
    return ParsedPythonDependencies(
×
130
        ParsedPythonImports(
131
            (key, ParsedPythonImportInfo(*value)) for key, value in imports.items()
132
        ),
133
        ParsedPythonAssetPaths(sorted(assets)),
134
    )
135

136

137
def rules():
12✔
138
    return [
12✔
139
        *collect_rules(),
140
    ]
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