This is an automated email from the ASF dual-hosted git repository.
xiaoxiang781216 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git
The following commit(s) were added to refs/heads/master by this push:
new 43071e199be tools/checkpatch: Add SPDX and license text check.
43071e199be is described below
commit 43071e199be18cda85a6ce992cdb01a25bf3888b
Author: Shikha Bhadoria <[email protected]>
AuthorDate: Sun Nov 29 08:16:04 2026 +0000
tools/checkpatch: Add SPDX and license text check.
Require C, C++, make, script, and similar source files changed in a
pull request to contain both an SPDX-License-Identifier tag and the
license in clear text. Wire the check into checkpatch.sh so GitHub CI
enforces the file header rules from the coding standard.
Assisted-by: Cursor:Grok-4.6
Signed-off-by: Shikha Bhadoria <[email protected]>
---
Documentation/components/tools/checkpatch.rst | 11 +-
Documentation/contributing/coding_style.rst | 10 +-
tools/checkpatch.sh | 13 +
tools/checkspdx.py | 400 ++++++++++++++++++++++++++
4 files changed, 429 insertions(+), 5 deletions(-)
diff --git a/Documentation/components/tools/checkpatch.rst
b/Documentation/components/tools/checkpatch.rst
index 586c0c239af..52ae8daf23f 100644
--- a/Documentation/components/tools/checkpatch.rst
+++ b/Documentation/components/tools/checkpatch.rst
@@ -4,9 +4,12 @@
``checkpatch.sh``
=================
-``checkpatch.sh`` is a bash script that makes use of ``nxstyle`` and
-``codespell`` tools to format patches and ensure that files conform to NuttX
-coding standard. It is used in NuttX's GitHub CI.
+``checkpatch.sh`` is a bash script that makes use of ``nxstyle``,
+``codespell``, and ``checkspdx.py`` to format patches and ensure that
+files conform to the NuttX coding standard. ``checkspdx.py`` requires
+each C, C++, make, script, and similar source file to contain both an
+``SPDX-License-Identifier`` tag and the license in clear text. It is
+used in NuttX's GitHub CI.
Help message:
@@ -25,6 +28,8 @@ Help message:
-g <commit list>
-f <file list>
-x format supported files (only .py, requires: pip install black)
+ Each C, C++, make, script, and similar source file is also checked
+ for SPDX-License-Identifier and the license in clear text.
- read standard input mainly used by git pre-commit hook as below:
git diff --cached | ./tools/checkpatch.sh -
Where a <commit list> is any syntax supported by git for specifying git
revision, see GITREVISIONS(7)
diff --git a/Documentation/contributing/coding_style.rst
b/Documentation/contributing/coding_style.rst
index c2c39f21273..64f7724d55b 100644
--- a/Documentation/contributing/coding_style.rst
+++ b/Documentation/contributing/coding_style.rst
@@ -49,8 +49,10 @@ block comment, the following must appear:
- The relative path to the file from the top-level directory.
- An optional, one-line description of the file contents.
- A blank line
- - NuttX standard Apache 2.0 licensing information as provided in
- the `appendix <#appndxa>`__.
+ - An ``SPDX-License-Identifier`` tag
+ - The license in clear text: NuttX standard Apache 2.0 licensing
+ information as provided in the `appendix <#appndxa>`__, or a
+ compatible third-party license such as BSD or MIT
**Sample File Headers**. Sample file headers are provided in an
`Appendix <#appndxa>`__ to this document. No new software may be
@@ -2463,6 +2465,8 @@ C Source File Structure
* <Relative path to the file>
* <Optional one line file description>
*
+ * 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
@@ -2591,6 +2595,8 @@ C Header File Structure
* <Relative path to the file>
* <Optional one line file description>
*
+ * 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
diff --git a/tools/checkpatch.sh b/tools/checkpatch.sh
index 10bb3670ca2..f27119f99e3 100755
--- a/tools/checkpatch.sh
+++ b/tools/checkpatch.sh
@@ -45,6 +45,7 @@ isort_warning_once=0
cvt2utf_warning_once=0
codespell_config_file_location_was_shown_once=0
+spdx_warning_once=0
# links
COMMIT_URL="https://github.com/apache/nuttx/blob/master/CONTRIBUTING.md"
@@ -67,6 +68,8 @@ usage() {
echo " Use --stdin with -p to read patch content from stdin."
echo "-f <file list>"
echo "-x format supported files (only .py, requires: pip install black)"
+ echo "Each C, C++, make, script, and similar source file is also checked"
+ echo "for SPDX-License-Identifier and the license in clear text."
echo "- read standard input mainly used by git pre-commit hook as below:"
echo " git diff --cached | ./tools/checkpatch.sh -"
echo "Where a <commit list> is any syntax supported by git for specifying
git revision, see GITREVISIONS(7)"
@@ -250,6 +253,16 @@ check_file() {
fi
fi
fi
+
+ if ! command -v python3 &> /dev/null; then
+ if [ $spdx_warning_once == 0 ]; then
+ echo -e "\npython3 not found, required for SPDX license check"
+ spdx_warning_once=1
+ fi
+ fail=1
+ elif ! python3 "$TOOLDIR/checkspdx.py" "${@: -1}"; then
+ fail=1
+ fi
}
check_ranges() {
diff --git a/tools/checkspdx.py b/tools/checkspdx.py
new file mode 100755
index 00000000000..b80b7294de8
--- /dev/null
+++ b/tools/checkspdx.py
@@ -0,0 +1,400 @@
+#!/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())