patch.py 11 KB

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