2
0

patch.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 time
  25. from dulwich.objects import (
  26. Commit,
  27. S_ISGITLINK,
  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. import subprocess
  44. p = subprocess.Popen(["diffstat"], stdout=subprocess.PIPE,
  45. stdin=subprocess.PIPE)
  46. except (ImportError, 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_object_diff(f, store, (old_path, old_mode, old_id),
  93. (new_path, new_mode, new_id)):
  94. """Write file contents diff.
  95. """
  96. def shortid(hexsha):
  97. if hexsha is None:
  98. return "0" * 7
  99. else:
  100. return hexsha[:7]
  101. def lines(mode, hexsha):
  102. if hexsha is None:
  103. return []
  104. elif S_ISGITLINK(mode):
  105. return ["Submodule commit " + hexsha + "\n"]
  106. else:
  107. return store[hexsha].data.splitlines(True)
  108. if old_path is None:
  109. old_path = "/dev/null"
  110. else:
  111. old_path = "a/%s" % old_path
  112. if new_path is None:
  113. new_path = "/dev/null"
  114. else:
  115. new_path = "b/%s" % new_path
  116. f.write("diff --git %s %s\n" % (old_path, new_path))
  117. if old_mode != new_mode:
  118. if new_mode is not None:
  119. if old_mode is not None:
  120. f.write("old mode %o\n" % old_mode)
  121. f.write("new mode %o\n" % new_mode)
  122. else:
  123. f.write("deleted mode %o\n" % old_mode)
  124. f.write("index %s..%s" % (shortid(old_id), shortid(new_id)))
  125. if new_mode is not None:
  126. f.write(" %o" % new_mode)
  127. f.write("\n")
  128. old_contents = lines(old_mode, old_id)
  129. new_contents = lines(new_mode, new_id)
  130. f.writelines(unified_diff(old_contents, new_contents,
  131. old_path, new_path))
  132. def write_blob_diff(f, (old_path, old_mode, old_blob),
  133. (new_path, new_mode, new_blob)):
  134. """Write diff file header.
  135. :param f: File-like object to write to
  136. :param (old_path, old_mode, old_blob): Previous file (None if nonexisting)
  137. :param (new_path, new_mode, new_blob): New file (None if nonexisting)
  138. """
  139. def blob_id(blob):
  140. if blob is None:
  141. return "0" * 7
  142. else:
  143. return blob.id[:7]
  144. def lines(blob):
  145. if blob is not None:
  146. return blob.data.splitlines(True)
  147. else:
  148. return []
  149. if old_path is None:
  150. old_path = "/dev/null"
  151. else:
  152. old_path = "a/%s" % old_path
  153. if new_path is None:
  154. new_path = "/dev/null"
  155. else:
  156. new_path = "b/%s" % new_path
  157. f.write("diff --git %s %s\n" % (old_path, new_path))
  158. if old_mode != new_mode:
  159. if new_mode is not None:
  160. if old_mode is not None:
  161. f.write("old mode %o\n" % old_mode)
  162. f.write("new mode %o\n" % new_mode)
  163. else:
  164. f.write("deleted mode %o\n" % old_mode)
  165. f.write("index %s..%s" % (blob_id(old_blob), blob_id(new_blob)))
  166. if new_mode is not None:
  167. f.write(" %o" % new_mode)
  168. f.write("\n")
  169. old_contents = lines(old_blob)
  170. new_contents = lines(new_blob)
  171. f.writelines(unified_diff(old_contents, new_contents,
  172. old_path, new_path))
  173. def write_tree_diff(f, store, old_tree, new_tree):
  174. """Write tree diff.
  175. :param f: File-like object to write to.
  176. :param old_tree: Old tree id
  177. :param new_tree: New tree id
  178. """
  179. changes = store.tree_changes(old_tree, new_tree)
  180. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  181. write_object_diff(f, store, (oldpath, oldmode, oldsha),
  182. (newpath, newmode, newsha))
  183. def git_am_patch_split(f):
  184. """Parse a git-am-style patch and split it up into bits.
  185. :param f: File-like object to parse
  186. :return: Tuple with commit object, diff contents and git version
  187. """
  188. msg = rfc822.Message(f)
  189. c = Commit()
  190. c.author = msg["from"]
  191. c.committer = msg["from"]
  192. try:
  193. patch_tag_start = msg["subject"].index("[PATCH")
  194. except ValueError:
  195. subject = msg["subject"]
  196. else:
  197. close = msg["subject"].index("] ", patch_tag_start)
  198. subject = msg["subject"][close+2:]
  199. c.message = subject.replace("\n", "") + "\n"
  200. first = True
  201. for l in f:
  202. if l == "---\n":
  203. break
  204. if first:
  205. if l.startswith("From: "):
  206. c.author = l[len("From: "):].rstrip()
  207. else:
  208. c.message += "\n" + l
  209. first = False
  210. else:
  211. c.message += l
  212. diff = ""
  213. for l in f:
  214. if l == "-- \n":
  215. break
  216. diff += l
  217. try:
  218. version = f.next().rstrip("\n")
  219. except StopIteration:
  220. version = None
  221. return c, diff, version