check-trailing-whitespace.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import argparse
  4. import os
  5. import sys
  6. SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
  7. DOCS_DIR = os.path.join(SOURCE_ROOT, 'docs')
  8. def main():
  9. os.chdir(SOURCE_ROOT)
  10. args = parse_args()
  11. filepaths = []
  12. totalDirs = 0
  13. try:
  14. for root, dirs, files in os.walk(DOCS_DIR):
  15. totalDirs += len(dirs)
  16. for f in files:
  17. if f.endswith('.md'):
  18. filepaths.append(os.path.join(root, f))
  19. except KeyboardInterrupt:
  20. print('Keyboard interruption. Please try again.')
  21. return
  22. trailingWhiteSpaceFiles = 0
  23. for path in filepaths:
  24. trailingWhiteSpaceFiles += hasTrailingWhiteSpace(path, args.fix)
  25. print('Parsed through ' + str(len(filepaths)) +
  26. ' files within docs directory and its ' +
  27. str(totalDirs) + ' subdirectories.')
  28. print('Found ' + str(trailingWhiteSpaceFiles) +
  29. ' files with trailing whitespace.')
  30. return trailingWhiteSpaceFiles
  31. def hasTrailingWhiteSpace(filepath, fix):
  32. try:
  33. f = open(filepath, 'r')
  34. lines = f.read().splitlines()
  35. except KeyboardInterrupt:
  36. print('Keyboard interruption whle parsing. Please try again.')
  37. finally:
  38. f.close()
  39. fixed_lines = []
  40. for line in lines:
  41. fixed_lines.append(line.rstrip() + '\n')
  42. if not fix and line != line.rstrip():
  43. print("Trailing whitespace in: " + filepath)
  44. return True
  45. if fix:
  46. with open(filepath, 'w') as f:
  47. print(fixed_lines)
  48. f.writelines(fixed_lines)
  49. return False
  50. def parse_args():
  51. parser = argparse.ArgumentParser(
  52. description='Check for trailing whitespace in md files')
  53. parser.add_argument('-f', '--fix',
  54. help='Automatically fix trailing whitespace issues',
  55. action='store_true')
  56. return parser.parse_known_args()[0]
  57. if __name__ == '__main__':
  58. sys.exit(main())