v0.166.0
 1"""Which checkout am I, and where does its state live?
 2
 3A checkout accumulates facts about itself: which database it uses, whether its
 4dev server is running. Those facts are *about* the checkout but they don't
 5belong *inside* it — a working tree is exactly what gets symlinked, copied,
 6rsynced, and mounted into containers, so state keyed by location is eventually
 7read by the wrong reader. Two worktrees sharing a `.plain/` then quietly share
 8a database, or one refuses to start because the other's dev server holds the
 9pidfile.
10
11So the checkout's path is the key, and the state lives beside the rest of
12Plain's machine-level cache. Artifacts stay in `.plain/` — logs you tail,
13compiled assets, certificates. The difference is that an artifact read from the
14wrong place is confusing, while a *fact* read from the wrong place is wrong.
15"""
16
17import hashlib
18from pathlib import Path
19
20from plain.runtime import PLAIN_CACHE_PATH
21
22from .utils import has_pyproject_toml
23
24
25def sanitize(value: str) -> str:
26    """Lowercase and reduce to `[a-z0-9_]`."""
27    return "".join(c if c.isalnum() else "_" for c in value.lower()).strip("_")
28
29
30def short_digest(value: str) -> str:
31    """A short, stable hash for disambiguating names built from `value`."""
32    return hashlib.sha256(value.encode()).hexdigest()[:8]
33
34
35def find_project_root(start: Path) -> Path:
36    """The nearest directory at or above `start` holding a pyproject.toml.
37
38    One definition, used by the CLI (which starts from the app), by `setup()`
39    (which starts from the working directory), and by the dev supervisors,
40    because they have to agree: the project root decides the database name, the
41    cluster identity, and where this checkout's state lives. Two answers means
42    two checkouts.
43    """
44    for directory in [start, *start.parents]:
45        if has_pyproject_toml(directory):
46            return directory
47    return start
48
49
50def checkout_id(project_root: Path) -> str:
51    """What "this checkout" means when we record or compare ownership.
52
53    One definition because it's compared for exact equality against the
54    database metadata `plain.dev.postgres.guard` reads, and two sites
55    normalizing differently would silently disagree forever rather than fail.
56    """
57    return str(project_root.resolve())
58
59
60def checkout_state_path(project_root: Path) -> Path:
61    """Where this checkout's facts about itself are kept.
62
63    Keyed by the checkout's resolved path (see the module docstring for why),
64    with the readable checkout name in the directory too, so the cache stays
65    greppable when something needs explaining.
66    """
67    resolved = project_root.resolve()
68    return (
69        PLAIN_CACHE_PATH
70        / "checkouts"
71        / f"{sanitize(resolved.name)}-{short_digest(str(resolved))}"
72    )