Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2a94c3b

Browse files
committedJan 31, 2025·
Check for SPDX headers using pre-commit
Signed-off-by: Russell Bryant <[email protected]>
1 parent 14c2986 commit 2a94c3b

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed
 

‎.pre-commit-config.yaml

+5-1
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,8 @@ repos:
103103
language: system
104104
verbose: true
105105
pass_filenames: false
106-
106+
- id: check-spdx-header
107+
name: Check SPDX headers
108+
entry: python tools/check_spdx_header.py
109+
language: python
110+
types: [python]

‎tools/check_spdx_header.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# SPDX-License-Identifier: Apache-2.0
2+
3+
import sys
4+
5+
SPDX_HEADER = "# SPDX-License-Identifier: Apache-2.0"
6+
SPDX_HEADER_PREFIX = "# SPDX-License-Identifier:"
7+
8+
9+
def check_spdx_header(file_path):
10+
with open(file_path, encoding='UTF-8') as file:
11+
lines = file.readlines()
12+
if not lines:
13+
# not necessary for an empty file like __init__.py
14+
return True
15+
if not lines[0].strip().startswith(SPDX_HEADER_PREFIX):
16+
return False
17+
return True
18+
19+
20+
def add_header(file_path):
21+
with open(file_path, 'r+', encoding='UTF-8') as file:
22+
lines = file.readlines()
23+
file.seek(0, 0)
24+
file.write(SPDX_HEADER + '\n\n' + ''.join(lines))
25+
26+
27+
def main():
28+
files_with_missing_header = []
29+
for file_path in sys.argv[1:]:
30+
if not check_spdx_header(file_path):
31+
files_with_missing_header.append(file_path)
32+
33+
if files_with_missing_header:
34+
print("The following files are missing the SPDX header:")
35+
for file_path in files_with_missing_header:
36+
print(f" {file_path}")
37+
add_header(file_path)
38+
39+
sys.exit(1 if files_with_missing_header else 0)
40+
41+
42+
if __name__ == "__main__":
43+
main()

0 commit comments

Comments
 (0)
Please sign in to comment.