patch.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # patch.py -- For dealing wih packed-style patches.
  2. # Copryight (C) 2009 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) a later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Classes for dealing with git am-style patches.
  19. These patches are basically unified diffs with some extra metadata tacked
  20. on.
  21. """
  22. from difflib import SequenceMatcher
  23. import rfc822
  24. import subprocess
  25. import time
  26. from dulwich.objects import (
  27. Commit,
  28. )
  29. def write_commit_patch(f, commit, contents, progress, version=None):
  30. """Write a individual file patch.
  31. :param commit: Commit object
  32. :param progress: Tuple with current patch number and total.
  33. :return: tuple with filename and contents
  34. """
  35. (num, total) = progress
  36. f.write("From %s %s\n" % (commit.id, time.ctime(commit.commit_time)))
  37. f.write("From: %s\n" % commit.author)
  38. f.write("Date: %s\n" % time.strftime("%a, %d %b %Y %H:%M:%S %Z"))
  39. f.write("Subject: [PATCH %d/%d] %s\n" % (num, total, commit.message))
  40. f.write("\n")
  41. f.write("---\n")
  42. try:
  43. p = subprocess.Popen(["diffstat"], stdout=subprocess.PIPE,
  44. stdin=subprocess.PIPE)
  45. except OSError, e:
  46. pass # diffstat not available?
  47. else:
  48. (diffstat, _) = p.communicate(contents)
  49. f.write(diffstat)
  50. f.write("\n")
  51. f.write(contents)
  52. f.write("-- \n")
  53. if version is None:
  54. from dulwich import __version__ as dulwich_version
  55. f.write("Dulwich %d.%d.%d\n" % dulwich_version)
  56. else:
  57. f.write("%s\n" % version)
  58. def get_summary(commit):
  59. """Determine the summary line for use in a filename.
  60. :param commit: Commit
  61. :return: Summary string
  62. """
  63. return commit.message.splitlines()[0].replace(" ", "-")
  64. def unified_diff(a, b, fromfile='', tofile='', n=3, lineterm='\n'):
  65. """difflib.unified_diff that doesn't write any dates or trailing spaces.
  66. Based on the same function in Python2.6.5-rc2's difflib.py
  67. """
  68. started = False
  69. for group in SequenceMatcher(None, a, b).get_grouped_opcodes(3):
  70. if not started:
  71. yield '--- %s\n' % fromfile
  72. yield '+++ %s\n' % tofile
  73. started = True
  74. i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
  75. yield "@@ -%d,%d +%d,%d @@\n" % (i1+1, i2-i1, j1+1, j2-j1)
  76. for tag, i1, i2, j1, j2 in group:
  77. if tag == 'equal':
  78. for line in a[i1:i2]:
  79. yield ' ' + line
  80. continue
  81. if tag == 'replace' or tag == 'delete':
  82. for line in a[i1:i2]:
  83. yield '-' + line
  84. if tag == 'replace' or tag == 'insert':
  85. for line in b[j1:j2]:
  86. yield '+' + line
  87. def write_blob_diff(f, (old_path, old_mode, old_blob),
  88. (new_path, new_mode, new_blob)):
  89. """Write diff file header.
  90. :param f: File-like object to write to
  91. :param (old_path, old_mode, old_blob): Previous file (None if nonexisting)
  92. :param (new_path, new_mode, new_blob): New file (None if nonexisting)
  93. """
  94. def blob_id(blob):
  95. if blob is None:
  96. return "0" * 7
  97. else:
  98. return blob.id[:7]
  99. def lines(blob):
  100. if blob is not None:
  101. return blob.data.splitlines(True)
  102. else:
  103. return []
  104. if old_path is None:
  105. old_path = "/dev/null"
  106. else:
  107. old_path = "a/%s" % old_path
  108. if new_path is None:
  109. new_path = "/dev/null"
  110. else:
  111. new_path = "b/%s" % new_path
  112. f.write("diff --git %s %s\n" % (old_path, new_path))
  113. if old_mode != new_mode:
  114. if new_mode is not None:
  115. if old_mode is not None:
  116. f.write("old mode %o\n" % old_mode)
  117. f.write("new mode %o\n" % new_mode)
  118. else:
  119. f.write("deleted mode %o\n" % old_mode)
  120. f.write("index %s..%s %o\n" % (
  121. blob_id(old_blob), blob_id(new_blob), new_mode))
  122. old_contents = lines(old_blob)
  123. new_contents = lines(new_blob)
  124. f.writelines(unified_diff(old_contents, new_contents,
  125. old_path, new_path))
  126. def git_am_patch_split(f):
  127. """Parse a git-am-style patch and split it up into bits.
  128. :param f: File-like object to parse
  129. :return: Tuple with commit object, diff contents and git version
  130. """
  131. msg = rfc822.Message(f)
  132. c = Commit()
  133. c.author = msg["from"]
  134. c.committer = msg["from"]
  135. if msg["subject"].startswith("[PATCH"):
  136. subject = msg["subject"].split("]", 1)[1][1:]
  137. else:
  138. subject = msg["subject"]
  139. c.message = subject
  140. for l in f:
  141. if l == "---\n":
  142. break
  143. c.message += l
  144. diff = ""
  145. for l in f:
  146. if l == "-- \n":
  147. break
  148. diff += l
  149. version = f.next().rstrip("\n")
  150. return c, diff, version