diff --git a/src/helper_lib/__init__.py b/src/helper_lib/__init__.py index 74e275a1a..93ee7098f 100644 --- a/src/helper_lib/__init__.py +++ b/src/helper_lib/__init__.py @@ -59,6 +59,13 @@ def find_git_root() -> Path | None: start_path = find_ws_root() if start_path is None: start_path = Path.cwd() + if "execroot" in start_path.resolve().parts: + # Build actions do not receive BUILD_WORKSPACE_DIRECTORY. Their + # working directory is below Bazel's execroot, so walking parents + # can escape the sandbox and find an unrelated host Git worktree. + # Treat this as no worktree instead; bazel run uses the explicit + # workspace directory and never takes this fallback path. + return None git_root = Path(start_path).resolve() while not (git_root / ".git").exists(): git_root = git_root.parent diff --git a/src/helper_lib/test_helper_lib.py b/src/helper_lib/test_helper_lib.py index dfca2b261..e268158a9 100644 --- a/src/helper_lib/test_helper_lib.py +++ b/src/helper_lib/test_helper_lib.py @@ -20,6 +20,7 @@ from src.helper_lib import ( config_setdefault, + find_git_root, get_current_git_hash, get_github_repo_info, get_runfiles_dir, @@ -82,6 +83,19 @@ def git_repo(temp_dir: Path) -> Path: return git_dir +def test_find_git_root_ignores_bazel_sandbox_ancestor_git_repo( + temp_dir: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A sandbox must not discover a Git repository outside its execroot.""" + (temp_dir / ".git").mkdir() + sandbox_dir = temp_dir / "sandbox" / "linux-sandbox" / "1" / "execroot" / "_main" + sandbox_dir.mkdir(parents=True) + monkeypatch.chdir(sandbox_dir) + monkeypatch.delenv("BUILD_WORKSPACE_DIRECTORY", raising=False) + + assert find_git_root() is None + + @pytest.fixture def git_repo_multiple_remotes(temp_dir: Path) -> Path: """Create a git repository with multiple remotes for testing."""