patch.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. # patch.py -- For dealing with packed-style patches.
  2. # Copyright (C) 2009-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Classes for dealing with git am-style patches.
  22. These patches are basically unified diffs with some extra metadata tacked
  23. on.
  24. """
  25. import email.parser
  26. import time
  27. from collections.abc import Generator
  28. from difflib import SequenceMatcher
  29. from typing import (
  30. TYPE_CHECKING,
  31. BinaryIO,
  32. Optional,
  33. TextIO,
  34. Union,
  35. )
  36. if TYPE_CHECKING:
  37. import email.message
  38. from .object_store import BaseObjectStore
  39. from .objects import S_ISGITLINK, Blob, Commit
  40. FIRST_FEW_BYTES = 8000
  41. def write_commit_patch(
  42. f: BinaryIO,
  43. commit: "Commit",
  44. contents: Union[str, bytes],
  45. progress: tuple[int, int],
  46. version: Optional[str] = None,
  47. encoding: Optional[str] = None,
  48. ) -> None:
  49. """Write a individual file patch.
  50. Args:
  51. commit: Commit object
  52. progress: tuple with current patch number and total.
  53. Returns:
  54. tuple with filename and contents
  55. """
  56. encoding = encoding or getattr(f, "encoding", "ascii")
  57. if encoding is None:
  58. encoding = "ascii"
  59. if isinstance(contents, str):
  60. contents = contents.encode(encoding)
  61. (num, total) = progress
  62. f.write(
  63. b"From "
  64. + commit.id
  65. + b" "
  66. + time.ctime(commit.commit_time).encode(encoding)
  67. + b"\n"
  68. )
  69. f.write(b"From: " + commit.author + b"\n")
  70. f.write(
  71. b"Date: " + time.strftime("%a, %d %b %Y %H:%M:%S %Z").encode(encoding) + b"\n"
  72. )
  73. f.write(
  74. (f"Subject: [PATCH {num}/{total}] ").encode(encoding) + commit.message + b"\n"
  75. )
  76. f.write(b"\n")
  77. f.write(b"---\n")
  78. try:
  79. import subprocess
  80. p = subprocess.Popen(
  81. ["diffstat"], stdout=subprocess.PIPE, stdin=subprocess.PIPE
  82. )
  83. except (ImportError, OSError):
  84. pass # diffstat not available?
  85. else:
  86. (diffstat, _) = p.communicate(contents)
  87. f.write(diffstat)
  88. f.write(b"\n")
  89. f.write(contents)
  90. f.write(b"-- \n")
  91. if version is None:
  92. from dulwich import __version__ as dulwich_version
  93. f.write(b"Dulwich %d.%d.%d\n" % dulwich_version)
  94. else:
  95. if encoding is None:
  96. encoding = "ascii"
  97. f.write(version.encode(encoding) + b"\n")
  98. def get_summary(commit: "Commit") -> str:
  99. """Determine the summary line for use in a filename.
  100. Args:
  101. commit: Commit
  102. Returns: Summary string
  103. """
  104. decoded = commit.message.decode(errors="replace")
  105. lines = decoded.splitlines()
  106. return lines[0].replace(" ", "-") if lines else ""
  107. # Unified Diff
  108. def _format_range_unified(start: int, stop: int) -> str:
  109. """Convert range to the "ed" format."""
  110. # Per the diff spec at http://www.unix.org/single_unix_specification/
  111. beginning = start + 1 # lines start numbering with one
  112. length = stop - start
  113. if length == 1:
  114. return f"{beginning}"
  115. if not length:
  116. beginning -= 1 # empty ranges begin at line just before the range
  117. return f"{beginning},{length}"
  118. def unified_diff(
  119. a: list[bytes],
  120. b: list[bytes],
  121. fromfile: bytes = b"",
  122. tofile: bytes = b"",
  123. fromfiledate: str = "",
  124. tofiledate: str = "",
  125. n: int = 3,
  126. lineterm: str = "\n",
  127. tree_encoding: str = "utf-8",
  128. output_encoding: str = "utf-8",
  129. ) -> Generator[bytes, None, None]:
  130. """difflib.unified_diff that can detect "No newline at end of file" as
  131. original "git diff" does.
  132. Based on the same function in Python2.7 difflib.py
  133. """
  134. started = False
  135. for group in SequenceMatcher(a=a, b=b).get_grouped_opcodes(n):
  136. if not started:
  137. started = True
  138. fromdate = f"\t{fromfiledate}" if fromfiledate else ""
  139. todate = f"\t{tofiledate}" if tofiledate else ""
  140. yield f"--- {fromfile.decode(tree_encoding)}{fromdate}{lineterm}".encode(
  141. output_encoding
  142. )
  143. yield f"+++ {tofile.decode(tree_encoding)}{todate}{lineterm}".encode(
  144. output_encoding
  145. )
  146. first, last = group[0], group[-1]
  147. file1_range = _format_range_unified(first[1], last[2])
  148. file2_range = _format_range_unified(first[3], last[4])
  149. yield f"@@ -{file1_range} +{file2_range} @@{lineterm}".encode(output_encoding)
  150. for tag, i1, i2, j1, j2 in group:
  151. if tag == "equal":
  152. for line in a[i1:i2]:
  153. yield b" " + line
  154. continue
  155. if tag in ("replace", "delete"):
  156. for line in a[i1:i2]:
  157. if not line[-1:] == b"\n":
  158. line += b"\n\\ No newline at end of file\n"
  159. yield b"-" + line
  160. if tag in ("replace", "insert"):
  161. for line in b[j1:j2]:
  162. if not line[-1:] == b"\n":
  163. line += b"\n\\ No newline at end of file\n"
  164. yield b"+" + line
  165. def is_binary(content: bytes) -> bool:
  166. """See if the first few bytes contain any null characters.
  167. Args:
  168. content: Bytestring to check for binary content
  169. """
  170. return b"\0" in content[:FIRST_FEW_BYTES]
  171. def shortid(hexsha: Optional[bytes]) -> bytes:
  172. if hexsha is None:
  173. return b"0" * 7
  174. else:
  175. return hexsha[:7]
  176. def patch_filename(p: Optional[bytes], root: bytes) -> bytes:
  177. if p is None:
  178. return b"/dev/null"
  179. else:
  180. return root + b"/" + p
  181. def write_object_diff(
  182. f: BinaryIO,
  183. store: "BaseObjectStore",
  184. old_file: tuple[Optional[bytes], Optional[int], Optional[bytes]],
  185. new_file: tuple[Optional[bytes], Optional[int], Optional[bytes]],
  186. diff_binary: bool = False,
  187. ) -> None:
  188. """Write the diff for an object.
  189. Args:
  190. f: File-like object to write to
  191. store: Store to retrieve objects from, if necessary
  192. old_file: (path, mode, hexsha) tuple
  193. new_file: (path, mode, hexsha) tuple
  194. diff_binary: Whether to diff files even if they
  195. are considered binary files by is_binary().
  196. Note: the tuple elements should be None for nonexistent files
  197. """
  198. (old_path, old_mode, old_id) = old_file
  199. (new_path, new_mode, new_id) = new_file
  200. patched_old_path = patch_filename(old_path, b"a")
  201. patched_new_path = patch_filename(new_path, b"b")
  202. def content(mode: Optional[int], hexsha: Optional[bytes]) -> Blob:
  203. from typing import cast
  204. if hexsha is None:
  205. return cast(Blob, Blob.from_string(b""))
  206. elif mode is not None and S_ISGITLINK(mode):
  207. return cast(Blob, Blob.from_string(b"Subproject commit " + hexsha + b"\n"))
  208. else:
  209. obj = store[hexsha]
  210. if isinstance(obj, Blob):
  211. return obj
  212. else:
  213. # Fallback for non-blob objects
  214. return cast(Blob, Blob.from_string(obj.as_raw_string()))
  215. def lines(content: "Blob") -> list[bytes]:
  216. if not content:
  217. return []
  218. else:
  219. return content.splitlines()
  220. f.writelines(
  221. gen_diff_header((old_path, new_path), (old_mode, new_mode), (old_id, new_id))
  222. )
  223. old_content = content(old_mode, old_id)
  224. new_content = content(new_mode, new_id)
  225. if not diff_binary and (is_binary(old_content.data) or is_binary(new_content.data)):
  226. binary_diff = (
  227. b"Binary files "
  228. + patched_old_path
  229. + b" and "
  230. + patched_new_path
  231. + b" differ\n"
  232. )
  233. f.write(binary_diff)
  234. else:
  235. f.writelines(
  236. unified_diff(
  237. lines(old_content),
  238. lines(new_content),
  239. patched_old_path,
  240. patched_new_path,
  241. )
  242. )
  243. # TODO(jelmer): Support writing unicode, rather than bytes.
  244. def gen_diff_header(
  245. paths: tuple[Optional[bytes], Optional[bytes]],
  246. modes: tuple[Optional[int], Optional[int]],
  247. shas: tuple[Optional[bytes], Optional[bytes]],
  248. ) -> Generator[bytes, None, None]:
  249. """Write a blob diff header.
  250. Args:
  251. paths: Tuple with old and new path
  252. modes: Tuple with old and new modes
  253. shas: Tuple with old and new shas
  254. """
  255. (old_path, new_path) = paths
  256. (old_mode, new_mode) = modes
  257. (old_sha, new_sha) = shas
  258. if old_path is None and new_path is not None:
  259. old_path = new_path
  260. if new_path is None and old_path is not None:
  261. new_path = old_path
  262. old_path = patch_filename(old_path, b"a")
  263. new_path = patch_filename(new_path, b"b")
  264. yield b"diff --git " + old_path + b" " + new_path + b"\n"
  265. if old_mode != new_mode:
  266. if new_mode is not None:
  267. if old_mode is not None:
  268. yield (f"old file mode {old_mode:o}\n").encode("ascii")
  269. yield (f"new file mode {new_mode:o}\n").encode("ascii")
  270. else:
  271. yield (f"deleted file mode {old_mode:o}\n").encode("ascii")
  272. yield b"index " + shortid(old_sha) + b".." + shortid(new_sha)
  273. if new_mode is not None and old_mode is not None:
  274. yield (f" {new_mode:o}").encode("ascii")
  275. yield b"\n"
  276. # TODO(jelmer): Support writing unicode, rather than bytes.
  277. def write_blob_diff(
  278. f: BinaryIO,
  279. old_file: tuple[Optional[bytes], Optional[int], Optional["Blob"]],
  280. new_file: tuple[Optional[bytes], Optional[int], Optional["Blob"]],
  281. ) -> None:
  282. """Write blob diff.
  283. Args:
  284. f: File-like object to write to
  285. old_file: (path, mode, hexsha) tuple (None if nonexisting)
  286. new_file: (path, mode, hexsha) tuple (None if nonexisting)
  287. Note: The use of write_object_diff is recommended over this function.
  288. """
  289. (old_path, old_mode, old_blob) = old_file
  290. (new_path, new_mode, new_blob) = new_file
  291. patched_old_path = patch_filename(old_path, b"a")
  292. patched_new_path = patch_filename(new_path, b"b")
  293. def lines(blob: Optional["Blob"]) -> list[bytes]:
  294. if blob is not None:
  295. return blob.splitlines()
  296. else:
  297. return []
  298. f.writelines(
  299. gen_diff_header(
  300. (old_path, new_path),
  301. (old_mode, new_mode),
  302. (getattr(old_blob, "id", None), getattr(new_blob, "id", None)),
  303. )
  304. )
  305. old_contents = lines(old_blob)
  306. new_contents = lines(new_blob)
  307. f.writelines(
  308. unified_diff(old_contents, new_contents, patched_old_path, patched_new_path)
  309. )
  310. def write_tree_diff(
  311. f: BinaryIO,
  312. store: "BaseObjectStore",
  313. old_tree: Optional[bytes],
  314. new_tree: Optional[bytes],
  315. diff_binary: bool = False,
  316. ) -> None:
  317. """Write tree diff.
  318. Args:
  319. f: File-like object to write to.
  320. old_tree: Old tree id
  321. new_tree: New tree id
  322. diff_binary: Whether to diff files even if they
  323. are considered binary files by is_binary().
  324. """
  325. changes = store.tree_changes(old_tree, new_tree)
  326. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  327. write_object_diff(
  328. f,
  329. store,
  330. (oldpath, oldmode, oldsha),
  331. (newpath, newmode, newsha),
  332. diff_binary=diff_binary,
  333. )
  334. def git_am_patch_split(
  335. f: Union[TextIO, BinaryIO], encoding: Optional[str] = None
  336. ) -> tuple["Commit", bytes, Optional[bytes]]:
  337. """Parse a git-am-style patch and split it up into bits.
  338. Args:
  339. f: File-like object to parse
  340. encoding: Encoding to use when creating Git objects
  341. Returns: Tuple with commit object, diff contents and git version
  342. """
  343. encoding = encoding or getattr(f, "encoding", "ascii")
  344. encoding = encoding or "ascii"
  345. contents = f.read()
  346. if isinstance(contents, bytes):
  347. bparser = email.parser.BytesParser()
  348. msg = bparser.parsebytes(contents)
  349. else:
  350. uparser = email.parser.Parser()
  351. msg = uparser.parsestr(contents)
  352. return parse_patch_message(msg, encoding)
  353. def parse_patch_message(
  354. msg: "email.message.Message", encoding: Optional[str] = None
  355. ) -> tuple["Commit", bytes, Optional[bytes]]:
  356. """Extract a Commit object and patch from an e-mail message.
  357. Args:
  358. msg: An email message (email.message.Message)
  359. encoding: Encoding to use to encode Git commits
  360. Returns: Tuple with commit object, diff contents and git version
  361. """
  362. c = Commit()
  363. if encoding is None:
  364. encoding = "ascii"
  365. c.author = msg["from"].encode(encoding)
  366. c.committer = msg["from"].encode(encoding)
  367. try:
  368. patch_tag_start = msg["subject"].index("[PATCH")
  369. except ValueError:
  370. subject = msg["subject"]
  371. else:
  372. close = msg["subject"].index("] ", patch_tag_start)
  373. subject = msg["subject"][close + 2 :]
  374. c.message = (subject.replace("\n", "") + "\n").encode(encoding)
  375. first = True
  376. body = msg.get_payload(decode=True)
  377. if isinstance(body, str):
  378. body = body.encode(encoding)
  379. if isinstance(body, bytes):
  380. lines = body.splitlines(True)
  381. else:
  382. # Handle other types by converting to string first
  383. lines = str(body).encode(encoding).splitlines(True)
  384. line_iter = iter(lines)
  385. for line in line_iter:
  386. if line == b"---\n":
  387. break
  388. if first:
  389. if line.startswith(b"From: "):
  390. c.author = line[len(b"From: ") :].rstrip()
  391. else:
  392. c.message += b"\n" + line
  393. first = False
  394. else:
  395. c.message += line
  396. diff = b""
  397. for line in line_iter:
  398. if line == b"-- \n":
  399. break
  400. diff += line
  401. try:
  402. version = next(line_iter).rstrip(b"\n")
  403. except StopIteration:
  404. version = None
  405. return c, diff, version