gendiff.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env python3
  2. """
  3. scripts/gendiff.py:
  4. Clean up control characters and trailing whitespace in the listed source files
  5. and create a unified diff between them.
  6. If more or less than two files are listed on the command line, the cleanup is
  7. performed on all files, but no diff is created.
  8. The source files are assumed to be terminal output captured by the `script`
  9. command.
  10. The cleaned source files are saved with the .clean extension.
  11. """
  12. import sys,re
  13. from difflib import unified_diff
  14. fns = sys.argv[1:]
  15. translate = {
  16. '\r': None,
  17. '\b': '[BS]',
  18. # chr(4): '', # Ctrl-D, EOT
  19. }
  20. def cleanup_file(fn):
  21. # must use binary mode to prevent conversion of DOS CR into newline
  22. with open(fn,'rb') as fp:
  23. data = fp.read().decode()
  24. def gen_text():
  25. for line in data.split('\n'): # do not use splitlines()
  26. line = line.translate({ord(a):b for a,b in translate.items()})
  27. line = re.sub(r'\s+$','',line) # trailing whitespace
  28. yield line
  29. ret = list(gen_text())
  30. sys.stderr.write(f'Saving cleaned file to {fn}.clean\n')
  31. with open(f'{fn}.clean','w') as fp:
  32. fp.write('\n'.join(ret))
  33. return ret
  34. if len(fns) != 2:
  35. sys.stderr.write(f'{len(fns)} input files. Not generating diff.\n')
  36. cleaned_texts = [cleanup_file(fn) for fn in fns]
  37. if len(fns) == 2:
  38. # chunk headers have trailing newlines, hence the rstrip()
  39. sys.stderr.write('Generating diff\n')
  40. print(
  41. f'diff a/{fns[0]} b/{fns[1]}\n' +
  42. '\n'.join(a.rstrip() for a in unified_diff(*cleaned_texts,fromfile=f'a/{fns[0]}',tofile=f'b/{fns[1]}'))
  43. )