| #!/usr/bin/env python3 | |
| ############################################################################ | |
| # tools/checkspdx.py | |
| # | |
| # SPDX-License-Identifier: Apache-2.0 | |
| # | |
| # Licensed to the Apache Software Foundation (ASF) under one or more | |
| # contributor license agreements. See the NOTICE file distributed with | |
| # this work for additional information regarding copyright ownership. The | |
| # ASF licenses this file to you under the Apache License, Version 2.0 (the | |
| # "License"); you may not use this file except in compliance with the | |
| # License. You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | |
| # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | |
| # License for the specific language governing permissions and limitations | |
| # under the License. | |
| # | |
| ############################################################################ | |
| """Check that a source file header has SPDX-License-Identifier and license text.""" | |
| import os | |
| import re | |
| import sys | |
| import tempfile | |
| import unittest | |
| from contextlib import redirect_stdout | |
| from io import StringIO | |
| HEADER_BYTES = 8192 | |
| CHECKED_EXT = { | |
| ".c", | |
| ".h", | |
| ".cpp", | |
| ".cxx", | |
| ".cc", | |
| ".hpp", | |
| ".hxx", | |
| ".S", | |
| ".s", | |
| ".asm", | |
| ".py", | |
| ".sh", | |
| ".bash", | |
| ".bat", | |
| ".mk", | |
| ".cmake", | |
| ".rs", | |
| ".ld", | |
| ".lds", | |
| } | |
| CHECKED_NAMES = { | |
| "Makefile", | |
| "Make.defs", | |
| "CMakeLists.txt", | |
| "Kconfig", | |
| "Kconfig.host", | |
| } | |
| SPDX_RE = re.compile( | |
| r"SPDX-License-Identifier:\s*" | |
| r"([A-Za-z0-9.+-]+(?:\s+(?:OR|AND|WITH)\s+[A-Za-z0-9.+-]+)*)", | |
| re.IGNORECASE, | |
| ) | |
| APACHE_MARKERS = ( | |
| "licensed to the apache software foundation", | |
| "licensed under the apache license", | |
| "licensed as apache", | |
| "apache license", | |
| "asf licenses this file", | |
| ) | |
| BSD_MARKERS = ( | |
| "redistribution and use", | |
| "bsd license", | |
| "freebsd license", | |
| ) | |
| MIT_MARKERS = ("permission is hereby granted",) | |
| ISC_MARKERS = ( | |
| "permission to use, copy, and modify", | |
| "permission to use, copy, modify", | |
| "permission to use, copy", | |
| ) | |
| PUBLIC_DOMAIN_MARKERS = ( | |
| "public domain", | |
| "unlicense", | |
| "this software is provided", | |
| ) | |
| ZLIB_MARKERS = ( | |
| "this software is provided 'as-is'", | |
| 'this software is provided "as-is"', | |
| ) | |
| GENERIC_MARKERS = ( | |
| "licensed to the apache software foundation", | |
| "licensed under the apache license", | |
| "licensed as apache", | |
| "apache license", | |
| "redistribution and use", | |
| "bsd license", | |
| "freebsd license", | |
| "permission is hereby granted", | |
| "permission to use, copy", | |
| "permission is granted", | |
| "public domain", | |
| "unlicense", | |
| "this software is provided", | |
| "free for commercial", | |
| "without any express or implied warranty", | |
| "without warranty of any kind", | |
| "asf licenses this file", | |
| ) | |
| def should_check(path): | |
| """Return True if path is a source, script, or make file we must check.""" | |
| if not path or path in ("/dev/null", "nul", "NUL"): | |
| return False | |
| if not os.path.isfile(path): | |
| return False | |
| if os.path.getsize(path) == 0: | |
| return False | |
| name = os.path.basename(path) | |
| if name in CHECKED_NAMES: | |
| return True | |
| ext = os.path.splitext(name)[1] | |
| return ext in CHECKED_EXT | |
| def read_header(path): | |
| """Read the start of a text file. Return (text, lines) or (None, None).""" | |
| try: | |
| with open(path, "rb") as handle: | |
| data = handle.read(HEADER_BYTES) | |
| except OSError as err: | |
| print(f"{path}:1:1: error: Cannot read file: {err}") | |
| return None, None | |
| if b"\0" in data: | |
| return "", [] | |
| text = data.decode("utf-8", "replace") | |
| return text, text.splitlines() | |
| def find_spdx(lines): | |
| """Return (lineno, identifier) for the first SPDX tag, or (None, None).""" | |
| for index, line in enumerate(lines, start=1): | |
| match = SPDX_RE.search(line) | |
| if match: | |
| return index, match.group(1).strip() | |
| return None, None | |
| def header_has_marker(header_lc, markers): | |
| """Return True if any marker appears in the lower-cased header.""" | |
| return any(marker in header_lc for marker in markers) | |
| def strip_spdx_tags(header): | |
| """Remove SPDX tag lines so the identifier itself is not treated as text.""" | |
| kept = [] | |
| for line in header.splitlines(): | |
| if "SPDX-" in line: | |
| continue | |
| kept.append(line) | |
| return "\n".join(kept) | |
| def has_clear_text_license(header, spdx_id): | |
| """Return True if the header contains human-readable license text.""" | |
| header_lc = strip_spdx_tags(header).lower() | |
| ident = spdx_id.lower() | |
| tokens = ident.replace("(", " ").replace(")", " ").split() | |
| matched = False | |
| if "apache-2.0" in ident: | |
| matched = header_has_marker(header_lc, APACHE_MARKERS) | |
| elif ident.startswith("bsd") or ident.endswith("-uc"): | |
| matched = header_has_marker(header_lc, BSD_MARKERS) | |
| elif "mit" in tokens: | |
| matched = header_has_marker(header_lc, MIT_MARKERS) | |
| elif ident in ("isc", "oar") or "isc" in tokens: | |
| matched = header_has_marker(header_lc, ISC_MARKERS) | |
| elif ( | |
| "publicdomain" in ident.replace("-", "") | |
| or "unlicense" in ident | |
| or ident == "0bsd" | |
| ): | |
| matched = header_has_marker(header_lc, PUBLIC_DOMAIN_MARKERS) | |
| elif ident == "zlib": | |
| matched = header_has_marker(header_lc, ZLIB_MARKERS) | |
| if matched: | |
| return True | |
| return header_has_marker(header_lc, GENERIC_MARKERS) | |
| def check_file(path): | |
| """Check one file. Return 0 on success or skip, 1 on a license error.""" | |
| if not should_check(path): | |
| return 0 | |
| text, lines = read_header(path) | |
| if text is None: | |
| return 1 | |
| if text == "" and lines == []: | |
| return 0 | |
| lineno, spdx_id = find_spdx(lines) | |
| if not spdx_id: | |
| print(f"{path}:1:1: error: Missing SPDX-License-Identifier in the file header") | |
| return 1 | |
| if not has_clear_text_license(text, spdx_id): | |
| print( | |
| f"{path}:{lineno}:1: error: Missing clear-text license for " | |
| f"SPDX-License-Identifier: {spdx_id}" | |
| ) | |
| return 1 | |
| return 0 | |
| class SelfTests(unittest.TestCase): | |
| """Built-in checks for the SPDX and clear-text license rules.""" | |
| def write_temp(self, name, content): | |
| path = os.path.join(self.tmpdir, name) | |
| os.makedirs(os.path.dirname(path), exist_ok=True) | |
| with open(path, "w", encoding="utf-8") as handle: | |
| handle.write(content) | |
| return path | |
| def setUp(self): | |
| self._ctx = tempfile.TemporaryDirectory() | |
| self.tmpdir = self._ctx.name | |
| def tearDown(self): | |
| self._ctx.cleanup() | |
| def test_apache_c_passes(self): | |
| path = self.write_temp( | |
| "ok.c", | |
| "/*\n" | |
| " * SPDX-License-Identifier: Apache-2.0\n" | |
| " *\n" | |
| " * Licensed to the Apache Software Foundation (ASF) under one or more\n" | |
| " * contributor license agreements.\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_missing_spdx_fails(self): | |
| path = self.write_temp( | |
| "nospdx.c", | |
| "/*\n" | |
| " * Licensed to the Apache Software Foundation (ASF) under one or more\n" | |
| " */\n", | |
| ) | |
| with redirect_stdout(StringIO()): | |
| self.assertEqual(check_file(path), 1) | |
| def test_spdx_without_text_fails(self): | |
| path = self.write_temp( | |
| "notext.c", | |
| "/*\n * SPDX-License-Identifier: Apache-2.0\n */\n", | |
| ) | |
| with redirect_stdout(StringIO()): | |
| self.assertEqual(check_file(path), 1) | |
| def test_bsd_passes(self): | |
| path = self.write_temp( | |
| "bsd.h", | |
| "/*\n" | |
| " * SPDX-License-Identifier: BSD-3-Clause\n" | |
| " * Redistribution and use in source and binary forms, with or without\n" | |
| " * modification, are permitted provided that the following conditions\n" | |
| " * are met:\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_public_domain_passes(self): | |
| path = self.write_temp( | |
| "pd.c", | |
| "/*\n" | |
| " * SPDX-License-Identifier: LicenseRef-NuttX-PublicDomain\n" | |
| " * 100% Public Domain\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_skips_markdown(self): | |
| path = self.write_temp("README.md", "no license here\n") | |
| self.assertEqual(check_file(path), 0) | |
| def test_skips_empty(self): | |
| path = self.write_temp("empty.c", "") | |
| self.assertEqual(check_file(path), 0) | |
| def test_makefile_passes(self): | |
| path = self.write_temp( | |
| "Makefile", | |
| "# SPDX-License-Identifier: Apache-2.0\n" | |
| "# Licensed to the Apache Software Foundation (ASF) under one or more\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_python_shebang_passes(self): | |
| path = self.write_temp( | |
| "tool.py", | |
| "#!/usr/bin/env python3\n" | |
| "# SPDX-License-Identifier: Apache-2.0\n" | |
| '# Licensed under the Apache License, Version 2.0 (the "License");\n', | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_bsd_license_phrase_passes(self): | |
| path = self.write_temp( | |
| "bsd2.c", | |
| "/*\n" | |
| " * SPDX-License-Identifier: BSD\n" | |
| " * subject to the terms and conditions of the BSD License.\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_llvm_apache_passes(self): | |
| path = self.write_temp( | |
| "llvm.h", | |
| "/*\n" | |
| " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n" | |
| " * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_spdx_bsd_with_apache_text_passes(self): | |
| path = self.write_temp( | |
| "dual.S", | |
| "/*\n" | |
| " * Licensed to the Apache Software Foundation (ASF) under one or more\n" | |
| " * SPDX-License-Identifier: BSD-2-Clause\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def test_zerobsd_as_is_passes(self): | |
| path = self.write_temp( | |
| "zero.c", | |
| "/*\n" | |
| " * SPDX-License-Identifier: 0BSD\n" | |
| " * THIS SOFTWARE IS PROVIDED BY NXP AS IS AND ANY EXPRESSED OR\n" | |
| " */\n", | |
| ) | |
| self.assertEqual(check_file(path), 0) | |
| def main(argv=None): | |
| argv = list(sys.argv[1:] if argv is None else argv) | |
| if not argv or "-h" in argv or "--help" in argv: | |
| print("Usage: checkspdx.py FILE...") | |
| print(" checkspdx.py --selftest") | |
| return 0 if argv and ("-h" in argv or "--help" in argv) else 1 | |
| if argv == ["--selftest"]: | |
| suite = unittest.defaultTestLoader.loadTestsFromTestCase(SelfTests) | |
| result = unittest.TextTestRunner(verbosity=1).run(suite) | |
| return 0 if result.wasSuccessful() else 1 | |
| fail = 0 | |
| for path in argv: | |
| fail |= check_file(path) | |
| return fail | |
| if __name__ == "__main__": | |
| sys.exit(main()) |