Skip to content

Commit

Permalink
perf: use p1.relative(p2) when it makes sense (#2369)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Nov 1, 2024
1 parent 26dcf13 commit 50299ab
Show file tree
Hide file tree
Showing 6 changed files with 12 additions and 30 deletions.
6 changes: 2 additions & 4 deletions src/ape/managers/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@


def _path_to_source_id(path: Path, root_path: Path) -> str:
return f"{get_relative_path(path.absolute(), root_path.absolute())}"
return f"{path.relative_to(root_path)}"


class SourceManager(BaseManager):
Expand Down Expand Up @@ -495,9 +495,7 @@ def _compile(
):
self._compile_contracts(needs_compile)

src_ids = [
f"{get_relative_path(Path(p).absolute(), self.project.path)}" for p in path_ls_final
]
src_ids = [f"{Path(p).relative_to(self.project.path)}" for p in path_ls_final]
for contract_type in (self.project.manifest.contract_types or {}).values():
if contract_type.source_id and contract_type.source_id in src_ids:
yield ContractContainer(contract_type)
Expand Down
4 changes: 2 additions & 2 deletions src/ape/pytest/coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from ape.logging import logger
from ape.utils.basemodel import ManagerAccessMixin
from ape.utils.misc import get_current_timestamp_ms
from ape.utils.os import get_full_extension, get_relative_path
from ape.utils.os import get_full_extension
from ape.utils.trace import parse_coverage_tables

if TYPE_CHECKING:
Expand Down Expand Up @@ -92,7 +92,7 @@ def cover(
self, src_path: Path, pcs: Iterable[int], inc_fn_hits: bool = True
) -> tuple[set[int], list[str]]:
if hasattr(self.project, "path"):
source_id = str(get_relative_path(src_path.absolute(), self.project.path))
source_id = f"{src_path.relative_to(self.project.path)}"
else:
source_id = str(src_path)

Expand Down
12 changes: 6 additions & 6 deletions src/ape/utils/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ def get_relative_path(target: Path, anchor: Path) -> Path:
Compute the relative path of ``target`` relative to ``anchor``,
which may or may not share a common ancestor.
**NOTE**: Both paths must be absolute.
**NOTE ON PERFORMANCE**: Both paths must be absolute to
use this method. If you know both methods are absolute,
this method is a performance boost. If you have to first
call `.absolute()` on the paths, use
`target.relative_to(anchor)` instead; as it will be
faster in that case.
Args:
target (pathlib.Path): The path we are interested in.
Expand All @@ -43,11 +48,6 @@ def get_relative_path(target: Path, anchor: Path) -> Path:
Returns:
pathlib.Path: The new path to the target path from the anchor path.
"""
if not target.is_absolute():
raise ValueError("'target' must be an absolute path.")
if not anchor.is_absolute():
raise ValueError("'anchor' must be an absolute path.")

# Calculate common prefix length
common_parts = 0
for target_part, anchor_part in zip(target.parts, anchor.parts):
Expand Down
3 changes: 1 addition & 2 deletions src/ape_pm/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from ape.api.compiler import CompilerAPI
from ape.exceptions import CompilerError, ContractLogicError
from ape.logging import logger
from ape.utils.os import get_relative_path

if TYPE_CHECKING:
from ape.managers.project import ProjectManager
Expand Down Expand Up @@ -41,7 +40,7 @@ def compile(
) -> Iterator[ContractType]:
project = project or self.local_project
source_ids = {
p: f"{get_relative_path(p, project.path.absolute())}" if p.is_absolute() else str(p)
p: f"{p.relative_to(project.path)}" if p.is_absolute() else str(p)
for p in contract_filepaths
}
logger.info(f"Compiling {', '.join(source_ids.values())}.")
Expand Down
2 changes: 1 addition & 1 deletion tests/functional/test_compilers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def test_compile(compilers, project_with_contract, factory):
Testing both stringified paths and path-object paths.
"""
path = next(iter(project_with_contract.sources.paths))
actual = compilers.compile((factory(path),))
actual = compilers.compile((factory(path),), project=project_with_contract)
contract_name = path.stem
assert contract_name in [x.name for x in actual]

Expand Down
15 changes: 0 additions & 15 deletions tests/functional/utils/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,6 @@ def test_get_relative_path_from_project():
assert actual == expected


def test_get_relative_path_given_relative_path():
relative_script_path = Path("../deploy.py")
with pytest.raises(ValueError) as err:
get_relative_path(relative_script_path, _TEST_DIRECTORY_PATH)

assert str(err.value) == "'target' must be an absolute path."

relative_project_path = Path("../This/is/a/test")

with pytest.raises(ValueError) as err:
get_relative_path(_TEST_FILE_PATH, relative_project_path)

assert str(err.value) == "'anchor' must be an absolute path."


def test_get_relative_path_same_path():
actual = get_relative_path(_TEST_FILE_PATH, _TEST_FILE_PATH)
assert actual == Path()
Expand Down

0 comments on commit 50299ab

Please sign in to comment.