#!/usr/bin/env python3 """Нормализация пробелов и табуляции в тексте.""" from __future__ import annotations import argparse import re import shutil from pathlib import Path FENCE = re.compile(r"^\s*(```|~~~)") def normalize_line(line: str, keep_indent: bool, tab_width: int) -> str: if not line.strip(): return "" indent = re.match(r"[ \t]*", line).group(0) body = line[len(indent):] body = re.sub(r"[ \t]+", " ", body).strip() if keep_indent and body: return indent.expandtabs(tab_width) + body return body def process(text: str, keep_indent: bool, tab_width: int, protect_code: bool) -> str: output = [] in_fence = False for line in text.splitlines(): if protect_code and FENCE.match(line): in_fence = not in_fence output.append(line) continue if in_fence: output.append(line) continue output.append(normalize_line(line, keep_indent, tab_width)) return "\n".join(output).rstrip("\n") + "\n" def main() -> int: parser = argparse.ArgumentParser(description="Нормализовать пробелы в тексте") parser.add_argument("input", type=Path, help="Входной файл") parser.add_argument("--output", type=Path, help="Выходной файл, по умолчанию stdout") parser.add_argument("--in-place", action="store_true", help="Заменить исходный файл") parser.add_argument("--keep-indent", action="store_true", help="Сохранить отступы слева") parser.add_argument("--tab-width", type=int, default=4, help="Ширина табуляции") parser.add_argument("--no-protect-code", action="store_true", help="Обрабатывать и блоки кода") args = parser.parse_args() source = args.input.expanduser() if not source.is_file(): parser.error(f"Файл не найден: {source}") if args.in_place and args.output: parser.error("С --in-place не указывайте --output") if args.output and args.output.expanduser().resolve() == source.resolve(): parser.error("Выходной файл совпадает с входным, используйте --in-place") text = source.read_text(encoding="utf-8") result = process(text, args.keep_indent, args.tab_width, not args.no_protect_code) if args.in_place: backup = source.with_name(source.name + ".bak") shutil.copy2(source, backup) source.write_text(result, encoding="utf-8") print(f"Файл обновлён, копия: {backup.name}") elif args.output: target = args.output.expanduser() target.parent.mkdir(parents=True, exist_ok=True) target.write_text(result, encoding="utf-8") print(f"Результат: {target}") else: print(result, end="") return 0 if __name__ == "__main__": raise SystemExit(main())