patch.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. # patch.py -- For dealing with packed-style patches.
  2. # Copyright (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. Blob,
  28. Commit,
  29. )
  30. def write_commit_patch(f, commit, contents, progress, version=None):
  31. """Write a individual file patch.
  32. :param commit: Commit object
  33. :param progress: Tuple with current patch number and total.
  34. :return: tuple with filename and contents
  35. """
  36. (num, total) = progress
  37. f.write("From %s %s\n" % (commit.id, time.ctime(commit.commit_time)))
  38. f.write("From: %s\n" % commit.author)
  39. f.write("Date: %s\n" % time.strftime("%a, %d %b %Y %H:%M:%S %Z"))
  40. f.write("Subject: [PATCH %d/%d] %s\n" % (num, total, commit.message))
  41. f.write("\n")
  42. f.write("---\n")
  43. try:
  44. p = subprocess.Popen(["diffstat"], stdout=subprocess.PIPE,
  45. stdin=subprocess.PIPE)
  46. except OSError, e:
  47. pass # diffstat not available?
  48. else:
  49. (diffstat, _) = p.communicate(contents)
  50. f.write(diffstat)
  51. f.write("\n")
  52. f.write(contents)
  53. f.write("-- \n")
  54. if version is None:
  55. from dulwich import __version__ as dulwich_version
  56. f.write("Dulwich %d.%d.%d\n" % dulwich_version)
  57. else:
  58. f.write("%s\n" % version)
  59. def get_summary(commit):
  60. """Determine the summary line for use in a filename.
  61. :param commit: Commit
  62. :return: Summary string
  63. """
  64. return commit.message.splitlines()[0].replace(" ", "-")
  65. def unified_diff(a, b, fromfile='', tofile='', n=3):
  66. """difflib.unified_diff that doesn't write any dates or trailing spaces.
  67. Based on the same function in Python2.6.5-rc2's difflib.py
  68. """
  69. started = False
  70. for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n):
  71. if not started:
  72. yield '--- %s\n' % fromfile
  73. yield '+++ %s\n' % tofile
  74. started = True
  75. i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
  76. yield "@@ -%d,%d +%d,%d @@\n" % (i1+1, i2-i1, j1+1, j2-j1)
  77. for tag, i1, i2, j1, j2 in group:
  78. if tag == 'equal':
  79. for line in a[i1:i2]:
  80. yield ' ' + line
  81. continue
  82. if tag == 'replace' or tag == 'delete':
  83. for line in a[i1:i2]:
  84. if not line[-1] == '\n':
  85. line += '\n\\ No newline at end of file\n'
  86. yield '-' + line
  87. if tag == 'replace' or tag == 'insert':
  88. for line in b[j1:j2]:
  89. if not line[-1] == '\n':
  90. line += '\n\\ No newline at end of file\n'
  91. yield '+' + line
  92. def write_blob_diff(f, (old_path, old_mode, old_blob),
  93. (new_path, new_mode, new_blob)):
  94. """Write diff file header.
  95. :param f: File-like object to write to
  96. :param (old_path, old_mode, old_blob): Previous file (None if nonexisting)
  97. :param (new_path, new_mode, new_blob): New file (None if nonexisting)
  98. """
  99. def blob_id(blob):
  100. if blob is None:
  101. return "0" * 7
  102. else:
  103. return blob.id[:7]
  104. def lines(blob):
  105. if blob is not None:
  106. return blob.data.splitlines(True)
  107. else:
  108. return []
  109. if old_path is None:
  110. old_path = "/dev/null"
  111. else:
  112. old_path = "a/%s" % old_path
  113. if new_path is None:
  114. new_path = "/dev/null"
  115. else:
  116. new_path = "b/%s" % new_path
  117. f.write("diff --git %s %s\n" % (old_path, new_path))
  118. if old_mode != new_mode:
  119. if new_mode is not None:
  120. if old_mode is not None:
  121. f.write("old mode %o\n" % old_mode)
  122. f.write("new mode %o\n" % new_mode)
  123. else:
  124. f.write("deleted mode %o\n" % old_mode)
  125. f.write("index %s..%s" % (blob_id(old_blob), blob_id(new_blob)))
  126. if new_mode is not None:
  127. f.write(" %o" % new_mode)
  128. f.write("\n")
  129. old_contents = lines(old_blob)
  130. new_contents = lines(new_blob)
  131. f.writelines(unified_diff(old_contents, new_contents,
  132. old_path, new_path))
  133. def write_tree_diff(f, store, old_tree, new_tree):
  134. """Write tree diff.
  135. :param f: File-like object to write to.
  136. :param old_tree: Old tree id
  137. :param new_tree: New tree id
  138. """
  139. changes = store.tree_changes(old_tree, new_tree)
  140. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  141. if oldsha is None:
  142. old_blob = Blob.from_string("")
  143. else:
  144. old_blob = store[oldsha]
  145. if newsha is None:
  146. new_blob = Blob.from_string("")
  147. else:
  148. new_blob = store[newsha]
  149. write_blob_diff(f, (oldpath, oldmode, old_blob),
  150. (newpath, newmode, new_blob))
  151. def git_am_patch_split(f):
  152. """Parse a git-am-style patch and split it up into bits.
  153. :param f: File-like object to parse
  154. :return: Tuple with commit object, diff contents and git version
  155. """
  156. msg = rfc822.Message(f)
  157. c = Commit()
  158. c.author = msg["from"]
  159. c.committer = msg["from"]
  160. try:
  161. patch_tag_start = msg["subject"].index("[PATCH")
  162. except ValueError:
  163. subject = msg["subject"]
  164. else:
  165. close = msg["subject"].index("] ", patch_tag_start)
  166. subject = msg["subject"][close+2:]
  167. c.message = subject.replace("\n", "") + "\n"
  168. first = True
  169. for l in f:
  170. if l == "---\n":
  171. break
  172. if first:
  173. if l.startswith("From: "):
  174. c.author = l[len("From: "):].rstrip()
  175. else:
  176. c.message += "\n" + l
  177. first = False
  178. else:
  179. c.message += l
  180. diff = ""
  181. for l in f:
  182. if l == "-- \n":
  183. break
  184. diff += l
  185. try:
  186. version = f.next().rstrip("\n")
  187. except StopIteration:
  188. version = None
  189. return c, diff, version