patches.py 1013 B

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