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.

55 lines
1.3 KiB

  1. #! /usr/bin/env python3
  2. "Replace tabs with spaces in argument files. Print names of changed files."
  3. import os
  4. import sys
  5. import getopt
  6. import tokenize
  7. def main():
  8. tabsize = 8
  9. try:
  10. opts, args = getopt.getopt(sys.argv[1:], "t:")
  11. if not args:
  12. raise getopt.error("At least one file argument required")
  13. except getopt.error as msg:
  14. print(msg)
  15. print("usage:", sys.argv[0], "[-t tabwidth] file ...")
  16. return
  17. for optname, optvalue in opts:
  18. if optname == '-t':
  19. tabsize = int(optvalue)
  20. for filename in args:
  21. process(filename, tabsize)
  22. def process(filename, tabsize, verbose=True):
  23. try:
  24. with tokenize.open(filename) as f:
  25. text = f.read()
  26. encoding = f.encoding
  27. except IOError as msg:
  28. print("%r: I/O error: %s" % (filename, msg))
  29. return
  30. newtext = text.expandtabs(tabsize)
  31. if newtext == text:
  32. return
  33. backup = filename + "~"
  34. try:
  35. os.unlink(backup)
  36. except os.error:
  37. pass
  38. try:
  39. os.rename(filename, backup)
  40. except os.error:
  41. pass
  42. with open(filename, "w", encoding=encoding) as f:
  43. f.write(newtext)
  44. if verbose:
  45. print(filename)
  46. if __name__ == '__main__':
  47. main()