Skip to content

: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.

feat(hogli): make worktrees:clean cargo-aware and drop ~/.cargo/target (#129033)

Robbie4919b517133e
diff --git a/docs/published/handbook/engineering/flox-multi-instance-workflow.md b/docs/published/handbook/engineering/flox-multi-instance-workflow.md
index 210048f2cf33..98a18ca56663 100644
--- a/docs/published/handbook/engineering/flox-multi-instance-workflow.md
+++ b/docs/published/handbook/engineering/flox-multi-instance-workflow.md
@@ -403,6 +403,8 @@ git worktree prune
```
To clear old `phw`, Claude Code, Codex, and PostHog Code worktrees in bulk, run `hogli worktrees:clean --before 7d --mode deps --dry-run` to preview, then drop `--dry-run`, or use `--mode full` to remove whole worktrees.
+Both modes skip a worktree where `cargo` or `rustc` is running.
+`--mode deps` keeps a Cargo `target` that a build used after the cutoff, and, without `--source` or `--repo`, offers to delete the old shared `~/.cargo/target` when `CARGO_TARGET_DIR` is not set and no build used it after the cutoff.
Flox activation also runs this once a day in the background: `--mode deps` on worktrees idle for 7 days and `--mode full` on worktrees idle for 14 days.
It skips worktrees with uncommitted or unpushed work and keeps every branch.
diff --git a/tools/hogli-commands/hogli_commands/cargo_targets.py b/tools/hogli-commands/hogli_commands/cargo_targets.py
new file mode 100644
index 000000000000..cfd88c140c4f
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/cargo_targets.py
@@ -0,0 +1,108 @@
+from __future__ import annotations
+
+import os
+import subprocess
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+from .processes import process_cwds
+
+
+@dataclass(frozen=True, kw_only=True)
+class InodeKey:
+ """Identifies a directory independent of symlinks and of path case on a case-insensitive file system."""
+
+ device: int
+ inode: int
+
+
+def inode_key(path: Path) -> InodeKey | None:
+ try:
+ stat = path.stat()
+ except OSError:
+ return None
+ return InodeKey(device=stat.st_dev, inode=stat.st_ino)
+
+
+def _cargo_pids() -> list[int] | None:
+ try:
+ result = subprocess.run(["pgrep", "-x", "cargo|rustc"], capture_output=True, text=True, timeout=5, check=False)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode not in (0, 1):
+ return None
+ return [int(pid) for pid in result.stdout.split() if pid.isdigit()]
+
+
+def _is_alive(pid: int) -> bool:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ pass
+ return True
+
+
+def worktrees_running_cargo(worktrees: Sequence[Path]) -> set[Path] | None:
+ """The worktrees where cargo or rustc runs, or None when a running build cannot be traced to a directory."""
+
+ pids = _cargo_pids()
+ if pids is None:
+ return None
+ if not pids:
+ return set()
+
+ cwd_by_pid = process_cwds(pids)
+ if any(pid not in cwd_by_pid and _is_alive(pid) for pid in pids):
+ return None
+
+ worktree_by_key = {key: worktree for worktree in worktrees if (key := inode_key(worktree)) is not None}
+ busy: set[Path] = set()
+ for cwd in cwd_by_pid.values():
+ for directory in (Path(cwd), *Path(cwd).parents):
+ key = inode_key(directory)
+ if key in worktree_by_key:
+ busy.add(worktree_by_key[key])
+ break
+ return busy
+
+
+def last_cargo_build_epoch(target: Path) -> float:
+ """Newest mtime under each .fingerprint dir, at <profile>/ or at <target-triple>/<profile>/, which Cargo rewrites for every unit it builds."""
+
+ newest = 0.0
+ for fingerprint_dir in (*target.glob("*/.fingerprint"), *target.glob("*/*/.fingerprint")):
+ try:
+ with os.scandir(fingerprint_dir) as units:
+ unit_dirs = [Path(unit.path) for unit in units if unit.is_dir(follow_symlinks=False)]
+ newest = max(newest, fingerprint_dir.stat().st_mtime)
+ except OSError:
+ continue
+ for unit_dir in unit_dirs:
+ try:
+ with os.scandir(unit_dir) as entries:
+ for entry in entries:
+ newest = max(newest, entry.stat(follow_symlinks=False).st_mtime)
+ except OSError:
+ continue
+
+ if newest == 0.0:
+ try:
+ newest = target.stat().st_mtime
+ except OSError:
+ pass
+ return newest
+
+
+def unused_legacy_cargo_target(built_before_epoch: float) -> Path | None:
+ """The ~/.cargo/target that Cargo used when the Flox env set CARGO_TARGET_DIR, if no build used it after *built_before_epoch*."""
+
+ target = Path.home() / ".cargo" / "target"
+ if os.environ.get("CARGO_TARGET_DIR") or not target.is_dir() or target.is_symlink():
+ return None
+ if last_cargo_build_epoch(target) >= built_before_epoch:
+ return None
+ # A shell with an older Flox env can still build here, and its CARGO_TARGET_DIR is not visible from this process.
+ return target if _cargo_pids() == [] else None
diff --git a/tools/hogli-commands/hogli_commands/doctor.py b/tools/hogli-commands/hogli_commands/doctor.py
index 1759d001e2ea..78de0928a946 100644
--- a/tools/hogli-commands/hogli_commands/doctor.py
+++ b/tools/hogli-commands/hogli_commands/doctor.py
@@ -27,6 +27,8 @@ import click
from hogli.manifest import REPO_ROOT, get_manifest
from . import hints
+from .cargo_targets import unused_legacy_cargo_target
+from .processes import process_cwds
MAX_SAMPLE_PATHS = 8
@@ -38,6 +40,8 @@ MAX_SAMPLE_PATHS = 8
FLOX_LOG_MAX_AGE_DAYS = 7
FLOX_LOG_MAX_TOTAL_BYTES = 512 * 1024 * 1024 # 512 MiB of recent logs is plenty for debugging
+STALE_RUST_TARGET_DAYS = 7
+
PYTHON_CACHE_PATTERNS = ("__pycache__", ".mypy_cache", ".pytest_cache", ".ruff_cache")
NODE_ARTIFACT_PATTERNS = (
".parcel-cache",
@@ -143,6 +147,7 @@ class CleanupResult:
"dagster",
"node-artifacts",
"rust",
+ "legacy-cargo-target",
"sccache",
"uv-cache",
"pnpm-store",
@@ -170,6 +175,7 @@ def doctor_disk(
- Dagster background job storage
- pnpm/Vite/Tailwind/Storybook/Playwright build artifacts
- Rust workspaces built with Cargo, plus the sccache compilation cache
+ - The old shared Cargo target at ~/.cargo/target
- The uv and pnpm package caches shared across every worktree
Several of these caches live outside the repository because the Flox env
@@ -290,6 +296,18 @@ def doctor_disk(
skip_if_empty=False,
dry_run_message="Would run: cargo clean in all Rust workspaces",
),
+ CleanupCategory(
+ id="legacy_cargo_target",
+ title="🦀 Old shared Cargo target (~/.cargo/target)",
+ description=[
+ "Cargo built here while the Flox env set CARGO_TARGET_DIR to this directory.",
+ f"Deleted only when CARGO_TARGET_DIR is not set and no build used it in {STALE_RUST_TARGET_DAYS} days.",
+ ],
+ estimate=_estimate_legacy_cargo_target,
+ cleanup=_cleanup_legacy_cargo_target,
+ confirmation_prompt="Delete the old shared Cargo target?",
+ default_confirm=False,
+ ),
CleanupCategory(
id="sccache",
title="⚡ sccache compilation cache",
@@ -1411,6 +1429,27 @@ def _collect_rust_target_dirs(repo_root: Path) -> list[CleanupItem]:
return items
+def _estimate_legacy_cargo_target(_repo_root: Path) -> CleanupEstimate:
+ pointer = f" For the rust/target of other worktrees, run: hogli worktrees:clean --before {STALE_RUST_TARGET_DAYS}d --mode deps"
+ target = unused_legacy_cargo_target(time.time() - STALE_RUST_TARGET_DAYS * 24 * 60 * 60)
+ if target is None:
+ return CleanupEstimate(total_size=0.0, items=[], details=[" Nothing to delete.", pointer])
+
+ size, _ = _get_dir_size(target)
+ return CleanupEstimate(
+ total_size=size,
+ items=[CleanupItem(target, size, is_dir=True)],
+ details=[f" {target} ({_format_size(size)})", pointer],
+ )
+
+
+def _cleanup_legacy_cargo_target(estimate: CleanupEstimate, repo_root: Path) -> CleanupStats:
+ if unused_legacy_cargo_target(time.time() - STALE_RUST_TARGET_DAYS * 24 * 60 * 60) is None:
+ click.echo(" A build used it while the prompt waited, so it is kept.")
+ return CleanupStats()
+ return _cleanup_items(estimate, repo_root)
+
+
def _find_cargo_workspaces(repo_root: Path) -> list[Path]:
"""Find all Cargo workspace roots in the repository.
@@ -1718,7 +1757,7 @@ def _scan_posthog_processes(repo_root: Path) -> list[DevProcess]:
candidates.append((entry, False))
cwd_pids.append(pid)
- cwd_by_pid = _get_process_cwds(cwd_pids)
+ cwd_by_pid = process_cwds(cwd_pids)
processes: list[DevProcess] = []
for entry, repo_match in candidates:
@@ -1893,41 +1932,6 @@ def _has_known_executable(args: str) -> bool:
return first_word in known
-def _get_process_cwds(pids: Sequence[int]) -> dict[int, str]:
- """Map each pid to its working directory via a single lsof call.
-
- ``-a`` ANDs the ``-p`` (pid set) and ``-d cwd`` (fd) selectors; without it
- lsof ORs them and reports *every* process's cwd — slow (a full-system scan
- per pid) and wrong (attributing the first process's cwd to the queried pid).
- ``-Fpn`` emits pid/name fields so each cwd attributes back to its pid; with
- ``-d cwd`` each process yields exactly one name line.
- """
- if not pids:
- return {}
-
- try:
- result = subprocess.run(
- ["lsof", "-a", "-p", ",".join(str(pid) for pid in pids), "-d", "cwd", "-Fpn"],
- capture_output=True,
- text=True,
- check=False,
- )
- except FileNotFoundError:
- return {}
-
- # lsof exits non-zero when any queried pid has vanished, but still emits valid
- # records for the survivors — parse whatever stdout we got.
- cwds: dict[int, str] = {}
- current: int | None = None
- for line in result.stdout.splitlines():
- tag, value = line[:1], line[1:]
- if tag == "p":
- current = int(value) if value.isdigit() else None
- elif tag == "n" and current is not None:
- cwds[current] = value
- return cwds
-
-
def _extract_process_name(args: str) -> str:
"""Extract a short display name from a full command line."""
diff --git a/tools/hogli-commands/hogli_commands/processes.py b/tools/hogli-commands/hogli_commands/processes.py
new file mode 100644
index 000000000000..3436224c0073
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/processes.py
@@ -0,0 +1,39 @@
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Sequence
+
+
+def process_cwds(pids: Sequence[int]) -> dict[int, str]:
+ """Map each pid to its working directory via a single lsof call.
+
+ ``-a`` ANDs the ``-p`` (pid set) and ``-d cwd`` (fd) selectors; without it
+ lsof ORs them and reports *every* process's cwd — slow (a full-system scan
+ per pid) and wrong (attributing the first process's cwd to the queried pid).
+ ``-Fpn`` emits pid/name fields so each cwd attributes back to its pid; with
+ ``-d cwd`` each process yields exactly one name line.
+ """
+ if not pids:
+ return {}
+
+ try:
+ result = subprocess.run(
+ ["lsof", "-a", "-p", ",".join(str(pid) for pid in pids), "-d", "cwd", "-Fpn"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ except FileNotFoundError:
+ return {}
+
+ # lsof exits non-zero when any queried pid has vanished, but still emits valid
+ # records for the survivors — parse whatever stdout we got.
+ cwds: dict[int, str] = {}
+ current: int | None = None
+ for line in result.stdout.splitlines():
+ tag, value = line[:1], line[1:]
+ if tag == "p":
+ current = int(value) if value.isdigit() else None
+ elif tag == "n" and current is not None:
+ cwds[current] = value
+ return cwds
diff --git a/tools/hogli-commands/hogli_commands/tests/test_doctor.py b/tools/hogli-commands/hogli_commands/tests/test_doctor.py
index f3bac1d4ee7a..98536562109e 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_doctor.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_doctor.py
@@ -36,7 +36,6 @@ from hogli_commands.doctor import (
_find_volume_mount,
_format_kv_block,
_generated_config_path,
- _get_process_cwds,
_git_common_dir,
_git_health,
_git_housekeeping_running,
@@ -61,6 +60,7 @@ from hogli_commands.doctor import (
doctor_migrate_volumes,
doctor_ports,
)
+from hogli_commands.processes import process_cwds
_QUARTER_BUDGET = FLOX_LOG_MAX_TOTAL_BYTES // 4
_TWO_FIFTHS_BUDGET = int(FLOX_LOG_MAX_TOTAL_BYTES * 0.4)
@@ -255,25 +255,25 @@ def test_probe_command_imports(commands: dict[str, dict], expected_failure: tupl
assert expected_failure[1] in error
-def test_get_process_cwds_skips_lsof_for_empty_input(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_process_cwds_skips_lsof_for_empty_input(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(*_args: object, **_kwargs: object) -> SimpleNamespace:
raise AssertionError("lsof must not run for an empty pid list")
- monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fail)
- assert _get_process_cwds([]) == {}
+ monkeypatch.setattr("hogli_commands.processes.subprocess.run", fail)
+ assert process_cwds([]) == {}
-def test_get_process_cwds_parses_and_batches(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_process_cwds_parses_and_batches(monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, object] = {}
def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
captured["cmd"] = cmd
return SimpleNamespace(returncode=1, stdout="p100\nn/repo/a\np200\nn/repo/b\n", stderr="")
- monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ monkeypatch.setattr("hogli_commands.processes.subprocess.run", fake_run)
# Non-zero rc (a pid vanished) must not discard the records that did resolve.
- assert _get_process_cwds([100, 200]) == {100: "/repo/a", 200: "/repo/b"}
+ assert process_cwds([100, 200]) == {100: "/repo/a", 200: "/repo/b"}
# One batched, ANDed lsof call covering every pid — not one call per pid.
cmd = captured["cmd"]
assert isinstance(cmd, list)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
index 0c824a1b66f7..130cbab1be1c 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import os
import math
import time
import fcntl
@@ -13,6 +14,7 @@ from unittest.mock import Mock, patch
import click
from hogli import telemetry
from hogli_commands import worktrees
+from hogli_commands.cargo_targets import unused_legacy_cargo_target, worktrees_running_cargo
from hogli_commands.devbox import config as devbox_config
from hogli_commands.worktrees import (
Worktree,
@@ -30,6 +32,7 @@ from hogli_commands.worktrees import (
_is_under,
_match_worktree_boxes,
_parse_cutoff,
+ _populate_sizes,
_reclaimed_bytes,
_registered_worktrees,
_resolve_box_action,
@@ -262,6 +265,87 @@ class TestCollectDepsItems:
assert all(_is_under(item, worktree_resolved) for item in items)
assert (external / "dist").resolve() not in items
+ def test_deps_mode_keeps_a_cargo_target_built_after_the_cutoff(self, tmp_path) -> None:
+ cutoff = time.time() - 7 * 86400
+ worktree = tmp_path / "wt"
+ (worktree / "node_modules").mkdir(parents=True)
+ stale_target = _write_cargo_target(worktree / "rust" / "target", cutoff - 86400)
+ # Cargo rewrites fingerprint files in place, so a fresh build leaves the directory mtimes old.
+ _write_cargo_target(worktree / "cli" / "target", time.time())
+ _write_cargo_target(worktree / "plugin" / "target", time.time(), profile=Path("wasm32-wasip1") / "release")
+ wt = _make_worktree(worktree)
+
+ _populate_sizes([wt], "deps", cutoff)
+
+ assert sorted(wt.deps_items) == sorted([(worktree / "node_modules").resolve(), stale_target.resolve()])
+
+
+def _write_cargo_target(target: Path, last_build_epoch: float, profile: Path = Path("debug")) -> Path:
+ unit = target / profile / ".fingerprint" / "posthog-unit"
+ unit.mkdir(parents=True)
+ (unit / "lib-posthog").write_bytes(b"x" * 1024)
+ os.utime(unit / "lib-posthog", (last_build_epoch, last_build_epoch))
+ (target / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55\n")
+ month_ago = time.time() - 30 * 86400
+ directory = unit
+ while directory != target.parent:
+ os.utime(directory, (month_ago, month_ago))
+ directory = directory.parent
+ return target
+
+
+def _fake_cargo_processes(monkeypatch, cargo_cwd: Path | None, lsof_available: bool = True) -> None:
+ def fake_run(args, **kwargs):
+ if args[0] == "pgrep":
+ return subprocess.CompletedProcess(
+ args, 0 if cargo_cwd else 1, stdout=f"{os.getpid()}\n" if cargo_cwd else ""
+ )
+ if not lsof_available:
+ raise FileNotFoundError("lsof")
+ return subprocess.CompletedProcess(args, 0, stdout=f"p{os.getpid()}\nn{cargo_cwd}\n")
+
+ monkeypatch.setattr("hogli_commands.cargo_targets.subprocess.run", fake_run)
+
+
+class TestCargoTargets:
+ @pytest.mark.parametrize("lsof_available", [True, False], ids=["traced", "lsof_unavailable"])
+ def test_worktree_with_cargo_running_below_its_root_is_busy(self, tmp_path, monkeypatch, lsof_available) -> None:
+ idle, building = tmp_path / "idle", tmp_path / "building"
+ cargo_cwd = building / "rust" / "capture"
+ cargo_cwd.mkdir(parents=True)
+ idle.mkdir()
+ _fake_cargo_processes(monkeypatch, cargo_cwd, lsof_available)
+
+ # A live cargo process that cannot be traced to a directory must block every worktree, not none.
+ assert worktrees_running_cargo([idle, building]) == ({building} if lsof_available else None)
+
+ @pytest.mark.parametrize(
+ "cargo_target_dir_set,days_since_build,cargo_running,expected_offered",
+ [(False, 10, False, True), (True, 10, False, False), (False, 1, False, False), (False, 10, True, False)],
+ ids=["unused", "cargo_target_dir_set", "built_recently", "cargo_running_elsewhere"],
+ )
+ def test_legacy_cargo_target_is_offered_only_when_nothing_builds_there(
+ self,
+ tmp_path,
+ monkeypatch,
+ cargo_target_dir_set: bool,
+ days_since_build: int,
+ cargo_running: bool,
+ expected_offered: bool,
+ ) -> None:
+ home = tmp_path / "home"
+ target = _write_cargo_target(home / ".cargo" / "target", time.time() - days_since_build * 86400)
+ monkeypatch.setattr(Path, "home", lambda: home)
+ _fake_cargo_processes(monkeypatch, tmp_path if cargo_running else None)
+ if cargo_target_dir_set:
+ monkeypatch.setenv("CARGO_TARGET_DIR", str(target))
+ else:
+ monkeypatch.delenv("CARGO_TARGET_DIR", raising=False)
+
+ offered = unused_legacy_cargo_target(time.time() - 7 * 86400)
+
+ assert offered == (target if expected_offered else None)
+
class TestRegisteredWorktrees:
def test_parses_branch_detached_and_locked(self, tmp_path, monkeypatch) -> None:
diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.py
index 3525e2a3e3ff..a73fde89392f 100644
--- a/tools/hogli-commands/hogli_commands/worktrees.py
+++ b/tools/hogli-commands/hogli_commands/worktrees.py
@@ -18,7 +18,8 @@ the directory never touches git refs, so committed work survives in the shared
repo — only uncommitted edits in an already-stale tree could be lost. `--mode
deps` only removes recreatable artifacts, so it has no such gate — it can strip
deps from a worktree that is idle by the activity signal but still has a live
-dev server/build running.
+dev server running. Both modes skip a worktree where cargo or rustc runs, and
+`--mode deps` keeps a Cargo target that a build used after the cutoff.
"""
from __future__ import annotations
@@ -41,6 +42,7 @@ import click
from hogli import telemetry
from hogli.manifest import REPO_ROOT
+from .cargo_targets import last_cargo_build_epoch, unused_legacy_cargo_target, worktrees_running_cargo
from .devbox import hogland, mutagen
from .devbox.coder import (
delete_workspace,
@@ -334,6 +336,9 @@ def worktrees_clean(
if box_action:
pending = _boxes_of_removed_worktrees(load_worktree_boxes(), repo_root, repo_common, selected_sources)
_clean_boxes_of_removed_worktrees(pending, box_action, cutoff, dry_run, yes)
+ # ~/.cargo/target belongs to no single worktree or repository, so a run narrowed by --source or --repo leaves it alone.
+ if mode == "deps" and selected_sources is None and repo is None:
+ _clean_legacy_cargo_target(cutoff, dry_run, yes)
protected = _protected_paths(repo_root)
registry = _registered_worktrees(repo_root)
@@ -392,6 +397,11 @@ def worktrees_clean(
if not stale:
return
+ stale = _without_cargo_builds(stale)
+ if not stale:
+ click.echo("Nothing left to remove.")
+ return
+
# Full mode is destructive of working-tree state, so refuse worktrees with
# unsaved work — or whose git state we can't verify — unless the user opts in.
# (deps mode only removes recreatable artifacts, so it doesn't need this gate.)
@@ -419,7 +429,7 @@ def worktrees_clean(
return
click.echo(f"Measuring {len(stale)} worktree(s)…")
- _populate_sizes(stale, mode)
+ _populate_sizes(stale, mode, cutoff)
for wt in sorted(stale, key=lambda w: w.last_activity):
markers = _listing_markers(wt, mode)
@@ -452,6 +462,14 @@ def worktrees_clean(
click.echo("Aborted.")
return
+ # A build can start, or finish, while the prompt waits.
+ stale = _without_cargo_builds(stale)
+ for wt in stale:
+ wt.deps_items = [item for item in wt.deps_items if not _cargo_built_since(item, cutoff)]
+ if not stale:
+ click.echo("Nothing left to remove.")
+ return
+
reap = _execute(
stale,
mode,
@@ -1198,14 +1216,14 @@ def _listing_markers(wt: Worktree, mode: str) -> str:
return " · ".join(parts)
-def _populate_sizes(worktrees: list[Worktree], mode: str) -> None:
+def _populate_sizes(worktrees: list[Worktree], mode: str, cutoff: float) -> None:
"""Fill in .size (and deps items/sizes for deps mode) using a thread pool."""
def work(wt: Worktree) -> None:
if mode == "full":
wt.deps_sizes = _du_sizes([wt.path])
else:
- wt.deps_items = _collect_deps_items(wt.path)
+ wt.deps_items = [item for item in _collect_deps_items(wt.path) if not _cargo_built_since(item, cutoff)]
wt.deps_sizes = _du_sizes(wt.deps_items)
wt.size = sum(wt.deps_sizes.values())
@@ -1262,6 +1280,48 @@ def _looks_like_cargo_target(path: Path) -> bool:
return (path / "CACHEDIR.TAG").exists() or (path / "debug").exists() or (path / "release").exists()
+def _without_cargo_builds(worktrees: list[Worktree]) -> list[Worktree]:
+ building = worktrees_running_cargo([wt.path for wt in worktrees])
+ if building is None:
+ click.echo("Could not find the directory of every running cargo or rustc process, so no worktree is changed.\n")
+ return []
+ if building:
+ click.echo(f"Skipping {len(building)} worktree(s) where cargo is running:")
+ for wt in worktrees:
+ if wt.path in building:
+ click.echo(f" {wt.source} {_display_path(wt.path)}")
+ click.echo()
+ return [wt for wt in worktrees if wt.path not in building]
+
+
+def _cargo_built_since(path: Path, cutoff: float) -> bool:
+ return path.name == "target" and _looks_like_cargo_target(path) and last_cargo_build_epoch(path) >= cutoff
+
+
+def _clean_legacy_cargo_target(cutoff: float, dry_run: bool, yes: bool) -> None:
+ target = unused_legacy_cargo_target(cutoff)
+ if target is None:
+ return
+
+ size = sum(_du_sizes([target]).values())
+ click.echo(
+ f"Old shared Cargo target {_display_path(target)}: {_format_size(size)}, "
+ f"last build {_ago(last_cargo_build_epoch(target))} ago. Cargo built here while the Flox env set CARGO_TARGET_DIR."
+ )
+ if dry_run:
+ click.echo("[DRY-RUN] Not deleted.\n")
+ return
+ if not yes and not click.confirm("Delete it?", default=False):
+ click.echo()
+ return
+ if unused_legacy_cargo_target(cutoff) is None:
+ click.echo("A build used it while the prompt waited, so it is kept.\n")
+ return
+ if _delete_paths([target]) == 0:
+ click.echo(f"✓ Deleted {_display_path(target)}.")
+ click.echo()
+
+
def _du_sizes(paths: Sequence[Path]) -> dict[str, float]:
"""On-disk size in bytes per path via a single `du -sk`.