Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(core): one set of repo-relative path helpers (#3987)

Raghav Chamadiya88238f72140c
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
index 448880b7c..62cc8b56b 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/_shared.py
@@ -423,15 +423,6 @@ def _record_opportunity(
return
-def _relativize(file_path: str, repo_path: Path) -> str | None:
- """Repo-relative POSIX path for *file_path*, or None when outside it."""
- try:
- rel = Path(file_path).resolve().relative_to(Path(repo_path).resolve())
- except (ValueError, OSError):
- return None
- return rel.as_posix()
-
-
@lru_cache(maxsize=8)
def _find_repo_root(cwd: Path) -> Path | None:
"""Walk up from cwd to find a directory with .repowise/.
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py b/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py
index a6b3384af..3dd2a9f24 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py
@@ -83,9 +83,9 @@ def _handle_post_edit_use(
if tool_input is not None and session_id:
file_path = tool_input.get("file_path") if isinstance(tool_input, dict) else None
if isinstance(file_path, str) and file_path.strip():
- from .read_state import _relativize
+ from repowise.core.fsutils import repo_relative
- rel = _relativize(file_path, repo_path)
+ rel = repo_relative(file_path, repo_path, resolve=True)
if rel is not None:
state = _load_session_state(repo_path, session_id)
for emit in (
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
index 67de2e000..8d8d54aa6 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/coverage_reingest.py
@@ -29,6 +29,8 @@ import shlex
import time
from pathlib import Path
+from repowise.core.fsutils import repo_relative
+
from ._shared import _find_repo_root, hook_flag_enabled
from .fast_lookup import _DB_ENV_VARS
@@ -223,7 +225,7 @@ def _notice(tool_input: dict, cwd: str) -> str | None:
# A mapped ``coverage.paths`` entry keeps its prefix as ``PATH=PREFIX``.
spawn_coverage_add(repo, [f"{p}={pre}" if pre else p for p, _mtime, pre in reports])
_write_queued(repo, newest)
- names = ", ".join(_rel(repo, p) for p, _mtime, _prefix in reports)
+ names = ", ".join(repo_relative(p, repo) or p.as_posix() for p, _mtime, _prefix in reports)
return (
f"[repowise] Re-ingesting coverage from {names} in the background "
f"(log: .repowise/{LOG_FILENAME}); get_change_risk reads it once the ingest finishes."
@@ -350,13 +352,6 @@ def _expand(repo: Path, rel: str) -> list[Path]:
return expand_report_patterns([rel], repo)
-def _rel(repo: Path, path: Path) -> str:
- try:
- return path.relative_to(repo).as_posix()
- except ValueError:
- return path.as_posix()
-
-
def last_ingest_time(db: Path) -> float | None:
"""Epoch seconds of the newest coverage ingest; ``0.0`` when none; ``None`` when unreadable."""
import sqlite3
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
index 2a341ca59..ae34cceff 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/read_state.py
@@ -41,7 +41,9 @@ from __future__ import annotations
import json
from pathlib import Path
-from ._shared import HookResult, _extract_output_text, _find_repo_root, _relativize
+from repowise.core.fsutils import repo_relative
+
+from ._shared import HookResult, _extract_output_text, _find_repo_root
#: Replacement gates. Named for the retired nudge they were first tuned for,
#: and left that way on purpose: :mod:`search_digest` documents its own ratio
@@ -224,7 +226,7 @@ def _handle_edit_post(
repo_path = _find_repo_root(Path(cwd))
if repo_path is None:
return None
- rel = _relativize(file_path, repo_path)
+ rel = repo_relative(file_path, repo_path, resolve=True)
if rel is None:
return None
state = _load_session_state(repo_path, session_id)
@@ -307,7 +309,7 @@ def _handle_read_post(
repo_path = _find_repo_root(Path(cwd))
if repo_path is None:
return HookResult()
- rel = _relativize(file_path, repo_path)
+ rel = repo_relative(file_path, repo_path, resolve=True)
if rel is None:
return HookResult()
if adapter is None:
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
index dd220cf9d..cc9837d20 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
@@ -40,7 +40,9 @@ from __future__ import annotations
import json
from pathlib import Path
-from ._shared import _find_repo_root, _relativize
+from repowise.core.fsutils import repo_relative
+
+from ._shared import _find_repo_root
_SERVED_COVERAGE = 0.8 # served share of a Read window that counts as covered
_MAX_SERVED_FILES = 50 # served-range bookkeeping caps (state-file hygiene)
@@ -69,7 +71,7 @@ def _log_read_after_served(
repo_path = _find_repo_root(Path(cwd))
if repo_path is None:
return
- rel = _relativize(file_path, repo_path)
+ rel = repo_relative(file_path, repo_path, resolve=True)
if rel is None:
return
window = _read_window(tool_input, tool_output)
diff --git a/packages/core/src/repowise/core/analysis/dead_code/published_api.py b/packages/core/src/repowise/core/analysis/dead_code/published_api.py
index 18e123310..537921335 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/published_api.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/published_api.py
@@ -24,6 +24,8 @@ from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any
+from repowise.core.fsutils import repo_relative
+
from .models import DeadCodeFindingData, DeadCodeKind
#: Where a published symbol lands: under ``RISK_CAP_CONFIDENCE``, so the
@@ -43,14 +45,6 @@ class BuildFacts:
dotnet_index: Any | None
-def _relative(path: Path, root: Path) -> str | None:
- try:
- rel = path.resolve().relative_to(root.resolve()).as_posix()
- except (OSError, ValueError):
- return None
- return "" if rel == "." else rel
-
-
def _keeps_api_baseline(project_dir: Path) -> bool:
try:
folders = [project_dir, *(p for p in project_dir.iterdir() if p.is_dir())]
@@ -67,9 +61,10 @@ def _dotnet_published(facts: BuildFacts) -> dict[str, str | None]:
root = Path(index.repo_path)
out: dict[str, str | None] = {}
for project in index.projects.values():
- rel = _relative(project.project_dir, root)
+ rel = repo_relative(project.project_dir, root, resolve=True)
if rel is None:
continue
+ rel = "" if rel == "." else rel
name = project.published_id
if name is None and _keeps_api_baseline(project.project_dir):
name = project.assembly_name or project.path.stem
diff --git a/packages/core/src/repowise/core/fsutils.py b/packages/core/src/repowise/core/fsutils.py
index 7cd5c1094..194cbafbd 100644
--- a/packages/core/src/repowise/core/fsutils.py
+++ b/packages/core/src/repowise/core/fsutils.py
@@ -6,7 +6,7 @@ import os
import tempfile
import time
from collections.abc import Iterable
-from pathlib import Path
+from pathlib import Path, PurePath
from typing import Any
@@ -93,3 +93,38 @@ def relative_files(files: Iterable[str], repo_root: Any) -> list[str]:
continue
out.append(path)
return list(dict.fromkeys(out))
+
+
+def repo_relative(
+ path: str | os.PathLike[str], root: str | os.PathLike[str], *, resolve: bool = False
+) -> str | None:
+ """POSIX spelling of *path* under *root*, or None when it lies outside.
+
+ Lexical (``Path.relative_to``) by default, so both sides must already be
+ in the same form. *resolve* resolves both first, which follows symlinks
+ and reads a relative *path* against the working directory. *root* itself
+ reads as ".". Separators are the host's: on POSIX a backslash stays a
+ character.
+ """
+ try:
+ if resolve:
+ return Path(path).resolve().relative_to(Path(root).resolve()).as_posix()
+ p = path if isinstance(path, PurePath) else Path(path)
+ return p.relative_to(root).as_posix()
+ except (OSError, ValueError):
+ return None
+
+
+def strip_dir_prefix(path: str, base: str) -> str:
+ """POSIX *path* relative to directory *base*; unchanged outside it or when *base* is empty."""
+ if base and path.startswith(base + "/"):
+ return path[len(base) + 1 :]
+ return path
+
+
+def comparable_path(path: str | None) -> str:
+ """*path* with forward slashes and no leading "./"; None reads as ""."""
+ cleaned = (path or "").replace("\\", "/")
+ while cleaned.startswith("./"):
+ cleaned = cleaned[2:]
+ return cleaned
diff --git a/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py b/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py
index 436a496c3..6bb3802d0 100644
--- a/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py
+++ b/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py
@@ -31,6 +31,7 @@ from typing import Any
from repowise.core import fs_walk
from repowise.core.exclusion import build_exclude_spec, is_excluded
+from repowise.core.fsutils import repo_relative
from repowise.core.ingestion.traverser import is_output_dir
from .grouping import ConceptGroup
@@ -296,10 +297,7 @@ class HouseTerm:
def _rel(path: Path, repo_root: Path) -> str:
"""Repo-relative posix path, or the bare name when it is not under root."""
- try:
- return path.relative_to(repo_root).as_posix()
- except ValueError: # pragma: no cover — path came from repo_root
- return path.name
+ return repo_relative(path, repo_root) or path.name
def _exclude_spec(repo_root: Path) -> Any:
diff --git a/packages/core/src/repowise/core/generation/context/module_facts.py b/packages/core/src/repowise/core/generation/context/module_facts.py
index a0d958f8d..d55ff6176 100644
--- a/packages/core/src/repowise/core/generation/context/module_facts.py
+++ b/packages/core/src/repowise/core/generation/context/module_facts.py
@@ -24,6 +24,8 @@ from typing import Any
import networkx as nx
+from repowise.core.fsutils import strip_dir_prefix as relative_to
+
# The diagram stays small enough to read without zooming.
_MAX_PARTS = 9
_MAX_PART_EDGES = 12
@@ -52,12 +54,6 @@ def module_base(files: Iterable[str]) -> str:
return "/".join(common)
-def relative_to(path: str, base: str) -> str:
- """*path* relative to *base* when it lies under it, else unchanged."""
- prefix = f"{base}/" if base else ""
- return path[len(prefix) :] if prefix and path.startswith(prefix) else path
-
-
def _part_of(path: str, base: str) -> str:
"""The module part a file belongs to: its first segment below *base*."""
rest = relative_to(path, base)
diff --git a/packages/core/src/repowise/core/ingestion/external_systems/maven_model.py b/packages/core/src/repowise/core/ingestion/external_systems/maven_model.py
index f58290add..e9cb9dc95 100644
--- a/packages/core/src/repowise/core/ingestion/external_systems/maven_model.py
+++ b/packages/core/src/repowise/core/ingestion/external_systems/maven_model.py
@@ -13,6 +13,8 @@ import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
+from repowise.core.fsutils import repo_relative
+
_NS = re.compile(r"\{[^}]*\}")
_PROP_RE = re.compile(r"\$\{([^}]+)\}")
_MAX_PARENT_DEPTH = 16
@@ -245,10 +247,7 @@ def _parse_raw(
def _relative(path: Path, repo_root: Path) -> str:
- try:
- return path.resolve().relative_to(repo_root.resolve()).as_posix()
- except (OSError, ValueError):
- return path.name
+ return repo_relative(path, repo_root, resolve=True) or path.name
def _resolve(value: str, properties: dict[str, str]) -> str:
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py b/packages/core/src/repowise/core/ingestion/resolvers/csharp.py
index c70844d6c..8dd78af75 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/csharp.py
@@ -30,26 +30,12 @@ from __future__ import annotations
from pathlib import Path
+from repowise.core.fsutils import repo_relative
+
from .context import ResolverContext
from .dotnet import get_or_build_index
-def _to_repo_relative(abs_path: Path, repo_root_resolved: Path) -> str | None:
- """Return *abs_path* relative to a pre-resolved repo root in posix form.
-
- ``abs_path`` is expected to already be resolved — every value we pass
- in here comes out of ``DotNetProjectIndex.file_to_project`` /
- ``namespace_map``, both of which are keyed by resolved absolute paths.
- Re-resolving on every call (as the original implementation did) costs
- a stat-per-path-component on Windows and dominates ``graph.imports``
- wall-clock on large C# monorepos.
- """
- try:
- return abs_path.relative_to(repo_root_resolved).as_posix()
- except ValueError:
- return None
-
-
def _legacy_stem_resolve(
module_path: str, ctx: ResolverContext
) -> str | None:
@@ -137,7 +123,9 @@ def resolve_csharp_import(
repo_root_resolved = _repo_root_resolved(index, ctx.repo_path)
if ordered:
- rel = _to_repo_relative(ordered[0], repo_root_resolved)
+ # Index paths are already resolved, so the lexical form is enough;
+ # resolving again costs a stat per path component on Windows.
+ rel = repo_relative(ordered[0], repo_root_resolved)
if rel and rel in ctx.path_set:
return rel
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/vbnet.py b/packages/core/src/repowise/core/ingestion/resolvers/vbnet.py
index 842c33314..be60f65cb 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/vbnet.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/vbnet.py
@@ -20,12 +20,13 @@ mixed .sln) gives project-scoped answers:
from __future__ import annotations
+from repowise.core.fsutils import repo_relative
+
from .context import ResolverContext
from .csharp import (
_matches_package_prefix,
_repo_root_resolved,
_resolve_importer,
- _to_repo_relative,
)
from .dotnet import get_or_build_index
@@ -72,7 +73,7 @@ def resolve_vbnet_import(
if parent_ns in index.namespace_map:
ordered = index.rank_type_candidates(type_name, importer_abs)
for cand in ordered:
- rel = _to_repo_relative(cand, repo_root_resolved)
+ rel = repo_relative(cand, repo_root_resolved)
if rel and rel in ctx.path_set:
return rel
diff --git a/packages/core/src/repowise/core/workspace/code_api.py b/packages/core/src/repowise/core/workspace/code_api.py
index bd69f7015..fb047bc2f 100644
--- a/packages/core/src/repowise/core/workspace/code_api.py
+++ b/packages/core/src/repowise/core/workspace/code_api.py
@@ -38,6 +38,7 @@ import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
+from repowise.core.fsutils import repo_relative
from repowise.core.pyparse import parse_python
if TYPE_CHECKING:
@@ -103,13 +104,6 @@ class PublishedPackage:
# ---------------------------------------------------------------------------
-def _rel(path: Path, repo_path: Path) -> str | None:
- try:
- return path.relative_to(repo_path).as_posix()
- except ValueError:
- return None
-
-
def _npm(data: dict[str, Any], root: str) -> tuple[str, frozenset[str]] | None:
"""``name`` plus every file ``exports`` / ``main`` / ``module`` / ``types`` names.
@@ -277,7 +271,7 @@ def find_published_packages(
for dirpath, dirnames, filenames in walk_repo(repo_path, prune_dirs=prune):
if len(dirpath.relative_to(repo_path).parts) >= _MANIFEST_DEPTH:
dirnames[:] = []
- rel_dir = _rel(dirpath, repo_path)
+ rel_dir = repo_relative(dirpath, repo_path)
if rel_dir is None:
continue
root = "" if rel_dir == "." else rel_dir
@@ -291,7 +285,7 @@ def find_published_packages(
if ecosystem is None:
continue
manifest = dirpath / fname
- rel_manifest = _rel(manifest, repo_path)
+ rel_manifest = repo_relative(manifest, repo_path)
if rel_manifest is None:
continue
try:
@@ -322,7 +316,7 @@ def find_published_packages(
for csproj in find_csproj_files(repo_path):
project = parse_csproj(csproj)
- rel_manifest = _rel(csproj, repo_path) if project is not None else None
+ rel_manifest = repo_relative(csproj, repo_path) if project is not None else None
if project is None or rel_manifest is None:
continue
root = rel_manifest.rsplit("/", 1)[0] if "/" in rel_manifest else ""
diff --git a/packages/core/src/repowise/core/workspace/test_impact.py b/packages/core/src/repowise/core/workspace/test_impact.py
index ff81731c1..f15a4ef46 100644
--- a/packages/core/src/repowise/core/workspace/test_impact.py
+++ b/packages/core/src/repowise/core/workspace/test_impact.py
@@ -28,6 +28,7 @@ from repowise.core.analysis.test_reachability import (
tests_reaching_by_tier,
)
from repowise.core.analysis.test_selection import expand_test_scopes, scope_kind
+from repowise.core.fsutils import comparable_path as _norm
from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files
from repowise.core.workspace.config import WorkspaceConfig
from repowise.core.workspace.contracts import ContractLink, load_contract_store, same_service
@@ -120,14 +121,6 @@ class WorkspaceTestImpactResult:
summary: dict[str, Any] = field(default_factory=dict)
-def _norm(path: str) -> str:
- """One comparable spelling of a repo-relative path."""
- cleaned = (path or "").replace("\\", "/")
- while cleaned.startswith("./"):
- cleaned = cleaned[2:]
- return cleaned
-
-
def _internal_call(link: ContractLink) -> bool:
"""A link whose two ends are one program calling itself, as the matcher defines it."""
return same_service(
diff --git a/packages/server/src/repowise/server/mcp_server/_test_impact.py b/packages/server/src/repowise/server/mcp_server/_test_impact.py
index 6fb98b298..35d0668c3 100644
--- a/packages/server/src/repowise/server/mcp_server/_test_impact.py
+++ b/packages/server/src/repowise/server/mcp_server/_test_impact.py
@@ -18,6 +18,7 @@ import asyncio
import logging
from typing import TYPE_CHECKING, Any
+from repowise.core.fsutils import comparable_path
from repowise.server.mcp_server import _state
if TYPE_CHECKING:
@@ -42,14 +43,6 @@ __all__ = [
]
-def _norm(path: str) -> str:
- """The same one comparable spelling ``core.workspace.test_impact`` uses."""
- cleaned = (path or "").replace("\\", "/")
- while cleaned.startswith("./"):
- cleaned = cleaned[2:]
- return cleaned
-
-
def _lock() -> asyncio.Lock:
"""The one lock guarding the process-held indexes.
@@ -210,7 +203,7 @@ def tests_block_for(
block["unresolved_reason"] = "lookup_failed"
block["unresolved_detail"] = result.summary.get("detail")
return block
- path = _norm(consumer_file)
+ path = comparable_path(consumer_file)
rows = [
rec
for rec in result.recommendations
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 17a3841e3..53c25c280 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -40,6 +40,7 @@ from repowise.core.analysis.prior_fix_impact import (
unavailable_prior_fixes,
unsupported_prior_fixes,
)
+from repowise.core.fsutils import comparable_path
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
from repowise.server.mcp_server._budget.contracts import response_budget_shed_order
@@ -70,7 +71,6 @@ from repowise.server.mcp_server._helpers import (
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._test_impact import (
- _norm,
cross_repo_tests,
tests_block_for,
)
@@ -906,7 +906,7 @@ def _cross_repo_block(
keys = {
(
row.get("repo") or "",
- _norm(row.get("file") or ""),
+ comparable_path(row.get("file") or ""),
row.get("contract_id") or "",
)
for row in shown
diff --git a/packages/server/src/repowise/server/services/c4_builder/components.py b/packages/server/src/repowise/server/services/c4_builder/components.py
index b2b6404a2..adc92b743 100644
--- a/packages/server/src/repowise/server/services/c4_builder/components.py
+++ b/packages/server/src/repowise/server/services/c4_builder/components.py
@@ -30,6 +30,7 @@ from collections.abc import Iterable
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.fsutils import strip_dir_prefix
from repowise.core.ids import ComponentId, InvalidNodeIdError, render
from repowise.core.persistence import GraphNode
@@ -54,12 +55,6 @@ def component_id(component_path: str, *, is_root_bucket: bool = False) -> str:
return render(ComponentId(component_path or ".", is_root_bucket=is_root_bucket))
-def _relative(file_path: str, container_path: str) -> str:
- if container_path and file_path.startswith(container_path + "/"):
- return file_path[len(container_path) + 1 :]
- return file_path
-
-
def _component_for(
file_path: str, container_path: str, root_label: str
) -> tuple[str, str, str] | None:
@@ -72,7 +67,7 @@ def _component_for(
ending in the reserved root marker. One odd directory costs its own
component, not the whole view.
"""
- rel = _relative(file_path, container_path)
+ rel = strip_dir_prefix(file_path, container_path)
dirs = rel.split("/")[:-1] # directory segments only (drop the filename)
i = 0
diff --git a/tests/unit/test_fsutils_paths.py b/tests/unit/test_fsutils_paths.py
new file mode 100644
index 000000000..aa76d4a9a
--- /dev/null
+++ b/tests/unit/test_fsutils_paths.py
@@ -0,0 +1,85 @@
+"""Edge cases of the shared repo-relative path helpers in ``core.fsutils``."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from repowise.core.fsutils import comparable_path, repo_relative, strip_dir_prefix
+
+
+ ("parts", "expected"),
+ [
+ (("a", "b.py"), "a/b.py"),
+ ((), "."),
+ (("x", "..", "y"), "x/../y"), # lexical: no ".." folding
+ ],
+)
+def test_repo_relative_lexical(tmp_path: Path, parts: tuple[str, ...], expected: str) -> None:
+ path = tmp_path.joinpath(*parts)
+ assert repo_relative(path, tmp_path) == expected
+ assert repo_relative(str(path), str(tmp_path)) == expected
+
+
+def test_repo_relative_outside_root_is_none(tmp_path: Path) -> None:
+ root = tmp_path / "a"
+ assert repo_relative(tmp_path / "b" / "c.py", root) is None
+ assert repo_relative(tmp_path / "ab" / "c.py", root) is None # sibling sharing a prefix
+ assert repo_relative(tmp_path / "a" / ".." / "b", root) == "../b" # lexical, so it stays inside
+
+
+def test_repo_relative_resolve(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ (tmp_path / "y").mkdir()
+ assert repo_relative(tmp_path / "x" / ".." / "y", tmp_path, resolve=True) == "y"
+ assert repo_relative(tmp_path / "a" / ".." / ".." / "b", tmp_path, resolve=True) is None
+ monkeypatch.chdir(tmp_path)
+ assert repo_relative("y/f.py", tmp_path, resolve=True) == "y/f.py" # relative reads against cwd
+ assert repo_relative(tmp_path, tmp_path, resolve=True) == "."
+
+
+def test_repo_relative_resolve_follows_symlinks(tmp_path: Path) -> None:
+ root = tmp_path / "repo"
+ (root / "src").mkdir(parents=True)
+ link = tmp_path / "alias"
+ try:
+ os.symlink(root, link, target_is_directory=True)
+ except OSError:
+ pytest.skip("symlinks unavailable")
+ assert repo_relative(link / "src", root) is None
+ assert repo_relative(link / "src", root, resolve=True) == "src"
+
+
+ ("path", "base", "expected"),
+ [
+ ("a/b/c.py", "a/b", "c.py"),
+ ("a/bc/d.py", "a/b", "a/bc/d.py"),
+ ("a/b", "a/b", "a/b"),
+ ("a/b/", "a/b", ""),
+ ("x.py", "", "x.py"),
+ ("/a/b/c", "/a", "b/c"),
+ ],
+)
+def test_strip_dir_prefix(path: str, base: str, expected: str) -> None:
+ assert strip_dir_prefix(path, base) == expected
+
+
+ ("path", "expected"),
+ [
+ ("a\\b.py", "a/b.py"),
+ ("././a.py", "a.py"),
+ (".github/ci.yml", ".github/ci.yml"),
+ ("../a.py", "../a.py"),
+ ("/abs/a.py", "/abs/a.py"),
+ ("C:\\repo\\a.py", "C:/repo/a.py"),
+ ("a//b/", "a//b/"),
+ ("", ""),
+ (None, ""),
+ ],
+)
+def test_comparable_path(path: str | None, expected: str) -> None:
+ assert comparable_path(path) == expected