Guest User

Untitled

a guest
Jul 16th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. USAGE = '''
  2. Usage example:
  3.  
  4. python tabs2spaces.py . 4 ".*\.py$"
  5.  
  6. '''
  7.  
  8. import io
  9. import argparse
  10. import os
  11. import re
  12.  
  13. parser = argparse.ArgumentParser(description='Replace tabs with spaces.'+USAGE)
  14. parser.add_argument('root_directory', type=str,
  15. help='directory to run the script in')
  16. parser.add_argument('spaces_for_tab', type=int, default=4, nargs='?',
  17. help='number of spaces for one tab')
  18. parser.add_argument('file_mask_regex', default=".*", nargs='?',
  19. help='file name mask regex')
  20. parser.add_argument("--head-only", action='store_true', default=True,
  21. help='only change the tab in the head of each line.')
  22.  
  23. args = parser.parse_args()
  24. file_mask_regex = re.compile(args.file_mask_regex)
  25. replacement_spaces = ' ' * args.spaces_for_tab
  26.  
  27. print('Starting tab replacement. \
  28. directory {0}, spaces number {1}, file mask {2}'.format(args.root_directory, args.spaces_for_tab, args.file_mask_regex))
  29.  
  30. found_files = []
  31. for path, subdirs, files in os.walk(args.root_directory):
  32. for name in files:
  33. found_files.append(os.path.join(path, name));
  34.  
  35. matched_files = [name for name in found_files if file_mask_regex.match(name)]
  36.  
  37. for file_path in matched_files:
  38. print('Replacing tabs in {0}'.format(file_path))
  39.  
  40. file_contents = ''
  41. with open(file_path) as f:
  42. file_contents = f.read()
  43.  
  44. if args.head_only:
  45. file_lines = file_contents.split("\n")
  46. file_lines_out = []
  47. for line in file_lines:
  48. if not line.startswith("\t"):
  49. file_lines_out.append(line)
  50. continue
  51. else:
  52. head_tabs = re.findall("^\t+", line)[0]
  53. head_spaces = head_tabs.replace("\t", replacement_spaces)
  54. line = re.sub('^'+head_tabs, head_spaces, line)
  55. file_lines_out.append(line)
  56. file_contents = "\n".join(file_lines_out)
  57. else:
  58. file_contents = re.sub('\t', replacement_spaces, file_contents)
  59.  
  60.  
  61. with open(file_path, "w") as f:
  62. f.write(file_contents)
  63.  
  64. print('Done')
Add Comment
Please, Sign In to add comment