#!/usr/bin/env python3 """Проверка и добавление SPDX-заголовков в исходники.""" from __future__ import annotations import argparse import os from datetime import date from pathlib import Path STYLES = { ".py": "#", ".sh": "#", ".bash": "#", ".ps1": "#", ".rb": "#", ".yaml": "#", ".yml": "#", ".toml": "#", ".js": "//", ".jsx": "//", ".ts": "//", ".tsx": "//", ".mjs": "//", ".cjs": "//", ".go": "//", ".rs": "//", ".java": "//", ".kt": "//", ".c": "//", ".h": "//", ".cpp": "//", ".hpp": "//", ".cs": "//", ".php": "//", ".bat": "REM", ".cmd": "REM", } EXCLUDES = { ".git", ".hg", ".svn", ".venv", "venv", "node_modules", "__pycache__", "dist", "build", "target", "vendor", } def iter_files(root: Path): for current, dirs, files in os.walk(root): current_path = Path(current) dirs[:] = [ name for name in dirs if name not in EXCLUDES and not (current_path / name).is_symlink() ] for name in files: path = current_path / name if path.is_symlink() or path.suffix.lower() not in STYLES: continue try: if path.stat().st_size > 2 * 1024 * 1024: continue if b"\x00" in path.read_bytes()[:2048]: continue except OSError: continue yield path def header_lines(style: str, license_name: str, holder: str, year: int) -> list[str]: return [ f"{style} SPDX-License-Identifier: {license_name}\n", f"{style} Copyright (c) {year} {holder}\n", ] def has_spdx(text: str) -> bool: return "SPDX-License-Identifier" in "\n".join(text.splitlines()[:10]) def main() -> int: parser = argparse.ArgumentParser(description="Добавить SPDX-заголовки") parser.add_argument("--path", type=Path, default=Path("."), help="Папка проекта") parser.add_argument( "--license", default="MIT", choices=["MIT", "Apache-2.0", "GPL-3.0", "BSD-3-Clause"], help="Идентификатор лицензии", ) parser.add_argument("--holder", required=True, help="Владелец авторских прав") parser.add_argument("--year", type=int, default=date.today().year, help="Год") parser.add_argument("--apply", action="store_true", help="Записать заголовки") args = parser.parse_args() root = args.path.expanduser().resolve() if not root.is_dir(): print(f"Папка не найдена: {root}") return 2 if not args.holder.strip(): print("Параметр --holder не должен быть пустым.") return 2 existing = 0 missing = [] for path in iter_files(root): try: text = path.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): continue if has_spdx(text): existing += 1 continue missing.append(path) print(f"Файлов с заголовком: {existing}") print(f"Файлов без заголовка: {len(missing)}") if not missing: return 0 for path in missing[:100]: print(f" {path.relative_to(root)}") if len(missing) > 100: print(f" ... ещё {len(missing) - 100}") if not args.apply: print("Это предпросмотр. Для добавления заголовков используйте --apply.") return 0 changed = 0 for path in missing: try: text = path.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): print(f"Пропуск {path}: не удалось прочитать как UTF-8.") continue style = STYLES[path.suffix.lower()] header = "".join(header_lines(style, args.license, args.holder.strip(), args.year)) lines = text.splitlines(keepends=True) if lines and lines[0].startswith("#!"): new_text = lines[0] if not new_text.endswith("\n"): new_text += "\n" new_text += header + "".join(lines[1:]) else: new_text = header + text path.write_text(new_text, encoding="utf-8") changed += 1 print(f"Обновлено файлов: {changed}") return 0 if __name__ == "__main__": raise SystemExit(main())