tailing-spaces.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. '''
  4. Remove tailing whitespaces and ensures one and only one empty ending line.
  5. '''
  6. import os, re
  7. def scan(*dirs, **kwargs):
  8. files = []
  9. extensions = kwargs['extensions'] if kwargs.has_key('extensions') else None
  10. excludes = kwargs['excludes'] if kwargs.has_key('excludes') else []
  11. for top in dirs:
  12. for root, dirnames, filenames in os.walk(top):
  13. dirnames = [i for i in dirnames if i in excludes]
  14. for f in filenames:
  15. if f in excludes:
  16. continue
  17. ext = os.path.splitext(f)[1].lower()
  18. if extensions is None or ext in extensions:
  19. files.append(os.path.join(root, f))
  20. return files
  21. def fixone(src):
  22. lines = open(src, 'r').readlines()
  23. trimed = []
  24. for line in lines:
  25. trimed.append(re.sub('\s+$', '', line))
  26. while len(trimed) > 1 and not trimed[-1]:
  27. trimed.pop()
  28. trimed.append('')
  29. with open(src, 'w') as f:
  30. for line in trimed:
  31. f.write('%s\n' % line)
  32. def lint(root):
  33. print('Checking tailing whitespaces in: %s' % root)
  34. dirs = [
  35. os.path.join(root, 'cocos'),
  36. os.path.join(root, 'extensions'),
  37. os.path.join(root, 'templates'),
  38. os.path.join(root, 'tests'),
  39. os.path.join(root, 'tools', 'simulator')
  40. ]
  41. files = scan(*dirs, extensions=['.c', '.cpp', '.h', '.hpp', '.m', '.mm', '.java'])
  42. for f in files:
  43. print(f)
  44. fixone(f)
  45. def main():
  46. default_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
  47. lint(default_root)
  48. main()