patch.py 12 KB

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