check_copyright.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #-------------------------------------------------------------------------------------------------------
  2. # Copyright (C) Microsoft. All rights reserved.
  3. # Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. #-------------------------------------------------------------------------------------------------------
  5. # Python 2.7 and 3.x compatibility for easier testing regardless of python installation
  6. from __future__ import print_function
  7. import sys
  8. import os.path
  9. import re
  10. copyright_lines = [
  11. r'-------------------------------------------------------------------------------------------------------',
  12. r' Copyright \(C\) Microsoft( Corporation and contributors)?\. All rights reserved\.',
  13. r' Licensed under the MIT license\. See LICENSE\.txt file in the project root for full license information\.',
  14. r'.*' # the above should always be followed by at least one other line, so make sure that line is present
  15. ]
  16. regexes = []
  17. for line in copyright_lines:
  18. pattern = '^.{1,5}%s$' % line
  19. regexes.append(re.compile(pattern))
  20. if len(sys.argv) < 2:
  21. print("Requires passing a filename as an argument.")
  22. exit(1)
  23. file_name = sys.argv[1]
  24. if not os.path.isfile(file_name):
  25. print("File does not exist:", file_name, "(not necessarily an error)")
  26. exit(0)
  27. def report_incorrect(file_name, pairs):
  28. # found a problem so report the problem to the caller and exit
  29. print(file_name, "... does not contain a correct Microsoft copyright notice.\n")
  30. # print the relevant lines to help the reader find the problem
  31. for (_, line) in pairs:
  32. print(" ", line, end="")
  33. print()
  34. linecount = 0
  35. pairs = []
  36. with open(file_name, 'r') as sourcefile:
  37. hashbang = sourcefile.readline()
  38. if not hashbang.startswith("#!"):
  39. sourcefile.seek(0)
  40. pairs += zip(regexes, sourcefile)
  41. for (regex, line) in pairs:
  42. linecount += 1
  43. line = line.rstrip()
  44. matches = regex.match(line)
  45. if not matches:
  46. report_incorrect(file_name, pairs)
  47. exit(1)
  48. if linecount == 0:
  49. # the file was empty (e.g. dummy.js) so no problem
  50. exit(0)
  51. elif linecount != len(regexes):
  52. report_incorrect(file_name, pairs)
  53. exit(1)