Skip to content

Commit 1d1366a

Browse files
authored
A helper method for indexing paths by source root (#23085)
1 parent fafbb9c commit 1d1366a

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

src/python/pants/source/source_root.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import itertools
77
import logging
88
import os
9+
from collections import defaultdict
910
from collections.abc import Iterable
1011
from dataclasses import dataclass
1112
from pathlib import PurePath
@@ -173,7 +174,7 @@ def __post_init__(self) -> None:
173174

174175
@classmethod
175176
def for_files(cls, file_paths: Iterable[str]) -> SourceRootsRequest:
176-
"""Create a request for the source root for the given file."""
177+
"""Create a request for the source root for the given files."""
177178
return cls({PurePath(file_path) for file_path in file_paths}, ())
178179

179180

@@ -217,6 +218,12 @@ def debug_hint(self) -> str:
217218
class SourceRootsResult:
218219
path_to_root: FrozenDict[PurePath, SourceRoot]
219220

221+
def root_to_paths(self) -> FrozenDict[SourceRoot, tuple[PurePath, ...]]:
222+
res = defaultdict(list)
223+
for path, root in self.path_to_root.items():
224+
res[root].append(path)
225+
return FrozenDict((k, tuple(sorted(v))) for k, v in res.items())
226+
220227

221228
@dataclass(frozen=True)
222229
class OptionalSourceRootsResult:

src/python/pants/source/source_root_test.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from pants.source.source_root import rules as source_root_rules
2323
from pants.testutil.option_util import create_subsystem
2424
from pants.testutil.rule_runner import RuleRunner, run_rule_with_mocks
25+
from pants.util.frozendict import FrozenDict
2526

2627

2728
def _find_root(
@@ -287,3 +288,26 @@ def test_source_roots_request() -> None:
287288
PurePath("src/python/foo"): SourceRoot("src/python"),
288289
PurePath("src/python/baz/qux"): SourceRoot("src/python"),
289290
} == dict(res.path_to_root)
291+
292+
293+
def test_root_to_paths() -> None:
294+
res = SourceRootsResult(
295+
FrozenDict(
296+
{
297+
PurePath("src/python/foo/bar.py"): SourceRoot("src/python"),
298+
PurePath("tests/python/foo/bar_test.py"): SourceRoot("tests/python"),
299+
PurePath("src/python/foo"): SourceRoot("src/python"),
300+
PurePath("src/python/baz/qux"): SourceRoot("src/python"),
301+
}
302+
)
303+
)
304+
assert res.root_to_paths() == FrozenDict(
305+
{
306+
SourceRoot("src/python"): (
307+
PurePath("src/python/baz/qux"),
308+
PurePath("src/python/foo"),
309+
PurePath("src/python/foo/bar.py"),
310+
),
311+
SourceRoot("tests/python"): (PurePath("tests/python/foo/bar_test.py"),),
312+
}
313+
)

0 commit comments

Comments
 (0)