patch.py 12 KB

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