# SPDX-License-Identifier: MIT """Add the SPDX header to every tracked file that lacks one; --check only reports. python -I scripts/spdx_headers.py # add missing headers python -I scripts/spdx_headers.py --check # exit 1 if any file lacks one JSON has no comments: JSON files are listed, never edited (their licence is the repository's, LICENSE). """ from __future__ import annotations import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] TAG = "SPDX-License-Identifier: MIT" STYLES = { ".py": "# {}\n", ".toml": "# {}\n", ".md": "\n", ".vhd": "-- {}\n", ".gitignore": "# {}\n", ".sh": "# {}\n", } def tracked() -> list[Path]: out = subprocess.run( ["git", "-C", str(ROOT), "ls-files", "--cached", "--others", "--exclude-standard"], capture_output=True, text=True, check=True, ).stdout # fmt: skip return [ROOT / line for line in out.splitlines() if line] def main() -> int: check = "--check" in sys.argv missing = [] for path in tracked(): if path.name in ("LICENSE", "NOTICE") or not path.is_file(): continue key = path.name if path.name.startswith(".") else path.suffix style = STYLES.get(key) text = path.read_text(encoding="utf-8") if TAG in text[:400]: continue if style is None: print(f"no header style (licence by LICENSE): {path.relative_to(ROOT)}") continue missing.append(path) if not check: line = style.format(TAG) if text.startswith("#!"): first, _, rest = text.partition("\n") path.write_text(f"{first}\n{line}{rest}", encoding="utf-8") else: path.write_text(line + text, encoding="utf-8") for path in missing: print(("missing: " if check else "added: ") + str(path.relative_to(ROOT))) return 1 if check and missing else 0 if __name__ == "__main__": sys.exit(main())