check_copyright.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env python
  2. # Copyright (c) 2016 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Checks for copyright notices in all the files that need them under the
  16. current directory. Optionally insert them. When inserting, replaces
  17. an MIT or Khronos free use license with Apache 2.
  18. """
  19. from __future__ import print_function
  20. import argparse
  21. import fileinput
  22. import fnmatch
  23. import inspect
  24. import os
  25. import re
  26. import sys
  27. # List of designated copyright owners.
  28. AUTHORS = ['The Khronos Group Inc.',
  29. 'LunarG Inc.',
  30. 'Google Inc.',
  31. 'Google LLC',
  32. 'Pierre Moreau']
  33. CURRENT_YEAR='2019'
  34. YEARS = '(2014-2016|2015-2016|2016|2016-2017|2017|2018|2019)'
  35. COPYRIGHT_RE = re.compile(
  36. 'Copyright \(c\) {} ({})'.format(YEARS, '|'.join(AUTHORS)))
  37. MIT_BEGIN_RE = re.compile('Permission is hereby granted, '
  38. 'free of charge, to any person obtaining a')
  39. MIT_END_RE = re.compile('MATERIALS OR THE USE OR OTHER DEALINGS IN '
  40. 'THE MATERIALS.')
  41. APACHE2_BEGIN_RE = re.compile('Licensed under the Apache License, '
  42. 'Version 2.0 \(the "License"\);')
  43. APACHE2_END_RE = re.compile('limitations under the License.')
  44. LICENSED = """Licensed under the Apache License, Version 2.0 (the "License");
  45. you may not use this file except in compliance with the License.
  46. You may obtain a copy of the License at
  47. http://www.apache.org/licenses/LICENSE-2.0
  48. Unless required by applicable law or agreed to in writing, software
  49. distributed under the License is distributed on an "AS IS" BASIS,
  50. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  51. See the License for the specific language governing permissions and
  52. limitations under the License."""
  53. LICENSED_LEN = 10 # Number of lines in LICENSED
  54. def find(top, filename_glob, skip_glob_dir_list, skip_glob_files_list):
  55. """Returns files in the tree rooted at top matching filename_glob but not
  56. in directories matching skip_glob_dir_list nor files matching
  57. skip_glob_dir_list."""
  58. file_list = []
  59. for path, dirs, files in os.walk(top):
  60. for glob in skip_glob_dir_list:
  61. for match in fnmatch.filter(dirs, glob):
  62. dirs.remove(match)
  63. for filename in fnmatch.filter(files, filename_glob):
  64. full_file = os.path.join(path, filename)
  65. if full_file not in skip_glob_files_list:
  66. file_list.append(full_file)
  67. return file_list
  68. def filtered_descendants(glob):
  69. """Returns glob-matching filenames under the current directory, but skips
  70. some irrelevant paths."""
  71. return find('.', glob, ['third_party', 'external', 'CompilerIdCXX',
  72. 'build*', 'out*'], ['./utils/clang-format-diff.py'])
  73. def skip(line):
  74. """Returns true if line is all whitespace or shebang."""
  75. stripped = line.lstrip()
  76. return stripped == '' or stripped.startswith('#!')
  77. def comment(text, prefix):
  78. """Returns commented-out text.
  79. Each line of text will be prefixed by prefix and a space character. Any
  80. trailing whitespace will be trimmed.
  81. """
  82. accum = ['{} {}'.format(prefix, line).rstrip() for line in text.split('\n')]
  83. return '\n'.join(accum)
  84. def insert_copyright(author, glob, comment_prefix):
  85. """Finds all glob-matching files under the current directory and inserts the
  86. copyright message, and license notice. An MIT license or Khronos free
  87. use license (modified MIT) is replaced with an Apache 2 license.
  88. The copyright message goes into the first non-whitespace, non-shebang line
  89. in a file. The license notice follows it. Both are prefixed on each line
  90. by comment_prefix and a space.
  91. """
  92. copyright = comment('Copyright (c) {} {}'.format(CURRENT_YEAR, author),
  93. comment_prefix) + '\n\n'
  94. licensed = comment(LICENSED, comment_prefix) + '\n\n'
  95. for file in filtered_descendants(glob):
  96. # Parsing states are:
  97. # 0 Initial: Have not seen a copyright declaration.
  98. # 1 Seen a copyright line and no other interesting lines
  99. # 2 In the middle of an MIT or Khronos free use license
  100. # 9 Exited any of the above
  101. state = 0
  102. update_file = False
  103. for line in fileinput.input(file, inplace=1):
  104. emit = True
  105. if state is 0:
  106. if COPYRIGHT_RE.search(line):
  107. state = 1
  108. elif skip(line):
  109. pass
  110. else:
  111. # Didn't see a copyright. Inject copyright and license.
  112. sys.stdout.write(copyright)
  113. sys.stdout.write(licensed)
  114. # Assume there isn't a previous license notice.
  115. state = 1
  116. elif state is 1:
  117. if MIT_BEGIN_RE.search(line):
  118. state = 2
  119. emit = False
  120. elif APACHE2_BEGIN_RE.search(line):
  121. # Assume an Apache license is preceded by a copyright
  122. # notice. So just emit it like the rest of the file.
  123. state = 9
  124. elif state is 2:
  125. # Replace the MIT license with Apache 2
  126. emit = False
  127. if MIT_END_RE.search(line):
  128. state = 9
  129. sys.stdout.write(licensed)
  130. if emit:
  131. sys.stdout.write(line)
  132. def alert_if_no_copyright(glob, comment_prefix):
  133. """Prints names of all files missing either a copyright or Apache 2 license.
  134. Finds all glob-matching files under the current directory and checks if they
  135. contain the copyright message and license notice. Prints the names of all the
  136. files that don't meet both criteria.
  137. Returns the total number of file names printed.
  138. """
  139. printed_count = 0
  140. for file in filtered_descendants(glob):
  141. has_copyright = False
  142. has_apache2 = False
  143. line_num = 0
  144. apache_expected_end = 0
  145. with open(file) as contents:
  146. for line in contents:
  147. line_num += 1
  148. if COPYRIGHT_RE.search(line):
  149. has_copyright = True
  150. if APACHE2_BEGIN_RE.search(line):
  151. apache_expected_end = line_num + LICENSED_LEN
  152. if (line_num is apache_expected_end) and APACHE2_END_RE.search(line):
  153. has_apache2 = True
  154. if not (has_copyright and has_apache2):
  155. message = file
  156. if not has_copyright:
  157. message += ' has no copyright'
  158. if not has_apache2:
  159. message += ' has no Apache 2 license notice'
  160. print(message)
  161. printed_count += 1
  162. return printed_count
  163. class ArgParser(argparse.ArgumentParser):
  164. def __init__(self):
  165. super(ArgParser, self).__init__(
  166. description=inspect.getdoc(sys.modules[__name__]))
  167. self.add_argument('--update', dest='author', action='store',
  168. help='For files missing a copyright notice, insert '
  169. 'one for the given author, and add a license '
  170. 'notice. The author must be in the AUTHORS '
  171. 'list in the script.')
  172. def main():
  173. glob_comment_pairs = [('*.h', '//'), ('*.hpp', '//'), ('*.sh', '#'),
  174. ('*.py', '#'), ('*.cpp', '//'),
  175. ('CMakeLists.txt', '#')]
  176. argparser = ArgParser()
  177. args = argparser.parse_args()
  178. if args.author:
  179. if args.author not in AUTHORS:
  180. print('error: --update argument must be in the AUTHORS list in '
  181. 'check_copyright.py: {}'.format(AUTHORS))
  182. sys.exit(1)
  183. for pair in glob_comment_pairs:
  184. insert_copyright(args.author, *pair)
  185. sys.exit(0)
  186. else:
  187. count = sum([alert_if_no_copyright(*p) for p in glob_comment_pairs])
  188. sys.exit(count > 0)
  189. if __name__ == '__main__':
  190. main()