patch.py 12 KB

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