patch.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # patch.py -- For dealing with packed-style patches.
  2. # Copyright (C) 2009-2013 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 io import BytesIO
  23. from difflib import SequenceMatcher
  24. import email.parser
  25. import time
  26. from dulwich.objects import (
  27. Commit,
  28. S_ISGITLINK,
  29. )
  30. FIRST_FEW_BYTES = 8000
  31. def write_commit_patch(f, commit, contents, progress, version=None):
  32. """Write a individual file patch.
  33. :param commit: Commit object
  34. :param progress: Tuple with current patch number and total.
  35. :return: tuple with filename and contents
  36. """
  37. (num, total) = progress
  38. f.write("From %s %s\n" % (commit.id, time.ctime(commit.commit_time)))
  39. f.write("From: %s\n" % commit.author)
  40. f.write("Date: %s\n" % time.strftime("%a, %d %b %Y %H:%M:%S %Z"))
  41. f.write("Subject: [PATCH %d/%d] %s\n" % (num, total, commit.message))
  42. f.write("\n")
  43. f.write("---\n")
  44. try:
  45. import subprocess
  46. p = subprocess.Popen(["diffstat"], stdout=subprocess.PIPE,
  47. stdin=subprocess.PIPE)
  48. except (ImportError, OSError):
  49. pass # diffstat not available?
  50. else:
  51. (diffstat, _) = p.communicate(contents)
  52. f.write(diffstat)
  53. f.write("\n")
  54. f.write(contents)
  55. f.write("-- \n")
  56. if version is None:
  57. from dulwich import __version__ as dulwich_version
  58. f.write("Dulwich %d.%d.%d\n" % dulwich_version)
  59. else:
  60. f.write("%s\n" % version)
  61. def get_summary(commit):
  62. """Determine the summary line for use in a filename.
  63. :param commit: Commit
  64. :return: Summary string
  65. """
  66. return commit.message.splitlines()[0].replace(" ", "-")
  67. def unified_diff(a, b, fromfile='', tofile='', n=3):
  68. """difflib.unified_diff that doesn't write any dates or trailing spaces.
  69. Based on the same function in Python2.6.5-rc2's difflib.py
  70. """
  71. started = False
  72. for group in SequenceMatcher(None, a, b).get_grouped_opcodes(n):
  73. if not started:
  74. yield '--- %s\n' % fromfile
  75. yield '+++ %s\n' % tofile
  76. started = True
  77. i1, i2, j1, j2 = group[0][1], group[-1][2], group[0][3], group[-1][4]
  78. yield "@@ -%d,%d +%d,%d @@\n" % (i1+1, i2-i1, j1+1, j2-j1)
  79. for tag, i1, i2, j1, j2 in group:
  80. if tag == 'equal':
  81. for line in a[i1:i2]:
  82. yield ' ' + line
  83. continue
  84. if tag == 'replace' or tag == 'delete':
  85. for line in a[i1:i2]:
  86. if not line[-1] == '\n':
  87. line += '\n\\ No newline at end of file\n'
  88. yield '-' + line
  89. if tag == 'replace' or tag == 'insert':
  90. for line in b[j1:j2]:
  91. if not line[-1] == '\n':
  92. line += '\n\\ No newline at end of file\n'
  93. yield '+' + line
  94. def is_binary(content):
  95. """See if the first few bytes contain any null characters.
  96. :param content: Bytestring to check for binary content
  97. """
  98. return '\0' in content[:FIRST_FEW_BYTES]
  99. def shortid(hexsha):
  100. if hexsha is None:
  101. return "0" * 7
  102. else:
  103. return hexsha[:7]
  104. def patch_filename(p, root):
  105. if p is None:
  106. return "/dev/null"
  107. else:
  108. return root + "/" + p
  109. def write_object_diff(f, store, old_file, new_file, diff_binary=False):
  110. """Write the diff for an object.
  111. :param f: File-like object to write to
  112. :param store: Store to retrieve objects from, if necessary
  113. :param old_file: (path, mode, hexsha) tuple
  114. :param new_file: (path, mode, hexsha) tuple
  115. :param diff_binary: Whether to diff files even if they
  116. are considered binary files by is_binary().
  117. :note: the tuple elements should be None for nonexistant files
  118. """
  119. (old_path, old_mode, old_id) = old_file
  120. (new_path, new_mode, new_id) = new_file
  121. old_path = patch_filename(old_path, "a")
  122. new_path = patch_filename(new_path, "b")
  123. def content(mode, hexsha):
  124. if hexsha is None:
  125. return ''
  126. elif S_ISGITLINK(mode):
  127. return "Submodule commit " + hexsha + "\n"
  128. else:
  129. return store[hexsha].data
  130. def lines(content):
  131. if not content:
  132. return []
  133. else:
  134. return content.splitlines(True)
  135. f.writelines(gen_diff_header(
  136. (old_path, new_path), (old_mode, new_mode), (old_id, new_id)))
  137. old_content = content(old_mode, old_id)
  138. new_content = content(new_mode, new_id)
  139. if not diff_binary and (is_binary(old_content) or is_binary(new_content)):
  140. f.write("Binary files %s and %s differ\n" % (old_path, new_path))
  141. else:
  142. f.writelines(unified_diff(lines(old_content), lines(new_content),
  143. old_path, new_path))
  144. def gen_diff_header(paths, modes, shas):
  145. """Write a blob diff header.
  146. :param paths: Tuple with old and new path
  147. :param modes: Tuple with old and new modes
  148. :param shas: Tuple with old and new shas
  149. """
  150. (old_path, new_path) = paths
  151. (old_mode, new_mode) = modes
  152. (old_sha, new_sha) = shas
  153. yield "diff --git %s %s\n" % (old_path, new_path)
  154. if old_mode != new_mode:
  155. if new_mode is not None:
  156. if old_mode is not None:
  157. yield "old mode %o\n" % old_mode
  158. yield "new mode %o\n" % new_mode
  159. else:
  160. yield "deleted mode %o\n" % old_mode
  161. yield "index " + shortid(old_sha) + ".." + shortid(new_sha)
  162. if new_mode is not None:
  163. yield " %o" % new_mode
  164. yield "\n"
  165. def write_blob_diff(f, old_file, new_file):
  166. """Write blob diff.
  167. :param f: File-like object to write to
  168. :param old_file: (path, mode, hexsha) tuple (None if nonexisting)
  169. :param new_file: (path, mode, hexsha) tuple (None if nonexisting)
  170. :note: The use of write_object_diff is recommended over this function.
  171. """
  172. (old_path, old_mode, old_blob) = old_file
  173. (new_path, new_mode, new_blob) = new_file
  174. old_path = patch_filename(old_path, "a")
  175. new_path = patch_filename(new_path, "b")
  176. def lines(blob):
  177. if blob is not None:
  178. return blob.data.splitlines(True)
  179. else:
  180. return []
  181. f.writelines(gen_diff_header(
  182. (old_path, new_path), (old_mode, new_mode),
  183. (getattr(old_blob, "id", None), getattr(new_blob, "id", None))))
  184. old_contents = lines(old_blob)
  185. new_contents = lines(new_blob)
  186. f.writelines(unified_diff(old_contents, new_contents,
  187. old_path, new_path))
  188. def write_tree_diff(f, store, old_tree, new_tree, diff_binary=False):
  189. """Write tree diff.
  190. :param f: File-like object to write to.
  191. :param old_tree: Old tree id
  192. :param new_tree: New tree id
  193. :param diff_binary: Whether to diff files even if they
  194. are considered binary files by is_binary().
  195. """
  196. changes = store.tree_changes(old_tree, new_tree)
  197. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  198. write_object_diff(f, store, (oldpath, oldmode, oldsha),
  199. (newpath, newmode, newsha),
  200. diff_binary=diff_binary)
  201. def git_am_patch_split(f):
  202. """Parse a git-am-style patch and split it up into bits.
  203. :param f: File-like object to parse
  204. :return: Tuple with commit object, diff contents and git version
  205. """
  206. parser = email.parser.Parser()
  207. msg = parser.parse(f)
  208. c = Commit()
  209. c.author = msg["from"]
  210. c.committer = msg["from"]
  211. try:
  212. patch_tag_start = msg["subject"].index("[PATCH")
  213. except ValueError:
  214. subject = msg["subject"]
  215. else:
  216. close = msg["subject"].index("] ", patch_tag_start)
  217. subject = msg["subject"][close+2:]
  218. c.message = subject.replace("\n", "") + "\n"
  219. first = True
  220. body = BytesIO(msg.get_payload())
  221. for l in body:
  222. if l == "---\n":
  223. break
  224. if first:
  225. if l.startswith("From: "):
  226. c.author = l[len("From: "):].rstrip()
  227. else:
  228. c.message += "\n" + l
  229. first = False
  230. else:
  231. c.message += l
  232. diff = ""
  233. for l in body:
  234. if l == "-- \n":
  235. break
  236. diff += l
  237. try:
  238. version = next(body).rstrip("\n")
  239. except StopIteration:
  240. version = None
  241. return c, diff, version