"""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