diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 806b0029..d7121a4e 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -5,6 +5,7 @@ from release_plan.next_chunk import cut_name, NextChunk, NoItem from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES from failure import Failure from forge.commands import Forge +from chunk_preflight.indentation import SpaceIndented from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran from text_files.markdown_text import listed, quoted from chunk_preflight.choices import PULLS_LIST @@ -19,7 +20,7 @@ def render(found: Gathered) -> list[str]: """One `- ` line per fact, then the item's tagline and detail, the detail of each item that may join its chunk, and what each tool printed.""" note = [f"- {found.note}"] if found.note else [] unseen = [f"- {UNSEEN_RELEASES}"] if found.plan_outside else [] - head = [*note, f"- {last_release(found.default, found.cut)}", *unseen, *merge_lines(found)] + head = [*note, f"- {last_release(found.default, found.cut)}", *unseen, *merge_lines(found), *indentation_lines(found.indentation)] paths = f"- The project's config puts its files and plan at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}." texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}." if isinstance(found.item, NoItem): @@ -38,6 +39,15 @@ def merge_lines(found: Gathered) -> list[str]: return [*left, *over, *unread] +def indentation_lines(found: SpaceIndented | Failure | None) -> list[str]: + """The one fact about indentation: the project's code is space-indented with no setting that says so. It only reports: a client's repo belongs to its team.""" + if isinstance(found, Failure): + return [f"- Whether the project's code is space-indented cannot be read: {found.reason}"] + if found is None: + return [] + return [f"- The project's code is space-indented ({found.spaced} lines against {found.tabbed} with tabs), and no `.editorconfig` with `indent_style` nor formatter setting (`rustfmt.toml` `hard_tabs`, Prettier `useTabs`, Biome `indentStyle`) says so. The technical principles indent with hard tabs unless a setting a tool reads, plus a decision in `docs/decisions.md` that names the reason, overrides that. Either convert the code to tabs, or record the override in `.editorconfig` and a decision."] + + def last_release(default: str, release: LastCut) -> str: if isinstance(release.tag, Failure): return f"Last version cut: cannot be read: {release.tag.reason}" diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 00f81899..b7de48b8 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -6,6 +6,7 @@ from failure import Failure from forge.commands import Forge from release_plan.release_standing import LastCut from release_plan.next_chunk import NextChunk, NoItem +from chunk_preflight.indentation import SpaceIndented @dataclasses.dataclass(frozen=True) @@ -75,3 +76,5 @@ class Gathered: merges_unread: Failure | None = None # The worktrees `chunk-pr clean` is still to remove. left: tuple[LeftWorktree, ...] = () + # The line counts of the project's code where it is space-indented with no setting that says so, or why they cannot be read; None where it is not. + indentation: SpaceIndented | Failure | None = None diff --git a/bin/chunk_preflight/indentation.py b/bin/chunk_preflight/indentation.py new file mode 100644 index 00000000..4a73e4c0 --- /dev/null +++ b/bin/chunk_preflight/indentation.py @@ -0,0 +1,56 @@ +"""Whether a project's code is space-indented with no tool setting that says so. + +The technical principles indent with hard tabs by default, and let a setting a tool reads override that. Code that is mostly space-indented, with no such setting, reads as a first session's habit that later sessions followed, not as a choice.""" +import dataclasses +import os +import pathlib +import re + +from failure import Failure +from git_cli.git_repo import git + +# The files the project's language tooling covers. Markdown, JSON and YAML are not code: their indentation is a format's. +CODE = re.compile(r".*\.(py|js|mjs|cjs|jsx|ts|tsx|rs|go|php|java|kt|kts|scala|rb|c|h|cc|cpp|hpp|cs|swift|sh|bash|lua|ex|exs|dart|vue|svelte)", re.IGNORECASE) +# Committed copies of other people's code follow their authors' style. +VENDORED = re.compile(r"(^|/)(vendor|node_modules|third_party)/") +# The files whose key says how to indent: an `.editorconfig` with `indent_style`, rustfmt's `hard_tabs`, Prettier's `useTabs` in its own files or a `package.json`, Biome's `indentStyle`. +SETTINGS = ( + (re.compile(r"\.editorconfig"), "indent_style"), + (re.compile(r"\.?rustfmt\.toml"), "hard_tabs"), + (re.compile(r"\.prettierrc(\.\w+)?|prettier\.config\.\w+|package\.json"), "useTabs"), + (re.compile(r"biome\.jsonc?"), "indentStyle"), +) +# Two spaces is the narrowest space indent; a lone leading space aligns a comment's continuation. +SPACED_LINE = re.compile(r"^ {2,}\S", re.MULTILINE) +TABBED_LINE = re.compile(r"^\t+\S", re.MULTILINE) + + +@dataclasses.dataclass(frozen=True) +class SpaceIndented: + """Lines of tracked code that start with spaces, and lines that start with tabs.""" + spaced: int + tabbed: int + + +def space_indented(base: pathlib.Path, timeout: float | None = None) -> SpaceIndented | Failure | None: + """The line counts of the tracked code under base where it has more space-indented lines than tab-indented ones and no tracked file sets the indent; None where it doesn't, or has no code; a Failure where a file cannot be read.""" + tracked = git("ls-files", "-z", cwd=str(base), timeout=timeout) + if isinstance(tracked, Failure): + return tracked + spaced = tabbed = 0 + for name in filter(None, tracked.split("\0")): + code = CODE.fullmatch(name) and not VENDORED.search(name) + key = next((key for pattern, key in SETTINGS if pattern.fullmatch(name.rsplit("/", 1)[-1])), None) + path = base / name + if not (code or key) or not os.path.isfile(path): + continue + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError as failure: + return Failure(f"cannot read {name}: {failure}") + if key and key in text: + return None + if code: + spaced += len(SPACED_LINE.findall(text)) + tabbed += len(TABBED_LINE.findall(text)) + return SpaceIndented(spaced, tabbed) if spaced > tabbed else None diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index 9487ea08..30bc9ce5 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -21,6 +21,11 @@ and prints that the release reviews and the cuts are the human's to call. It pri finished on the branch of an open pull request that is not a draft, where the checkout holds the plan. Where no item of the release can start and one awaits such a merge, it names those pull requests and says the working loop stops there; +- where the project's tracked code (the files its language tooling covers, not Markdown, JSON or + YAML) has more space-indented than tab-indented lines, and neither an `.editorconfig` with + `indent_style` nor a formatter setting (`rustfmt.toml` `hard_tabs`, Prettier `useTabs`, Biome + `indentStyle`) says so, one line naming the technical principles' hard-tabs default and the two + ways out. It only reports; - the next release and its first item that does not wait, the item loop-claude routes on, with its L and E + I; with --item , the plan item of that ID instead, which loop-claude names in a window named for an item. An item waits while it is marked question, while an item still in todo.md @@ -93,6 +98,7 @@ from git_cli import epic_branch from failure import Failure from forge.commands import Forge, forge_of, Run, runner from chunk_preflight.gathered import Gathered, ItemFacts, LeftWorktree, NamedPath, Ran, Worktree +from chunk_preflight.indentation import space_indented from chunk_preflight.facts import JOINING_DETAILS, render from project_config.main import located from forge.pulls import merged_pull @@ -165,7 +171,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make, epic_branch_of(config)) # A `checkout:` path lands in the worktree the chunk works in. made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config - return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, merges_unread=held.merges_unread, left=left_worktrees(root, forge_run) if config.merge == "human" else ())) + return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts, merges_unread=held.merges_unread, left=left_worktrees(root, forge_run) if config.merge == "human" else (), indentation=space_indented(item.worktree.path if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else root, timeout))) def epic_branch_of(config: ProjectConfig) -> str | None | Failure: diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index ed6a98bb..01ec521f 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -22,6 +22,7 @@ from release_plan.release_standing import LastCut, UNSEEN_RELEASES from release_plan.awaiting_merge import marked from release_plan import next_chunk from chunk_preflight.facts import open_pulls, render +from chunk_preflight.indentation import SpaceIndented from plan_store.todo_md import plan_of from chunk_preflight.choices import worktree_add, worktree_on, worktrees from project_config.doubles import write_config @@ -801,6 +802,35 @@ class Running(unittest.TestCase): self.assertIsNone(line_count(folder)) +class IndentationFact(unittest.TestCase): + def said(self, indentation): + found = dataclasses.replace(gathered(item_facts()), indentation=indentation) + return [line for line in render(found) if "indent" in line] + + def test_names_the_counts_the_principle_and_the_two_ways_out(self): + (line,) = self.said(SpaceIndented(spaced=120, tabbed=3)) + self.assertIn("space-indented (120 lines against 3 with tabs)", line) + self.assertIn("The technical principles indent with hard tabs", line) + self.assertIn("convert the code to tabs, or record the override in `.editorconfig` and a decision", line) + + def test_says_nothing_where_the_code_is_not_space_indented_and_why_where_it_cannot_be_read(self): + self.assertEqual(self.said(None), []) + self.assertEqual(self.said(Failure("cannot read a.py: denied")), ["- Whether the project's code is space-indented cannot be read: cannot read a.py: denied"]) + + def test_prints_it_from_a_checkout_of_spaced_code_and_only_then(self): + tabbed = Repo(self) + self.assertNotIn("space-indented", tabbed.preflight().stdout) + spaced = Repo(self) + spaced.write(spaced.root, "src/app.py", "def run():\n if True:\n return 1\n") + spaced.commit(spaced.root, "spaces") + done = spaced.preflight() + self.assertEqual(done.returncode, 0, done.stderr) + self.assertIn("- The project's code is space-indented (2 lines against 0 with tabs)", done.stdout) + spaced.write(spaced.root, ".editorconfig", "[*]\nindent_style = space\n") + spaced.commit(spaced.root, "setting") + self.assertNotIn("space-indented", spaced.preflight().stdout) + + class BesideTest(unittest.TestCase): """The fact that names the items that may start chunks beside the next one.""" # Items 3 and 4 touch other parts of one file, and item 6 touches what item 3 does. diff --git a/bin/chunk_preflight/test_indentation.py b/bin/chunk_preflight/test_indentation.py new file mode 100644 index 00000000..018db070 --- /dev/null +++ b/bin/chunk_preflight/test_indentation.py @@ -0,0 +1,72 @@ +import os +import pathlib +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from chunk_preflight.indentation import space_indented, SpaceIndented +from failure import Failure +from test_env import isolated_env + +TABBED = "def run():\n\tif True:\n\t\treturn 1\n" +SPACED = "def run():\n if True:\n return 1\n" + + +class SpaceIndentation(unittest.TestCase): + """Each case is a fake checkout whose tracked files are those given.""" + + def checkout(self, **files): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = pathlib.Path(os.path.realpath(temp.name)) + for name, text in files.items(): + path = root / name.replace("__", "/") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + subprocess.run(["git", "init", "--quiet"], cwd=root, check=True, env=isolated_env()) + subprocess.run(["git", "add", "-A"], cwd=root, check=True, env=isolated_env()) + return root + + def test_stays_silent_for_code_indented_with_tabs(self): + self.assertIsNone(space_indented(self.checkout(**{"app.py": TABBED}))) + + def test_counts_the_lines_of_code_indented_with_spaces_where_no_tool_setting_says_so(self): + root = self.checkout(**{"app.py": SPACED, "lib__more.rs": SPACED, "web__page.ts": TABBED, "README.md": SPACED}) + self.assertEqual(space_indented(root), SpaceIndented(spaced=4, tabbed=2)) + + def test_stays_silent_where_a_tool_reads_a_setting_that_says_so(self): + settings = { + "editorconfig": (".editorconfig", "[*]\nindent_style = space\n"), + "rustfmt": ("rustfmt.toml", "hard_tabs = false\n"), + "prettier": (".prettierrc.json", '{"useTabs": false}\n'), + "prettier in package.json": ("package.json", '{"prettier": {"useTabs": false}}\n'), + "biome": ("biome.jsonc", '{"formatter": {"indentStyle": "space"}}\n'), + "a nested editorconfig": ("src__.editorconfig", "indent_style = space\n"), + } + for label, (name, text) in settings.items(): + with self.subTest(label): + self.assertIsNone(space_indented(self.checkout(**{"app.py": SPACED, name: text}))) + + def test_reports_a_file_that_names_no_such_setting(self): + for name, text in ((".editorconfig", "[*]\nend_of_line = lf\n"), ("package.json", '{"name": "x"}\n'), ("notes.txt", "indent_style = space\n")): + with self.subTest(name): + self.assertIsInstance(space_indented(self.checkout(**{"app.py": SPACED, name: text})), SpaceIndented) + + def test_stays_silent_for_a_repo_without_code(self): + self.assertIsNone(space_indented(self.checkout(**{"README.md": SPACED, "data.json": SPACED, "ci.yml": SPACED}))) + + def test_leaves_out_vendored_code(self): + self.assertIsNone(space_indented(self.checkout(**{"vendor__lib.py": SPACED, "web__node_modules__x__index.js": SPACED}))) + + def test_stays_silent_where_tabs_are_as_many_as_spaces(self): + self.assertIsNone(space_indented(self.checkout(**{"a.py": SPACED, "b.py": TABBED}))) + + def test_says_why_it_cannot_read_a_checkout(self): + self.assertIsInstance(space_indented(pathlib.Path("/nonexistent-checkout")), Failure) + + +if __name__ == "__main__": + unittest.main() diff --git a/principles/technical-principles.md b/principles/technical-principles.md index bde9eb8c..aa8b2f4f 100644 --- a/principles/technical-principles.md +++ b/principles/technical-principles.md @@ -70,6 +70,7 @@ - Enumerate the cases that can go wrong and return them as explicit results (e.g. a result DTO with an optional error), so failure is part of the signature instead of a hidden second channel. - try/catch lives only at the edges, wrapped tightly around the call that can actually throw (DB, HTTP, filesystem), converting the exception into an explicit result right there. Pure functions and core logic never throw or catch for control flow. - A function that both returns a result and throws for some inputs has two error channels; collapse to one. Throw only for a truly unrecoverable state. + - Where code branches on why a call failed, it reads a status code, an exit code the tool documents, or a typed error. It reads message text only where the tool documents that text as unique to one cause, and treats every other failure as unknown, which stops the run rather than guessing. Older versions of a CLI often print one message for a missing image, a refused credential and a failed request. * Commands and Queries Separation (CQS)-ish - Queries must never modify data, commands may only return data that is the result of their change. * Copy important contextual information on buisness transactions and equal data, instead of referencing it. @@ -117,4 +118,4 @@ - A Python script with a `#!/usr/bin/env python3` shebang runs identically across systems where shell dialects and builtins differ. - Read config (credentials, hosts, paths) from CLI params or env vars, never hardcoded. * Indent with hard tabs by default. - - A project's own settings win: `.editorconfig`, linter/formatter config (Prettier, `rustfmt.toml`, …), or the surrounding file's existing indentation. + - Only a setting a tool reads overrides it: `.editorconfig` or a formatter's config (Prettier, `rustfmt.toml`, Biome, …), plus a decision in `docs/decisions.md` that names the reason. A prose rule in `AGENTS.md`, or the existing files' habit, doesn't. Output formats a spec fixes, such as a spelling's JSON, are outside the rule. `chunk-preflight` reports space-indented code that has no such setting.