Coverage for packages/workshop/src/livery/workshop/_clean.py: 94%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""``fm clean``: restore this working tree to a fresh checkout of HEAD.
2
3``clean`` restores the working tree; ``workflow.abort`` stops a
4workflow. This verb's object is the thing people mean by "clean":
5the working tree in front of them.
6
7Two safety properties, both about irreversibility:
8
9- **A machine secret is never collectable.** ``*.env.local`` holds
10 values that exist in no git history, so removing one cannot be
11 undone by any checkout. It survives ``--all``, which is otherwise
12 the take-the-gitignored-output-too switch.
13- **The destructive step is deliberate.** What will be discarded is
14 listed first and confirmed. Not a ``--force`` flag, a verb whose
15 whole purpose is discarding must not refuse in the exact case you
16 would reach for it, but not silent either.
17"""
18
19from __future__ import annotations
20
21from dataclasses import dataclass
22from pathlib import Path
23from typing import Annotated
24
25import livery.footman as footman
26import livery.toolroom.tools as tools
27from livery import git
28from livery.footman import doc, fail
29
30#: Never removed, at any depth, under any flag. A machine secret is
31#: the one thing here that no checkout can restore.
32PROTECTED_SUFFIX = ".env.local"
33
34
35@dataclass(frozen=True)
36class CleanPlan:
37 """What a clean would do, before it does any of it."""
38
39 modified: tuple[str, ...]
40 untracked: tuple[str, ...]
41 protected: tuple[str, ...]
42
43 @property
44 def empty(self) -> bool:
45 """Whether there is nothing to discard or remove."""
46 return not (self.modified or self.untracked)
47
48
49def _query(root: Path, *args: str) -> tools.Result:
50 return git.call(root, *args)
51
52
53def _protected(path: str) -> bool:
54 """Whether *path* is a machine secret the clean must never take."""
55 return Path(path).name.endswith(PROTECTED_SUFFIX)
56
57
58def protected_within(root: Path, candidate: str) -> tuple[str, ...]:
59 """The machine secrets beneath *candidate*, relative to *root*.
60
61 A directory removed whole takes every secret nested in it, so a
62 caller that removes directories asks here first. The untracked
63 enumeration collapses an untracked directory into one entry, so a
64 secret nested inside it never reaches the name check: the clean
65 takes such a directory one file at a time instead, and the sync's
66 sweep of a removed package's leftovers keeps it.
67 """
68 target = root / candidate
69 if not target.is_dir():
70 return ()
71 return tuple(
72 sorted(
73 # POSIX separators, like every other path here: these are
74 # git pathspecs, and on Windows `str(Path)` yields
75 # backslashes, which git reads as escapes rather than
76 # directories.
77 found.relative_to(root).as_posix()
78 for found in target.rglob(f"*{PROTECTED_SUFFIX}")
79 if found.is_file()
80 )
81 )
82
83
84def plan_clean(root: Path, *, everything: bool) -> CleanPlan:
85 """What ``clean`` would discard here; a pure read, no changes.
86
87 ``--all`` (*everything*) widens the untracked sweep to gitignored
88 files too (build output, caches), the only difference between
89 the two modes besides the count.
90 """
91 status = _query(root, "status", "--porcelain")
92 modified = tuple(
93 line[3:]
94 for line in status.stdout.splitlines()
95 if line and not line.startswith("??")
96 )
97 # `git ls-files --others --directory -z` lists exactly what
98 # `git clean -nd` would take, and lists it as data: NUL-separated
99 # raw bytes. The dry run prints "Would remove <path>" instead,
100 # which is translated (a non-English locale yields no candidates
101 # at all) and C-quotes any path outside ASCII, which then fails
102 # the removal round-trip. Dropping --exclude-standard widens the
103 # sweep to gitignored paths, matching `clean -ndx`.
104 args = ["ls-files", "--others", "--directory", "-z"]
105 if not everything:
106 args.append("--exclude-standard")
107 listing = _query(root, *args)
108 candidates = tuple(
109 entry.rstrip("/") for entry in listing.stdout.split("\0") if entry
110 )
111 removable: list[str] = []
112 protected: list[str] = []
113 for candidate in candidates:
114 if _protected(candidate):
115 protected.append(candidate)
116 continue
117 nested = protected_within(root, candidate)
118 if not nested:
119 removable.append(candidate)
120 continue
121 # The directory holds a secret, so it cannot go as one entry:
122 # keep the secret and take the rest file by file.
123 protected.extend(nested)
124 removable.extend(
125 posix
126 for found in sorted((root / candidate).rglob("*"))
127 if found.is_file()
128 and (posix := found.relative_to(root).as_posix()) not in nested
129 )
130 return CleanPlan(
131 modified=modified,
132 untracked=tuple(removable),
133 protected=tuple(protected),
134 )
135
136
137def render_plan(plan: CleanPlan) -> list[str]:
138 """The listing shown before the confirmation."""
139 lines: list[str] = []
140 for path in plan.modified:
141 lines.append(f" discard changes {path}")
142 for path in plan.untracked:
143 lines.append(f" remove {path}")
144 for path in plan.protected:
145 lines.append(f" KEEP (secret) {path}")
146 return lines
147
148
149def clean_tree(
150 root: Path, *, everything: bool = False, assume_yes: bool = False
151) -> None:
152 """Restore the tree, after listing and confirming what that costs."""
153 plan = plan_clean(root, everything=everything)
154 if plan.empty:
155 print(" Nothing to clean - the tree already matches HEAD")
156 for line in render_plan(plan):
157 print(line) # a protected file is still worth naming
158 return
159 for line in render_plan(plan):
160 print(line)
161 if not assume_yes and not footman.confirm(
162 f"Discard {len(plan.modified)} change(s) and remove"
163 f" {len(plan.untracked)} file(s)?"
164 ):
165 print(" Left alone")
166 return
167 if plan.modified:
168 restore = _query(root, "checkout", "--", ".")
169 if restore.code != 0:
170 fail(f"could not restore tracked files: {restore.stderr.strip()}")
171 for path in plan.untracked:
172 # One path at a time, so the protected files simply never
173 # appear in the argv: `git clean` has no "except this" and an
174 # -e pattern would put the secret's safety in a string nobody
175 # re-reads. Mirror the plan's scope: without -x git silently
176 # refuses every gitignored path it just listed, and the count
177 # below would claim removals that never happened.
178 remove_args = ["clean", "-fdq"]
179 if everything:
180 remove_args.append("-x")
181 removed = _query(root, *remove_args, "--", path)
182 if removed.code != 0:
183 print(f" could not remove {path}: {removed.stderr.strip()}")
184 print(
185 f" Restored: {len(plan.modified)} change(s) discarded,"
186 f" {len(plan.untracked)} file(s) removed"
187 )
188 if plan.protected:
189 print(
190 f" Kept {len(plan.protected)} machine-secret file(s) - never collectable"
191 )
192
193
194@footman.task(interactive=True)
195def clean(
196 all: Annotated[bool, doc("also remove gitignored files (build output)")] = False,
197 yes: Annotated[bool, doc("skip the confirmation")] = False,
198) -> None:
199 """Restore the working tree to a fresh checkout of HEAD.
200
201 Lists what a clean would discard, asks, then restores tracked
202 files and removes untracked ones. ``*.env.local`` files are kept
203 at any depth under any flag: a machine secret exists in no git
204 history, so removing one cannot be undone.
205 """
206 from livery.workshop._extensions import workspace_root
207
208 root = workspace_root()
209 if root is None:
210 fail("no workspace: no workshop.toml above the working directory")
211 clean_tree(root, everything=all, assume_yes=yes)