patch.py 12 KB

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