patch.py 10 KB

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