You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

182 lines
5.4 KiB

  1. #!/usr/bin/env python
  2. import re
  3. import sys
  4. import shutil
  5. import os.path
  6. import subprocess
  7. import sysconfig
  8. import reindent
  9. import untabify
  10. SRCDIR = sysconfig.get_config_var('srcdir')
  11. def n_files_str(count):
  12. """Return 'N file(s)' with the proper plurality on 'file'."""
  13. return "{} file{}".format(count, "s" if count != 1 else "")
  14. def status(message, modal=False, info=None):
  15. """Decorator to output status info to stdout."""
  16. def decorated_fxn(fxn):
  17. def call_fxn(*args, **kwargs):
  18. sys.stdout.write(message + ' ... ')
  19. sys.stdout.flush()
  20. result = fxn(*args, **kwargs)
  21. if not modal and not info:
  22. print "done"
  23. elif info:
  24. print info(result)
  25. else:
  26. print "yes" if result else "NO"
  27. return result
  28. return call_fxn
  29. return decorated_fxn
  30. def mq_patches_applied():
  31. """Check if there are any applied MQ patches."""
  32. cmd = 'hg qapplied'
  33. st = subprocess.Popen(cmd.split(),
  34. stdout=subprocess.PIPE,
  35. stderr=subprocess.PIPE)
  36. try:
  37. bstdout, _ = st.communicate()
  38. return st.returncode == 0 and bstdout
  39. finally:
  40. st.stdout.close()
  41. st.stderr.close()
  42. @status("Getting the list of files that have been added/changed",
  43. info=lambda x: n_files_str(len(x)))
  44. def changed_files():
  45. """Get the list of changed or added files from the VCS."""
  46. if os.path.isdir(os.path.join(SRCDIR, '.hg')):
  47. vcs = 'hg'
  48. cmd = 'hg status --added --modified --no-status'
  49. if mq_patches_applied():
  50. cmd += ' --rev qparent'
  51. elif os.path.isdir('.svn'):
  52. vcs = 'svn'
  53. cmd = 'svn status --quiet --non-interactive --ignore-externals'
  54. else:
  55. sys.exit('need a checkout to get modified files')
  56. st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
  57. try:
  58. st.wait()
  59. if vcs == 'hg':
  60. return [x.decode().rstrip() for x in st.stdout]
  61. else:
  62. output = (x.decode().rstrip().rsplit(None, 1)[-1]
  63. for x in st.stdout if x[0] in 'AM')
  64. return set(path for path in output if os.path.isfile(path))
  65. finally:
  66. st.stdout.close()
  67. def report_modified_files(file_paths):
  68. count = len(file_paths)
  69. if count == 0:
  70. return n_files_str(count)
  71. else:
  72. lines = ["{}:".format(n_files_str(count))]
  73. for path in file_paths:
  74. lines.append(" {}".format(path))
  75. return "\n".join(lines)
  76. @status("Fixing whitespace", info=report_modified_files)
  77. def normalize_whitespace(file_paths):
  78. """Make sure that the whitespace for .py files have been normalized."""
  79. reindent.makebackup = False # No need to create backups.
  80. fixed = []
  81. for path in (x for x in file_paths if x.endswith('.py')):
  82. if reindent.check(os.path.join(SRCDIR, path)):
  83. fixed.append(path)
  84. return fixed
  85. @status("Fixing C file whitespace", info=report_modified_files)
  86. def normalize_c_whitespace(file_paths):
  87. """Report if any C files """
  88. fixed = []
  89. for path in file_paths:
  90. abspath = os.path.join(SRCDIR, path)
  91. with open(abspath, 'r') as f:
  92. if '\t' not in f.read():
  93. continue
  94. untabify.process(abspath, 8, verbose=False)
  95. fixed.append(path)
  96. return fixed
  97. ws_re = re.compile(br'\s+(\r?\n)$')
  98. @status("Fixing docs whitespace", info=report_modified_files)
  99. def normalize_docs_whitespace(file_paths):
  100. fixed = []
  101. for path in file_paths:
  102. abspath = os.path.join(SRCDIR, path)
  103. try:
  104. with open(abspath, 'rb') as f:
  105. lines = f.readlines()
  106. new_lines = [ws_re.sub(br'\1', line) for line in lines]
  107. if new_lines != lines:
  108. shutil.copyfile(abspath, abspath + '.bak')
  109. with open(abspath, 'wb') as f:
  110. f.writelines(new_lines)
  111. fixed.append(path)
  112. except Exception as err:
  113. print 'Cannot fix %s: %s' % (path, err)
  114. return fixed
  115. @status("Docs modified", modal=True)
  116. def docs_modified(file_paths):
  117. """Report if any file in the Doc directory has been changed."""
  118. return bool(file_paths)
  119. @status("Misc/ACKS updated", modal=True)
  120. def credit_given(file_paths):
  121. """Check if Misc/ACKS has been changed."""
  122. return 'Misc/ACKS' in file_paths
  123. @status("Misc/NEWS updated", modal=True)
  124. def reported_news(file_paths):
  125. """Check if Misc/NEWS has been changed."""
  126. return 'Misc/NEWS' in file_paths
  127. def main():
  128. file_paths = changed_files()
  129. python_files = [fn for fn in file_paths if fn.endswith('.py')]
  130. c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
  131. doc_files = [fn for fn in file_paths if fn.startswith('Doc')]
  132. special_files = {'Misc/ACKS', 'Misc/NEWS'} & set(file_paths)
  133. # PEP 8 whitespace rules enforcement.
  134. normalize_whitespace(python_files)
  135. # C rules enforcement.
  136. normalize_c_whitespace(c_files)
  137. # Doc whitespace enforcement.
  138. normalize_docs_whitespace(doc_files)
  139. # Docs updated.
  140. docs_modified(doc_files)
  141. # Misc/ACKS changed.
  142. credit_given(special_files)
  143. # Misc/NEWS changed.
  144. reported_news(special_files)
  145. # Test suite run and passed.
  146. if python_files or c_files:
  147. print
  148. print "Did you run the test suite?"
  149. if __name__ == '__main__':
  150. main()