re_replace.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import sys
  2. from typing import List
  3. import argparse
  4. import re
  5. # Usage: re_replace.py --from-re <REGEXP> --to-re <REGEXP_REPLACE> FILE [FILE ...]
  6. def patch_line(line: str, from_re: re.Pattern, to_re: str) -> str:
  7. return re.sub(from_re, to_re, line)
  8. def main(args: List[str]):
  9. argparser = argparse.ArgumentParser(allow_abbrev=False)
  10. argparser.add_argument('--from-re', required=True)
  11. argparser.add_argument('--to-re', required=True)
  12. parsed_args, files = argparser.parse_known_args(args=args)
  13. from_re = re.compile(parsed_args.from_re)
  14. if not files:
  15. raise Exception('No input files')
  16. patched_files = []
  17. skipped_files = []
  18. for file in files:
  19. patched = False
  20. with open(file, 'rt', encoding="utf-8") as f:
  21. lines = f.readlines()
  22. for i in range(len(lines)):
  23. line = lines[i]
  24. patched_line = patch_line(line, from_re, parsed_args.to_re)
  25. if patched_line != line:
  26. patched = True
  27. lines[i] = patched_line
  28. if patched:
  29. with open(file, 'wt', encoding="utf-8") as f:
  30. f.writelines(lines)
  31. patched_files.append(file)
  32. else:
  33. skipped_files.append(file)
  34. if patched_files:
  35. print("Patched by re_replace: " + ", ".join(patched_files))
  36. if skipped_files:
  37. print("Skipped by re_replace: " + ", ".join(skipped_files))
  38. if __name__ == '__main__':
  39. main(sys.argv[1:])