patch.py 12 KB

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