patch.py 12 KB

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