:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogli): remove read-only directories in worktrees:clean (#113326)
Raúl Negrón-Otero63d1b1407af1
diff --git a/.flox/env/manifest.lock b/.flox/env/manifest.lockindex 39f49e9f0658..fb583d5fba7e 100644--- a/.flox/env/manifest.lock+++ b/.flox/env/manifest.lock@@ -203,10 +203,10 @@"on-activate": "source \"$FLOX_ENV_PROJECT/.flox/env/on-activate.sh\"\n"},"profile": {- "bash": " if [ -f \"$HOME/.bash_profile\" ]; then\n source \"$HOME/.bash_profile\"\n fi\n unset GOROOT\n export GOTOOLCHAIN=local\n export GOPATH=\"$FLOX_ENV_CACHE/go\"\n export GOCACHE=\"$FLOX_ENV_CACHE/go-build\"\n export GOMODCACHE=\"$GOPATH/pkg/mod\"\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n export PATH=\"$FLOX_ENV/bin:$PATH\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n export UV_PROJECT_ENVIRONMENT=\"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if [ ! -f \"$UV_PROJECT_ENVIRONMENT/bin/activate\" ]; then\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n elif [ ! -L \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ] || [ ! -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ]; then\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n fi\n source $UV_PROJECT_ENVIRONMENT/bin/activate\n # Source hogli bash completions\n [ -f \"$FLOX_ENV_CACHE/completions/hogli.bash\" ] && source \"$FLOX_ENV_CACHE/completions/hogli.bash\"\n # Load phw worktree helper\n [ -f \"$FLOX_ENV_PROJECT/bin/phw\" ] && source \"$FLOX_ENV_PROJECT/bin/phw\" >/dev/null\n # Route manually-run dependency installs (uv sync, pnpm install, ...) through the dev sandbox on macOS\n [ -f \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\" ] && source \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\"\n",- "zsh": " if [[ -f \"$HOME/.zshrc\" ]]; then\n source \"$HOME/.zshrc\"\n fi\n unset GOROOT\n export GOTOOLCHAIN=local\n export GOPATH=\"$FLOX_ENV_CACHE/go\"\n export GOCACHE=\"$FLOX_ENV_CACHE/go-build\"\n export GOMODCACHE=\"$GOPATH/pkg/mod\"\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n export PATH=\"$FLOX_ENV/bin:$PATH\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n export UV_PROJECT_ENVIRONMENT=\"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if [[ ! -f \"$UV_PROJECT_ENVIRONMENT/bin/activate\" ]]; then\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n elif [[ ! -L \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ]] || [[ ! -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ]]; then\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n fi\n source $UV_PROJECT_ENVIRONMENT/bin/activate\n # Add hogli completions to zsh\n [[ -f \"$FLOX_ENV_CACHE/completions/_hogli\" ]] && fpath=(\"$FLOX_ENV_CACHE/completions\" $fpath)\n autoload -Uz compinit && compinit -i\n # Load phw worktree helper\n [[ -f \"$FLOX_ENV_PROJECT/bin/phw\" ]] && source \"$FLOX_ENV_PROJECT/bin/phw\" >/dev/null\n # Route manually-run dependency installs (uv sync, pnpm install, ...) through the dev sandbox on macOS\n [[ -f \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\" ]] && source \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\"\n",- "fish": " set -e GOROOT\n set -gx GOTOOLCHAIN local\n set -gx GOPATH \"$FLOX_ENV_CACHE/go\"\n set -gx GOCACHE \"$FLOX_ENV_CACHE/go-build\"\n set -gx GOMODCACHE \"$GOPATH/pkg/mod\"\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n fish_add_path -g \"$FLOX_ENV/bin\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n set -gx UV_PROJECT_ENVIRONMENT \"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if not test -f \"$UV_PROJECT_ENVIRONMENT/bin/activate.fish\"\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n else if not test -L \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"; or not test -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n end\n source $UV_PROJECT_ENVIRONMENT/bin/activate.fish\n",- "tcsh": " unsetenv GOROOT\n setenv GOTOOLCHAIN local\n setenv GOPATH \"$FLOX_ENV_CACHE/go\"\n setenv GOCACHE \"$FLOX_ENV_CACHE/go-build\"\n setenv GOMODCACHE \"$GOPATH/pkg/mod\"\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n setenv PATH \"$FLOX_ENV/bin:$PATH\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n setenv UV_PROJECT_ENVIRONMENT \"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if ( ! -f \"$UV_PROJECT_ENVIRONMENT/bin/activate.csh\" ) then\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n else if ( ! -l \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" || ! -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ) then\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n endif\n source $UV_PROJECT_ENVIRONMENT/bin/activate.csh\n"+ "bash": " if [ -f \"$HOME/.bash_profile\" ]; then\n source \"$HOME/.bash_profile\"\n fi\n unset GOROOT\n export GOTOOLCHAIN=local\n export GOPATH=\"$FLOX_ENV_CACHE/go\"\n export GOCACHE=\"$FLOX_ENV_CACHE/go-build\"\n export GOMODCACHE=\"$GOPATH/pkg/mod\"\n export GOFLAGS=-modcacherw\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n export PATH=\"$FLOX_ENV/bin:$PATH\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n export UV_PROJECT_ENVIRONMENT=\"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if [ ! -f \"$UV_PROJECT_ENVIRONMENT/bin/activate\" ]; then\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n elif [ ! -L \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ] || [ ! -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ]; then\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n fi\n source $UV_PROJECT_ENVIRONMENT/bin/activate\n # Source hogli bash completions\n [ -f \"$FLOX_ENV_CACHE/completions/hogli.bash\" ] && source \"$FLOX_ENV_CACHE/completions/hogli.bash\"\n # Load phw worktree helper\n [ -f \"$FLOX_ENV_PROJECT/bin/phw\" ] && source \"$FLOX_ENV_PROJECT/bin/phw\" >/dev/null\n # Route manually-run dependency installs (uv sync, pnpm install, ...) through the dev sandbox on macOS\n [ -f \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\" ] && source \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\"\n",+ "zsh": " if [[ -f \"$HOME/.zshrc\" ]]; then\n source \"$HOME/.zshrc\"\n fi\n unset GOROOT\n export GOTOOLCHAIN=local\n export GOPATH=\"$FLOX_ENV_CACHE/go\"\n export GOCACHE=\"$FLOX_ENV_CACHE/go-build\"\n export GOMODCACHE=\"$GOPATH/pkg/mod\"\n export GOFLAGS=-modcacherw\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n export PATH=\"$FLOX_ENV/bin:$PATH\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n export UV_PROJECT_ENVIRONMENT=\"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if [[ ! -f \"$UV_PROJECT_ENVIRONMENT/bin/activate\" ]]; then\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n elif [[ ! -L \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ]] || [[ ! -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ]]; then\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n fi\n source $UV_PROJECT_ENVIRONMENT/bin/activate\n # Add hogli completions to zsh\n [[ -f \"$FLOX_ENV_CACHE/completions/_hogli\" ]] && fpath=(\"$FLOX_ENV_CACHE/completions\" $fpath)\n autoload -Uz compinit && compinit -i\n # Load phw worktree helper\n [[ -f \"$FLOX_ENV_PROJECT/bin/phw\" ]] && source \"$FLOX_ENV_PROJECT/bin/phw\" >/dev/null\n # Route manually-run dependency installs (uv sync, pnpm install, ...) through the dev sandbox on macOS\n [[ -f \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\" ]] && source \"$FLOX_ENV_PROJECT/bin/dev-sandbox-shims\"\n",+ "fish": " set -e GOROOT\n set -gx GOTOOLCHAIN local\n set -gx GOPATH \"$FLOX_ENV_CACHE/go\"\n set -gx GOCACHE \"$FLOX_ENV_CACHE/go-build\"\n set -gx GOMODCACHE \"$GOPATH/pkg/mod\"\n set -gx GOFLAGS -modcacherw\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n fish_add_path -g \"$FLOX_ENV/bin\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n set -gx UV_PROJECT_ENVIRONMENT \"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if not test -f \"$UV_PROJECT_ENVIRONMENT/bin/activate.fish\"\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n else if not test -L \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"; or not test -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n end\n source $UV_PROJECT_ENVIRONMENT/bin/activate.fish\n",+ "tcsh": " unsetenv GOROOT\n setenv GOTOOLCHAIN local\n setenv GOPATH \"$FLOX_ENV_CACHE/go\"\n setenv GOCACHE \"$FLOX_ENV_CACHE/go-build\"\n setenv GOMODCACHE \"$GOPATH/pkg/mod\"\n setenv GOFLAGS -modcacherw\n # Ensure flox binaries (especially Node.js) take precedence over system binaries\n setenv PATH \"$FLOX_ENV/bin:$PATH\"\n # uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)\n setenv UV_PROJECT_ENVIRONMENT \"$FLOX_ENV_CACHE/venv\"\n # Recreate venv if it was deleted (on-activate only runs on first activation)\n if ( ! -f \"$UV_PROJECT_ENVIRONMENT/bin/activate.csh\" ) then\n uv sync\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n else if ( ! -l \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" || ! -e \"$UV_PROJECT_ENVIRONMENT/bin/hogli\" ) then\n ln -sf \"$FLOX_ENV_PROJECT/bin/hogli\" \"$UV_PROJECT_ENVIRONMENT/bin/hogli\"\n endif\n source $UV_PROJECT_ENVIRONMENT/bin/activate.csh\n"},"options": {"systems": [diff --git a/.flox/env/manifest.toml b/.flox/env/manifest.tomlindex df66f8c06a47..a42ea711b07f 100644--- a/.flox/env/manifest.toml+++ b/.flox/env/manifest.toml@@ -115,6 +115,7 @@ bash = '''export GOPATH="$FLOX_ENV_CACHE/go"export GOCACHE="$FLOX_ENV_CACHE/go-build"export GOMODCACHE="$GOPATH/pkg/mod"+ export GOFLAGS=-modcacherw# Ensure flox binaries (especially Node.js) take precedence over system binariesexport PATH="$FLOX_ENV/bin:$PATH"# uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)@@ -143,6 +144,7 @@ zsh = '''export GOPATH="$FLOX_ENV_CACHE/go"export GOCACHE="$FLOX_ENV_CACHE/go-build"export GOMODCACHE="$GOPATH/pkg/mod"+ export GOFLAGS=-modcacherw# Ensure flox binaries (especially Node.js) take precedence over system binariesexport PATH="$FLOX_ENV/bin:$PATH"# uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)@@ -169,6 +171,7 @@ fish = '''set -gx GOPATH "$FLOX_ENV_CACHE/go"set -gx GOCACHE "$FLOX_ENV_CACHE/go-build"set -gx GOMODCACHE "$GOPATH/pkg/mod"+ set -gx GOFLAGS -modcacherw# Ensure flox binaries (especially Node.js) take precedence over system binariesfish_add_path -g "$FLOX_ENV/bin"# uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)@@ -188,6 +191,7 @@ tcsh = '''setenv GOPATH "$FLOX_ENV_CACHE/go"setenv GOCACHE "$FLOX_ENV_CACHE/go-build"setenv GOMODCACHE "$GOPATH/pkg/mod"+ setenv GOFLAGS -modcacherw# Ensure flox binaries (especially Node.js) take precedence over system binariessetenv PATH "$FLOX_ENV/bin:$PATH"# uv venv path — set here, not in [vars] (which can't expand $FLOX_ENV_CACHE)diff --git a/.flox/env/on-activate.sh b/.flox/env/on-activate.shindex 90ff141fc409..4290d199e837 100755--- a/.flox/env/on-activate.sh+++ b/.flox/env/on-activate.sh@@ -219,6 +219,9 @@ export GOTOOLCHAIN=localexport GOPATH="$FLOX_ENV_CACHE/go"export GOCACHE="$FLOX_ENV_CACHE/go-build"export GOMODCACHE="$GOPATH/pkg/mod"+# Go creates the module cache read-only by default, and `rm -rf` on a worktree+# cannot delete a read-only directory tree.+export GOFLAGS=-modcacherw# uv-managed venv location (mirrors the [profile] scripts; not in [vars], which# can't expand $FLOX_ENV_CACHE). Used below for uv sync + the hogli symlink.diff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.pyindex 736ff6bd3afb..94bfe8ab6e04 100644--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py@@ -13,6 +13,7 @@ from hogli_commands.worktrees import (_collect_deps_items,_compute_git_state,_du_sizes,+ _execute,_include_orphans,_is_under,_parse_cutoff,@@ -285,6 +286,27 @@ class TestReclaimedBytes:assert _reclaimed_bytes({}, {}) == -1.0+class TestExecute:+ @pytest.mark.parametrize("read_only_go_module_cache", [True, False], ids=["read_only_tree", "already_removed"])+ def test_full_mode_counts_worktree_as_removed(self, tmp_path, read_only_go_module_cache) -> None:+ worktree = tmp_path / "wt"+ if read_only_go_module_cache:+ module = worktree / "mod" / "[email protected]"+ module.mkdir(parents=True)+ (module / "lib.go").write_text("package lib\n")+ module.chmod(0o555)+ module.parent.chmod(0o555)++ _, removed, failed = _execute(+ [Worktree(source="claude", path=worktree, registered=False, locked=False, branch="", last_activity=0.0)],+ "full",+ tmp_path,+ )++ assert (removed, failed) == (1, 0)+ assert not worktree.exists()++class TestDuSizes:def test_parses_per_path_and_skips_garbage(self, tmp_path, monkeypatch) -> None:a = tmp_path / "a"diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.pyindex 2183f50829e1..6569957c2a94 100644--- a/tools/hogli-commands/hogli_commands/worktrees.py+++ b/tools/hogli-commands/hogli_commands/worktrees.py@@ -28,7 +28,7 @@ import reimport timeimport shutilimport subprocess-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclass, fieldfrom datetime import datetime@@ -852,35 +852,31 @@ def _execute(worktrees: list[Worktree], mode: str, repo_root: Path) -> tuple[flofor wt in worktrees:if mode == "deps":- _, failures = _delete_paths(wt.deps_items, wt.deps_sizes)- if failures:+ if _delete_paths(wt.deps_items):failed += 1else:removed += 1continueif wt.registered:- result = subprocess.run(+ subprocess.run(["git", "worktree", "remove", "--force", "--", str(wt.path)],cwd=repo_root,capture_output=True,- text=True,)- if result.returncode != 0:- stderr = result.stderr.strip()- click.echo(f" ⚠️ git worktree remove failed for {_display_path(wt.path)}: {stderr}")- shutil.rmtree(wt.path, ignore_errors=True)- # Either path may have removed it; prune any dangling admin entry.+ # git cannot delete read-only directories, so `_rmtree` below removes what it leaves+ # behind. Prune the admin entry that can remain in that case.need_prune = True- else:- shutil.rmtree(wt.path, ignore_errors=True)- if wt.path.exists():- click.echo(f" ⚠️ could not fully remove {_display_path(wt.path)}")+ try:+ _rmtree(wt.path)+ except OSError as err:+ click.echo(f" ⚠️ could not fully remove {_display_path(wt.path)}: {err}")failed += 1- else:- removed += 1- _cleanup_empty_parent(wt.path)+ continue++ removed += 1+ _cleanup_empty_parent(wt.path)if need_prune:subprocess.run(["git", "worktree", "prune"], cwd=repo_root, capture_output=True)@@ -919,22 +915,51 @@ def _reclaimed_bytes(before: dict[int, int], after: dict[int, int]) -> float:return float(sum(max(0, after[device] - before[device]) for device in common))-def _delete_paths(paths: Sequence[Path], sizes: dict[str, float]) -> tuple[float, int]:- """Remove deps directories; return (bytes actually freed, paths that failed)."""+def _rmtree(path: Path) -> None:+ """Remove a directory tree, including entries inside read-only directories.++ Go creates its module cache without write permission, and every worktree has+ one in `.flox/cache/go`. `shutil.rmtree` alone cannot delete entries from a+ directory that is not writable.++ Removal continues past an entry that cannot be deleted, so one stuck entry+ does not keep the rest of the tree on disk. The first such error is raised+ at the end. A path that does not exist is already removed, so it is not an+ error.+ """++ unresolved: list[BaseException] = []++ def make_parent_writable_and_retry(function: Callable[..., object], failed: str, error: BaseException) -> None:+ if isinstance(error, FileNotFoundError):+ return+ parent = Path(failed).parent+ # A parent outside `path` is not part of the tree, so its permissions stay as they are.+ if isinstance(error, PermissionError) and function in (os.unlink, os.rmdir) and parent.is_relative_to(path):+ try:+ parent.chmod(0o700)+ function(failed)+ return+ except OSError:+ pass+ unresolved.append(error)++ shutil.rmtree(path, onexc=make_parent_writable_and_retry)+ if unresolved:+ raise unresolved[0]+++def _delete_paths(paths: Sequence[Path]) -> int:+ """Remove deps directories; return how many could not be removed."""- freed = 0.0failures = 0for path in paths:try:- shutil.rmtree(path)- except FileNotFoundError:- continue # already gone — not a failure+ _rmtree(path)except OSError as err:click.echo(f" ⚠️ could not remove {_display_path(path)}: {err}")failures += 1- continue- freed += sizes.get(str(path), 0.0)- return freed, failures+ return failuresdef _cleanup_empty_parent(path: Path) -> None: