patch.py 11 KB

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