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/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_currency.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/pytest/tests/test_pytest_observer_runner.py, packages/extensions/pytest/tests/test_pytest_c4_reads.py, packages/extensions/docs/tests/test_task_links.py ran.
Keys
- r m x p show or hide the lines of a kind
- j k the next or previous highlighted chunk
- 0 the top of the page
- 1 the first highlighted chunk
- [ ] the previous or next file
- u the index
- ? show or hide this help
1"""``fm clean``: restore this working tree to a fresh checkout of HEAD.
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.
7Two safety properties, both about irreversibility:
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.
19from __future__ import annotations
21from dataclasses import dataclass
22from pathlib import Path
23from typing import Annotated
25import livery.footman as footman
26import livery.toolroom.tools as tools
27from livery import git
28from livery.footman import doc, fail
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"
35@dataclass(frozen=True)
37 """What a clean would do, before it does any of it."""
39 modified: tuple[str, ...]
40 untracked: tuple[str, ...]
41 protected: tuple[str, ...]
44 def empty(self) -> bool:
45 """Whether there is nothing to discard or remove."""
46 return not (self.modified or self.untracked)
49def _query(root: Path, *args: str) -> tools.Result:
50 return git.call(root, *args)
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)
58def protected_within(root: Path, candidate: str) -> tuple[str, ...]:
59 """The machine secrets beneath *candidate*, relative to *root*.
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.
68 target = root / candidate
69 if not target.is_dir():
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
77 found.relative_to(root).as_posix()
78 for found in target.rglob(f"*{PROTECTED_SUFFIX}")
84def plan_clean(root: Path, *, everything: bool) -> CleanPlan:
85 """What ``clean`` would discard here; a pure read, no changes.
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.
91 status = _query(root, "status", "--porcelain")
92 modified = tuple(
94 for line in status.stdout.splitlines()
95 if line and not line.startswith("??")
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
111 removable: list[str] = []
112 protected: list[str] = []
113 for candidate in candidates:
114 if _protected(candidate):
115 protected.append(candidate)
117 nested = protected_within(root, candidate)
119 removable.append(candidate)
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(
126 for found in sorted((root / candidate).rglob("*"))
128 and (posix := found.relative_to(root).as_posix()) not in nested
130 return CleanPlan(
132 untracked=tuple(removable),
133 protected=tuple(protected),
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}")
150 root: Path, *, everything: bool = False, assume_yes: bool = False
152 """Restore the tree, after listing and confirming what that costs."""
153 plan = plan_clean(root, everything=everything)
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
159 for line in render_plan(plan):
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)?"
165 print(" Left alone")
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"]
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()}")
185 f" Restored: {len(plan.modified)} change(s) discarded,"
186 f" {len(plan.untracked)} file(s) removed"
188 if plan.protected:
190 f" Kept {len(plan.protected)} machine-secret file(s) - never collectable"
194@footman.task(interactive=True)
196 all: Annotated[bool, doc("also remove gitignored files (build output)")] = False,
197 yes: Annotated[bool, doc("skip the confirmation")] = False,
199 """Restore the working tree to a fresh checkout of HEAD.
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.
206 from livery.workshop._extensions import workspace_root
208 root = workspace_root()
210 fail("no workspace: no workshop.toml above the working directory")
211 clean_tree(root, everything=all, assume_yes=yes)