59 lines
2.7 KiB
Python
59 lines
2.7 KiB
Python
"""Whether a project's code is space-indented where no tool setting sets the indent.
|
|
|
|
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
|
|
|
|
# Files of common programming languages, by extension. The check skips Markdown, JSON and YAML, which are prose or data.
|
|
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 key that, present in a file of that name, means the project sets its indent, whatever the key's value. Prettier also reads `package.json`.
|
|
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 than tab-indented lines and no tracked file holds an indent key; else None. A Failure where git cannot list the files or a file cannot be read."""
|
|
tracked = git("ls-files", "-z", cwd=str(base), timeout=timeout, errors="replace")
|
|
if isinstance(tracked, Failure):
|
|
return tracked
|
|
spaced = tabbed = 0
|
|
for name in filter(None, tracked.split("\0")):
|
|
if VENDORED.search(name):
|
|
continue
|
|
code = CODE.fullmatch(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"{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
|