patches.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/env python3
  2. import codecs
  3. import os
  4. PATCH_DIR_PREFIX = "Patch-Dir: "
  5. PATCH_FILENAME_PREFIX = "Patch-Filename: "
  6. PATCH_LINE_PREFIXES = (PATCH_DIR_PREFIX, PATCH_FILENAME_PREFIX)
  7. def is_patch_location_line(line):
  8. return line.startswith(PATCH_LINE_PREFIXES)
  9. def read_patch(patch_dir, patch_filename):
  10. """Read a patch from |patch_dir/filename| and amend the commit message with
  11. metadata about the patch file it came from."""
  12. ret = []
  13. added_patch_location = False
  14. patch_path = os.path.join(patch_dir, patch_filename)
  15. with codecs.open(patch_path, encoding='utf-8') as f:
  16. for l in f.readlines():
  17. line_has_correct_start = l.startswith('diff -') or l.startswith('---')
  18. if not added_patch_location and line_has_correct_start:
  19. ret.append('{}{}\n'.format(PATCH_DIR_PREFIX, patch_dir))
  20. ret.append('{}{}\n'.format(PATCH_FILENAME_PREFIX, patch_filename))
  21. added_patch_location = True
  22. ret.append(l)
  23. return ''.join(ret)
  24. def patch_from_dir(patch_dir):
  25. """Read a directory of patches into a format suitable for passing to
  26. 'git am'"""
  27. with open(os.path.join(patch_dir, ".patches")) as f:
  28. patch_list = [l.rstrip('\n') for l in f.readlines()]
  29. return ''.join([
  30. read_patch(patch_dir, patch_filename)
  31. for patch_filename in patch_list
  32. ])