Debian Codegraph @

tools/distrib/check_copyright.py

raw
1 #!/usr/bin/env python3
2
3 # Copyright 2015 gRPC authors.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import argparse
18 import datetime
19 import os
20 import re
21 import subprocess
22 import sys
23
24 # find our home
25 ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
26 os.chdir(ROOT)
27
28 # parse command line
29 argp = argparse.ArgumentParser(description='copyright checker')
30 argp.add_argument('-o',
31 '--output',
32 default='details',
33 choices=['list', 'details'])
34 argp.add_argument('-s', '--skips', default=0, action='store_const', const=1)
35 argp.add_argument('-a', '--ancient', default=0, action='store_const', const=1)
36 argp.add_argument('--precommit', action='store_true')
37 argp.add_argument('--fix', action='store_true')
38 args = argp.parse_args()
39
40 # open the license text
41 with open('NOTICE.txt') as f:
42 LICENSE_NOTICE = f.read().splitlines()
43
44 # license format by file extension
45 # key is the file extension, value is a format string
46 # that given a line of license text, returns what should
47 # be in the file
48 LICENSE_PREFIX_RE = {
49 '.bat': r'@rem\s*',
50 '.c': r'\s*(?://|\*)\s*',
51 '.cc': r'\s*(?://|\*)\s*',
52 '.h': r'\s*(?://|\*)\s*',
53 '.m': r'\s*\*\s*',
54 '.mm': r'\s*\*\s*',
55 '.php': r'\s*\*\s*',
56 '.js': r'\s*\*\s*',
57 '.py': r'#\s*',
58 '.pyx': r'#\s*',
59 '.pxd': r'#\s*',
60 '.pxi': r'#\s*',
61 '.rb': r'#\s*',
62 '.sh': r'#\s*',
63 '.proto': r'//\s*',
64 '.cs': r'//\s*',
65 '.mak': r'#\s*',
66 '.bazel': r'#\s*',
67 '.bzl': r'#\s*',
68 'Makefile': r'#\s*',
69 'Dockerfile': r'#\s*',
70 'BUILD': r'#\s*',
71 }
72
73 # The key is the file extension, while the value is a tuple of fields
74 # (header, prefix, footer).
75 # For example, for javascript multi-line comments, the header will be '/*', the
76 # prefix will be '*' and the footer will be '*/'.
77 # If header and footer are irrelevant for a specific file extension, they are
78 # set to None.
79 LICENSE_PREFIX_TEXT = {
80 '.bat': (None, '@rem', None),
81 '.c': (None, '//', None),
82 '.cc': (None, '//', None),
83 '.h': (None, '//', None),
84 '.m': ('/**', ' *', ' */'),
85 '.mm': ('/**', ' *', ' */'),
86 '.php': ('/**', ' *', ' */'),
87 '.js': ('/**', ' *', ' */'),
88 '.py': (None, '#', None),
89 '.pyx': (None, '#', None),
90 '.pxd': (None, '#', None),
91 '.pxi': (None, '#', None),
92 '.rb': (None, '#', None),
93 '.sh': (None, '#', None),
94 '.proto': (None, '//', None),
95 '.cs': (None, '//', None),
96 '.mak': (None, '#', None),
97 '.bazel': (None, '#', None),
98 '.bzl': (None, '#', None),
99 'Makefile': (None, '#', None),
100 'Dockerfile': (None, '#', None),
101 'BUILD': (None, '#', None),
102 }
103
104 _EXEMPT = frozenset((
105 # Generated protocol compiler output.
106 'examples/python/helloworld/helloworld_pb2.py',
107 'examples/python/helloworld/helloworld_pb2_grpc.py',
108 'examples/python/multiplex/helloworld_pb2.py',
109 'examples/python/multiplex/helloworld_pb2_grpc.py',
110 'examples/python/multiplex/route_guide_pb2.py',
111 'examples/python/multiplex/route_guide_pb2_grpc.py',
112 'examples/python/route_guide/route_guide_pb2.py',
113 'examples/python/route_guide/route_guide_pb2_grpc.py',
114
115 # Generated doxygen config file
116 'tools/doxygen/Doxyfile.php',
117
118 # An older file originally from outside gRPC.
119 'src/php/tests/bootstrap.php',
120 # census.proto copied from github
121 'tools/grpcz/census.proto',
122 # status.proto copied from googleapis
123 'src/proto/grpc/status/status.proto',
124
125 # Gradle wrappers used to build for Android
126 'examples/android/helloworld/gradlew.bat',
127 'src/android/test/interop/gradlew.bat',
128
129 # Designer-generated source
130 'examples/csharp/HelloworldXamarin/Droid/Resources/Resource.designer.cs',
131 'examples/csharp/HelloworldXamarin/iOS/ViewController.designer.cs',
132
133 # BoringSSL generated header. It has commit version information at the head
134 # of the file so we cannot check the license info.
135 'src/boringssl/boringssl_prefix_symbols.h',
136 ))
137
138 RE_YEAR = r'Copyright (?P<first_year>[0-9]+\-)?(?P<last_year>[0-9]+) ([Tt]he )?gRPC [Aa]uthors(\.|)'
139 RE_LICENSE = dict(
140 (k, r'\n'.join(LICENSE_PREFIX_RE[k] +
141 (RE_YEAR if re.search(RE_YEAR, line) else re.escape(line))
142 for line in LICENSE_NOTICE))
143 for k, v in list(LICENSE_PREFIX_RE.items()))
144
145 YEAR = datetime.datetime.now().year
146
147 LICENSE_YEAR = f'Copyright {YEAR} gRPC authors.'
148
149
150 def join_license_text(header, prefix, footer, notice):
151 text = (header + '\n') if header else ""
152
153 def add_prefix(prefix, line):
154 # Don't put whitespace between prefix and empty line to avoid having
155 # trailing whitespaces.
156 return prefix + ('' if len(line) == 0 else ' ') + line
157
158 text += '\n'.join(
159 add_prefix(prefix, (LICENSE_YEAR if re.search(RE_YEAR, line) else line))
160 for line in LICENSE_NOTICE)
161 text += '\n'
162 if footer:
163 text += footer + '\n'
164 return text
165
166
167 LICENSE_TEXT = dict(
168 (k,
169 join_license_text(LICENSE_PREFIX_TEXT[k][0], LICENSE_PREFIX_TEXT[k][1],
170 LICENSE_PREFIX_TEXT[k][2], LICENSE_NOTICE))
171 for k, v in list(LICENSE_PREFIX_TEXT.items()))
172
173 if args.precommit:
174 FILE_LIST_COMMAND = 'git status -z | grep -Poz \'(?<=^[MARC][MARCD ] )[^\s]+\''
175 else:
176 FILE_LIST_COMMAND = 'git ls-tree -r --name-only -r HEAD | ' \
177 'grep -v ^third_party/ |' \
178 'grep -v "\(ares_config.h\|ares_build.h\)"'
179
180
181 def load(name):
182 with open(name) as f:
183 return f.read()
184
185
186 def save(name, text):
187 with open(name, 'w') as f:
188 f.write(text)
189
190
191 assert (re.search(RE_LICENSE['Makefile'], load('Makefile')))
192
193
194 def log(cond, why, filename):
195 if not cond:
196 return
197 if args.output == 'details':
198 print(('%s: %s' % (why, filename)))
199 else:
200 print(filename)
201
202
203 def write_copyright(license_text, file_text, filename):
204 shebang = ""
205 lines = file_text.split("\n")
206 if lines and lines[0].startswith("#!"):
207 shebang = lines[0] + "\n"
208 file_text = file_text[len(shebang):]
209
210 rewritten_text = shebang + license_text + "\n" + file_text
211 with open(filename, 'w') as f:
212 f.write(rewritten_text)
213
214
215 # scan files, validate the text
216 ok = True
217 filename_list = []
218 try:
219 filename_list = subprocess.check_output(FILE_LIST_COMMAND,
220 shell=True).decode().splitlines()
221 except subprocess.CalledProcessError:
222 sys.exit(0)
223
224 for filename in filename_list:
225 if filename in _EXEMPT:
226 continue
227 # Skip check for upb generated code.
228 if (filename.endswith('.upb.h') or filename.endswith('.upb.c') or
229 filename.endswith('.upbdefs.h') or filename.endswith('.upbdefs.c')):
230 continue
231 ext = os.path.splitext(filename)[1]
232 base = os.path.basename(filename)
233 if ext in RE_LICENSE:
234 re_license = RE_LICENSE[ext]
235 license_text = LICENSE_TEXT[ext]
236 elif base in RE_LICENSE:
237 re_license = RE_LICENSE[base]
238 license_text = LICENSE_TEXT[base]
239 else:
240 log(args.skips, 'skip', filename)
241 continue
242 try:
243 text = load(filename)
244 except:
245 continue
246 m = re.search(re_license, text)
247 if m:
248 pass
249 elif 'DO NOT EDIT' not in text:
250 if args.fix:
251 write_copyright(license_text, text, filename)
252 log(1, 'copyright missing (fixed)', filename)
253 else:
254 log(1, 'copyright missing', filename)
255 ok = False
256
257 if not ok and not args.fix:
258 print(
259 'You may use following command to automatically fix copyright headers:')
260 print(' tools/distrib/check_copyright.py --fix')
261
262 sys.exit(0 if ok else 1)