|
| 1 | + |
| 2 | +"""This script checks for the presence of an SPDX-License-Identifier in the comments of source files.""" |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import re |
| 7 | +from collections.abc import Sequence |
| 8 | + |
| 9 | + |
| 10 | +def _load_file(file_path: str) -> str: |
| 11 | + try: |
| 12 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 13 | + return f.read() |
| 14 | + except Exception as e: |
| 15 | + print(f"Error loading file content of {file_path}: {e}") |
| 16 | + |
| 17 | + |
| 18 | +def _check_spdx(file_content: str) -> bool: |
| 19 | + for line in file_content: |
| 20 | + stripped_line = line.strip() |
| 21 | + if stripped_line.startswith("#") or stripped_line.startswith("//") or re.match(r"^\s*/\*", stripped_line): |
| 22 | + if "SPDX-License-Identifier:" in stripped_line: |
| 23 | + return True |
| 24 | + else: |
| 25 | + break |
| 26 | + |
| 27 | + |
| 28 | +def check_spdx(file_paths: list[str]) -> int: |
| 29 | + """ |
| 30 | + Check if the given files contain an SPDX license identifier. |
| 31 | +
|
| 32 | + Args: |
| 33 | + file_paths (list of str): List of file paths to check. |
| 34 | +
|
| 35 | + Returns: |
| 36 | + int: Returns 0 if all files contain an SPDX license identifier, |
| 37 | + otherwise returns 1 if any file is missing the SPDX line. |
| 38 | + """ |
| 39 | + any_missing_spdx = False |
| 40 | + for file_path in file_paths: |
| 41 | + file_content = _load_file(file_path) |
| 42 | + if not file_content: |
| 43 | + return 1 |
| 44 | + |
| 45 | + if not _check_spdx(file_path): |
| 46 | + print(f"Missing SPDX line in {file_path}") |
| 47 | + any_missing_spdx = True |
| 48 | + |
| 49 | + if any_missing_spdx: |
| 50 | + return 1 |
| 51 | + return 0 |
| 52 | + |
| 53 | + |
| 54 | +def main(argv: Sequence[str] | None = None) -> int: |
| 55 | + parser = argparse.ArgumentParser(description=__doc__) |
| 56 | + parser.add_argument('filenames', nargs='*') |
| 57 | + args = parser.parse_args(argv) |
| 58 | + |
| 59 | + return check_spdx(args.filenames) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + raise SystemExit(main()) |
0 commit comments