-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathcheck_copyright_header.py
executable file
·83 lines (64 loc) · 2.49 KB
/
check_copyright_header.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD 3-Clause license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import os
import re
import sys
from typing import List
BASE_COPYRIGHT_TEXT = """Copyright (c) Meta Platforms, Inc. and affiliates.
All rights reserved.
This source code is licensed under the BSD 3-Clause license found in the
LICENSE file in the root directory of this source tree."""
EXTENSIONS = {".py", ".cu", ".h", ".cuh", ".sh", ".metal"}
PRIVACY_PATTERNS = [
r"Meta Platforms, Inc\. and affiliates",
r"Facebook, Inc(\.|,)? and its affiliates",
r"[0-9]{4}-present(\.|,)? Facebook",
r"[0-9]{4}(\.|,)? Facebook",
]
def get_copyright_header(file_ext: str) -> str:
if file_ext in {".cu", ".h", ".cuh", ".cpp", ".metal"}:
# C/C++ style files use // comments
return "\n".join(
"// " + line if line else "//" for line in BASE_COPYRIGHT_TEXT.split("\n")
)
else:
# Python and shell scripts use # comments
return "\n".join(
"# " + line if line else "#" for line in BASE_COPYRIGHT_TEXT.split("\n")
)
def has_copyright_header(content: str) -> bool:
# Check first 16 lines for privacy policy
first_16_lines = "\n".join(content.split("\n")[:16])
return any(re.search(pattern, first_16_lines) for pattern in PRIVACY_PATTERNS)
def add_copyright_header(filename: str) -> None:
with open(filename, "r") as f:
content = f.read()
if not has_copyright_header(content):
ext = os.path.splitext(filename)[1]
header = get_copyright_header(ext)
with open(filename, "w") as f:
f.write(header + "\n\n" + content)
def main(argv: List[str] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("filenames", nargs="*", help="Filenames to check")
args = parser.parse_args(argv)
retval = 0
for filename in args.filenames:
# Skip __init__.py files
if os.path.basename(filename) == "__init__.py":
continue
ext = os.path.splitext(filename)[1]
if ext in EXTENSIONS:
with open(filename, "r") as f:
content = f.read()
if not has_copyright_header(content):
print(f"Adding copyright header to {filename}")
add_copyright_header(filename)
retval = 1
return retval
if __name__ == "__main__":
sys.exit(main())