Imported Upstream version 1.27.0
[platform/upstream/grpc.git] / tools / distrib / check_copyright.py
1 #!/usr/bin/env python2.7
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 sys
22 import subprocess
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', default=False, action='store_true')
37 args = argp.parse_args()
38
39 # open the license text
40 with open('NOTICE.txt') as f:
41     LICENSE_NOTICE = f.read().splitlines()
42
43 # license format by file extension
44 # key is the file extension, value is a format string
45 # that given a line of license text, returns what should
46 # be in the file
47 LICENSE_PREFIX = {
48     '.bat': r'@rem\s*',
49     '.c': r'\s*(?://|\*)\s*',
50     '.cc': r'\s*(?://|\*)\s*',
51     '.h': r'\s*(?://|\*)\s*',
52     '.m': r'\s*\*\s*',
53     '.mm': r'\s*\*\s*',
54     '.php': r'\s*\*\s*',
55     '.js': r'\s*\*\s*',
56     '.py': r'#\s*',
57     '.pyx': r'#\s*',
58     '.pxd': r'#\s*',
59     '.pxi': r'#\s*',
60     '.rb': r'#\s*',
61     '.sh': r'#\s*',
62     '.proto': r'//\s*',
63     '.cs': r'//\s*',
64     '.mak': r'#\s*',
65     'Makefile': r'#\s*',
66     'Dockerfile': r'#\s*',
67     'BUILD': r'#\s*',
68 }
69
70 _EXEMPT = frozenset((
71     # Generated protocol compiler output.
72     'examples/python/helloworld/helloworld_pb2.py',
73     'examples/python/helloworld/helloworld_pb2_grpc.py',
74     'examples/python/multiplex/helloworld_pb2.py',
75     'examples/python/multiplex/helloworld_pb2_grpc.py',
76     'examples/python/multiplex/route_guide_pb2.py',
77     'examples/python/multiplex/route_guide_pb2_grpc.py',
78     'examples/python/route_guide/route_guide_pb2.py',
79     'examples/python/route_guide/route_guide_pb2_grpc.py',
80
81     # An older file originally from outside gRPC.
82     'src/php/tests/bootstrap.php',
83     # census.proto copied from github
84     'tools/grpcz/census.proto',
85     # status.proto copied from googleapis
86     'src/proto/grpc/status/status.proto',
87
88     # Gradle wrappers used to build for Android
89     'examples/android/helloworld/gradlew.bat',
90     'src/android/test/interop/gradlew.bat',
91
92     # Designer-generated source
93     'examples/csharp/HelloworldXamarin/Droid/Resources/Resource.designer.cs',
94     'examples/csharp/HelloworldXamarin/iOS/ViewController.designer.cs',
95 ))
96
97 RE_YEAR = r'Copyright (?P<first_year>[0-9]+\-)?(?P<last_year>[0-9]+) ([Tt]he )?gRPC [Aa]uthors(\.|)'
98 RE_LICENSE = dict(
99     (k, r'\n'.join(LICENSE_PREFIX[k] +
100                    (RE_YEAR if re.search(RE_YEAR, line) else re.escape(line))
101                    for line in LICENSE_NOTICE))
102     for k, v in LICENSE_PREFIX.iteritems())
103
104 if args.precommit:
105     FILE_LIST_COMMAND = 'git status -z | grep -Poz \'(?<=^[MARC][MARCD ] )[^\s]+\''
106 else:
107     FILE_LIST_COMMAND = 'git ls-tree -r --name-only -r HEAD | ' \
108                         'grep -v ^third_party/ |' \
109                         'grep -v "\(ares_config.h\|ares_build.h\)"'
110
111
112 def load(name):
113     with open(name) as f:
114         return f.read()
115
116
117 def save(name, text):
118     with open(name, 'w') as f:
119         f.write(text)
120
121
122 assert (re.search(RE_LICENSE['Makefile'], load('Makefile')))
123
124
125 def log(cond, why, filename):
126     if not cond: return
127     if args.output == 'details':
128         print '%s: %s' % (why, filename)
129     else:
130         print filename
131
132
133 # scan files, validate the text
134 ok = True
135 filename_list = []
136 try:
137     filename_list = subprocess.check_output(FILE_LIST_COMMAND,
138                                             shell=True).splitlines()
139 except subprocess.CalledProcessError:
140     sys.exit(0)
141
142 for filename in filename_list:
143     if filename in _EXEMPT:
144         continue
145     # Skip check for upb generated code.
146     if filename.endswith('.upb.h') or filename.endswith('.upb.c'):
147         continue
148     ext = os.path.splitext(filename)[1]
149     base = os.path.basename(filename)
150     if ext in RE_LICENSE:
151         re_license = RE_LICENSE[ext]
152     elif base in RE_LICENSE:
153         re_license = RE_LICENSE[base]
154     else:
155         log(args.skips, 'skip', filename)
156         continue
157     try:
158         text = load(filename)
159     except:
160         continue
161     m = re.search(re_license, text)
162     if m:
163         pass
164     elif 'DO NOT EDIT' not in text and filename not in [
165             'src/boringssl/err_data.c', 'src/boringssl/crypto_test_data.cc'
166     ]:
167         log(1, 'copyright missing', filename)
168         ok = False
169
170 sys.exit(0 if ok else 1)