boilerplate.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #!/usr/bin/env python
  2. # Copyright 2015 The Kubernetes Authors.
  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. from __future__ import print_function
  16. import argparse
  17. import glob
  18. import json
  19. import mmap
  20. import os
  21. import re
  22. import sys
  23. parser = argparse.ArgumentParser()
  24. parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*')
  25. rootdir = os.path.dirname(__file__) + "/../../"
  26. rootdir = os.path.abspath(rootdir)
  27. parser.add_argument("--rootdir", default=rootdir, help="root directory to examine")
  28. default_boilerplate_dir = os.path.join(rootdir, "hack/boilerplate")
  29. parser.add_argument("--boilerplate-dir", default=default_boilerplate_dir)
  30. args = parser.parse_args()
  31. def get_refs():
  32. refs = {}
  33. for path in glob.glob(os.path.join(args.boilerplate_dir, "boilerplate.*.txt")):
  34. extension = os.path.basename(path).split(".")[1]
  35. ref_file = open(path, 'r')
  36. ref = ref_file.read().splitlines()
  37. ref_file.close()
  38. refs[extension] = ref
  39. return refs
  40. def file_passes(filename, refs, regexs):
  41. try:
  42. f = open(filename, 'r')
  43. except:
  44. return False
  45. data = f.read()
  46. f.close()
  47. basename = os.path.basename(filename)
  48. extension = file_extension(filename)
  49. if extension != "":
  50. ref = refs[extension]
  51. else:
  52. ref = refs[basename]
  53. # remove build tags from the top of Go files
  54. if extension == "go":
  55. p = regexs["go_build_constraints"]
  56. (data, found) = p.subn("", data, 1)
  57. # remove shebang from the top of shell files
  58. if extension == "sh":
  59. p = regexs["shebang"]
  60. (data, found) = p.subn("", data, 1)
  61. data = data.splitlines()
  62. # if our test file is smaller than the reference it surely fails!
  63. if len(ref) > len(data):
  64. return False
  65. # trim our file to the same number of lines as the reference file
  66. data = data[:len(ref)]
  67. p = regexs["year"]
  68. for d in data:
  69. if p.search(d):
  70. return False
  71. # Replace all occurrences of the regex "2016|2015|2014" with "YEAR"
  72. p = regexs["date"]
  73. for i, d in enumerate(data):
  74. (data[i], found) = p.subn('YEAR', d)
  75. if found != 0:
  76. break
  77. # if we don't match the reference at this point, fail
  78. if ref != data:
  79. return False
  80. return True
  81. def file_extension(filename):
  82. return os.path.splitext(filename)[1].split(".")[-1].lower()
  83. skipped_dirs = ['Godeps', 'third_party', '_gopath', '_output', '.git', 'cluster/env.sh', "vendor", "test/e2e/generated/bindata.go"]
  84. def normalize_files(files):
  85. newfiles = []
  86. for pathname in files:
  87. if any(x in pathname for x in skipped_dirs):
  88. continue
  89. newfiles.append(pathname)
  90. for i, pathname in enumerate(newfiles):
  91. if not os.path.isabs(pathname):
  92. newfiles[i] = os.path.join(args.rootdir, pathname)
  93. return newfiles
  94. def get_files(extensions):
  95. files = []
  96. if len(args.filenames) > 0:
  97. files = args.filenames
  98. else:
  99. for root, dirs, walkfiles in os.walk(args.rootdir):
  100. # don't visit certain dirs. This is just a performance improvement
  101. # as we would prune these later in normalize_files(). But doing it
  102. # cuts down the amount of filesystem walking we do and cuts down
  103. # the size of the file list
  104. for d in skipped_dirs:
  105. if d in dirs:
  106. dirs.remove(d)
  107. for name in walkfiles:
  108. pathname = os.path.join(root, name)
  109. files.append(pathname)
  110. files = normalize_files(files)
  111. outfiles = []
  112. for pathname in files:
  113. basename = os.path.basename(pathname)
  114. extension = file_extension(pathname)
  115. if extension in extensions or basename in extensions:
  116. outfiles.append(pathname)
  117. return outfiles
  118. def get_regexs():
  119. regexs = {}
  120. # Search for "YEAR" which exists in the boilerplate, but shouldn't in the real thing
  121. regexs["year"] = re.compile( 'YEAR' )
  122. # dates can be 2014, 2015 or 2016, company holder names can be anything
  123. regexs["date"] = re.compile( '(2014|2015|2016)' )
  124. # strip // +build \n\n build constraints
  125. regexs["go_build_constraints"] = re.compile(r"^(// \+build.*\n)+\n", re.MULTILINE)
  126. # strip #!.* from shell scripts
  127. regexs["shebang"] = re.compile(r"^(#!.*\n)\n*", re.MULTILINE)
  128. return regexs
  129. def main():
  130. regexs = get_regexs()
  131. refs = get_refs()
  132. filenames = get_files(refs.keys())
  133. for filename in filenames:
  134. if not file_passes(filename, refs, regexs):
  135. print(filename, file=sys.stdout)
  136. if __name__ == "__main__":
  137. sys.exit(main())