Files
computer-playbook/tests/unit/python/scripts/system/worktree/test_lib.py
T
kevinveenbirkenbachandClaude Opus 5 575a5a87ac refactor(layout): sort shipped scripts by language and split the unit suite
Every script a role ships now lives under `files/<language>/`, and the unit
suite is split the same way: `tests/unit/python/` beside new sibling trees for
the other languages. `tests/lint/filesystem/test_role_files_layout.py` keeps it
that way; directories whose shape is dictated from outside carry a `.nocheck`
naming the constraint (Docker build contexts, WordPress mu-plugins, the Joomla
extension, Odoo addons, Playwright suites, the `files/test/test.sh` harness
that `test-e2e-cli` resolves generically).

This cannot be applied in halves. Moving a file and repointing what names it
are the same change: 14 references resolve only at deploy time, so the tree is
green either before or after, never between.

Those 14 were found by static resolution over every reference class, not by the
test suite -- a full `make quality-high` was green while all of them were
broken:

  * 7 `src:` values built from a role variable holding a bare filename
    (svc-bkp-remote-2-local, decidim, espocrm, friendica, joomla, pixelfed x2).
    The variable doubles as the destination name inside the container, so the
    language segment belongs at the call site, not in the variable.
  * `sys-service/tasks/04_base.yml` resolved every consumer's systemd script
    through `first_found(..., errors='strict')` over `files/script.{sh,py}`.
    18 roles ship exactly that and have no template fallback: the play would
    have died on each.
  * `sys-front-inj-javascript` fell back to `<role>/files/javascript.js`; the
    interface now reads `files/javascript/javascript.js`.
  * `sys-front-inj-logout/templates/head_sub.j2` built the cache-busting mtime
    path through `path_absolute(... 'files', ...)`.
  * 4 `ansible.builtin.script:` invocations naming a bare command
    (pull.py, prune.sh, set_postgres_superuser_password.sh, ganesha-serve.sh).
  * `dev-python/files/shell/install.sh` pointed at a sibling role's script.

Depth-dependent paths inside the moved trees were bumped accordingly: 59
`parents[N]` computations, 12 relative climbs, and the per-role recover CLI,
whose path `cli/administration/recover/recoverers.py` still assembled from the
pre-move location.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 01:31:09 +02:00

109 lines
4.0 KiB
Python

"""Contract of the shared worktree metadata helpers.
``worktree_unregister`` is what lets a teardown succeed under the agent sandbox,
which pins some files inside ``.git/worktrees/<id>`` as read-only bind mounts so
the directory cannot be unlinked. Its three outcomes drive both callers: fully
removed, unregistered but pinned, and still registered. The last one is the only
state that keeps a branch claimed, so it must never be reported as success.
"""
from __future__ import annotations
import os
import stat
import subprocess
import tempfile
import unittest
from pathlib import Path
from utils.cache.files import PROJECT_ROOT
LIB = PROJECT_ROOT / "scripts" / "system" / "worktree" / "lib.sh"
NEEDS_UNPRIVILEGED = "clearing the write bit does not restrain root"
def _call(func: str, *args: str) -> subprocess.CompletedProcess:
return subprocess.run(
["bash", "-c", f'source "$1"; shift; {func} "$@"', "bash", str(LIB), *args],
capture_output=True,
text=True,
check=False,
)
class TestWorktreeMetaDir(unittest.TestCase):
def test_reads_the_gitdir_pointer(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / ".git").write_text("gitdir: /somewhere/.git/worktrees/feat\n")
result = _call("worktree_meta_dir", tmp)
self.assertEqual(result.stdout.strip(), "/somewhere/.git/worktrees/feat")
def test_missing_git_file_yields_nothing(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
result = _call("worktree_meta_dir", tmp)
self.assertEqual(result.stdout.strip(), "")
def test_directory_git_yields_nothing(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / ".git").mkdir()
result = _call("worktree_meta_dir", tmp)
self.assertEqual(result.stdout.strip(), "")
class TestWorktreeUnregister(unittest.TestCase):
def _entry(self, tmp: str) -> Path:
entry = Path(tmp) / "feat"
entry.mkdir()
(entry / "gitdir").write_text("/checkout/.git\n")
(entry / "HEAD").write_text("ref: refs/heads/feat\n")
(entry / "commondir").write_text("../..\n")
return entry
def test_removes_the_whole_entry(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
entry = self._entry(tmp)
result = _call("worktree_unregister", str(entry))
self.assertEqual(result.returncode, 0)
self.assertFalse(entry.exists())
@unittest.skipIf(os.geteuid() == 0, NEEDS_UNPRIVILEGED)
def test_pinned_directory_still_unregisters(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
entry = self._entry(tmp)
tmp_path = Path(tmp)
parent_mode = tmp_path.stat().st_mode
(entry / "gitdir").unlink()
(entry / "HEAD").unlink()
tmp_path.chmod(parent_mode & ~stat.S_IWUSR)
try:
result = _call("worktree_unregister", str(entry))
finally:
tmp_path.chmod(parent_mode)
self.assertEqual(result.returncode, 1)
self.assertTrue(entry.exists())
@unittest.skipIf(os.geteuid() == 0, NEEDS_UNPRIVILEGED)
def test_undeletable_pointers_report_still_registered(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
entry = self._entry(tmp)
mode = entry.stat().st_mode
entry.chmod(mode & ~stat.S_IWUSR)
try:
result = _call("worktree_unregister", str(entry))
finally:
entry.chmod(mode)
self.assertEqual(result.returncode, 2)
self.assertTrue((entry / "gitdir").exists())
def test_is_idempotent_on_a_half_emptied_entry(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
entry = self._entry(tmp)
(entry / "HEAD").unlink()
result = _call("worktree_unregister", str(entry))
self.assertEqual(result.returncode, 0)
self.assertFalse(entry.exists())
if __name__ == "__main__":
unittest.main()