diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 9aab6c2a8..99fb49258 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -28,3 +28,10 @@ repos: - id: mixed-line-ending args: [--fix,lf] - id: trailing-whitespace +- repo: local + hooks: + - id: indent-fix + name: Convert indentation spaces to tabs + entry: python3 misc/spaces_to_tabs.py + language: system + files: \.(cc|h)$ diff --git a/misc/spaces_to_tabs.py b/misc/spaces_to_tabs.py new file mode 100644 index 000000000..7db3456f7 --- /dev/null +++ b/misc/spaces_to_tabs.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 + +import re +import sys +from pathlib import Path + +changed = False + +for filename in sys.argv[1:]: + path = Path(filename) + + try: + text = path.read_text() + except UnicodeDecodeError: + continue + + # Determine whether this file uses tabs for indentation. + uses_tabs = any( + re.match(r"^\t+", line) + for line in text.splitlines() + ) + + if not uses_tabs: + continue + + new_text = re.sub( + r"^(?: {4})+", + lambda m: "\t" * (len(m.group()) // 4), + text, + flags=re.MULTILINE, + ) + + if new_text != text: + path.write_text(new_text) + changed = True + print(f"Converted indentation to tabs: {filename}") + +sys.exit(1 if changed else 0)