fixWhitespace.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python3
  2. from __future__ import print_function
  3. import os
  4. from scriptCommon import catchPath
  5. def isSourceFile( path ):
  6. return path.endswith( ".cpp" ) or path.endswith( ".h" ) or path.endswith( ".hpp" )
  7. def fixAllFilesInDir( dir ):
  8. changedFiles = 0
  9. for f in os.listdir( dir ):
  10. path = os.path.join( dir,f )
  11. if os.path.isfile( path ):
  12. if isSourceFile( path ):
  13. if fixFile( path ):
  14. changedFiles += 1
  15. else:
  16. fixAllFilesInDir( path )
  17. return changedFiles
  18. def fixFile( path ):
  19. f = open( path, 'r' )
  20. lines = []
  21. changed = 0
  22. for line in f:
  23. trimmed = line.rstrip() + "\n"
  24. trimmed = trimmed.replace('\t', ' ')
  25. if trimmed != line:
  26. changed = changed +1
  27. lines.append( trimmed )
  28. f.close()
  29. if changed > 0:
  30. global changedFiles
  31. changedFiles = changedFiles + 1
  32. print( path + ":" )
  33. print( " - fixed " + str(changed) + " line(s)" )
  34. altPath = path + ".backup"
  35. os.rename( path, altPath )
  36. f2 = open( path, 'w' )
  37. for line in lines:
  38. f2.write( line )
  39. f2.close()
  40. os.remove( altPath )
  41. return True
  42. return False
  43. changedFiles = fixAllFilesInDir(catchPath)
  44. if changedFiles > 0:
  45. print( "Fixed " + str(changedFiles) + " file(s)" )
  46. else:
  47. print( "No trailing whitespace found" )