patch.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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 public 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. return decoded.splitlines()[0].replace(" ", "-")
  106. # Unified Diff
  107. def _format_range_unified(start: int, stop: int) -> str:
  108. """Convert range to the "ed" format."""
  109. # Per the diff spec at http://www.unix.org/single_unix_specification/
  110. beginning = start + 1 # lines start numbering with one
  111. length = stop - start
  112. if length == 1:
  113. return f"{beginning}"
  114. if not length:
  115. beginning -= 1 # empty ranges begin at line just before the range
  116. return f"{beginning},{length}"
  117. def unified_diff(
  118. a: list[bytes],
  119. b: list[bytes],
  120. fromfile: bytes = b"",
  121. tofile: bytes = b"",
  122. fromfiledate: str = "",
  123. tofiledate: str = "",
  124. n: int = 3,
  125. lineterm: str = "\n",
  126. tree_encoding: str = "utf-8",
  127. output_encoding: str = "utf-8",
  128. ) -> Generator[bytes, None, None]:
  129. """difflib.unified_diff that can detect "No newline at end of file" as
  130. original "git diff" does.
  131. Based on the same function in Python2.7 difflib.py
  132. """
  133. started = False
  134. for group in SequenceMatcher(a=a, b=b).get_grouped_opcodes(n):
  135. if not started:
  136. started = True
  137. fromdate = f"\t{fromfiledate}" if fromfiledate else ""
  138. todate = f"\t{tofiledate}" if tofiledate else ""
  139. yield f"--- {fromfile.decode(tree_encoding)}{fromdate}{lineterm}".encode(
  140. output_encoding
  141. )
  142. yield f"+++ {tofile.decode(tree_encoding)}{todate}{lineterm}".encode(
  143. output_encoding
  144. )
  145. first, last = group[0], group[-1]
  146. file1_range = _format_range_unified(first[1], last[2])
  147. file2_range = _format_range_unified(first[3], last[4])
  148. yield f"@@ -{file1_range} +{file2_range} @@{lineterm}".encode(output_encoding)
  149. for tag, i1, i2, j1, j2 in group:
  150. if tag == "equal":
  151. for line in a[i1:i2]:
  152. yield b" " + line
  153. continue
  154. if tag in ("replace", "delete"):
  155. for line in a[i1:i2]:
  156. if not line[-1:] == b"\n":
  157. line += b"\n\\ No newline at end of file\n"
  158. yield b"-" + line
  159. if tag in ("replace", "insert"):
  160. for line in b[j1:j2]:
  161. if not line[-1:] == b"\n":
  162. line += b"\n\\ No newline at end of file\n"
  163. yield b"+" + line
  164. def is_binary(content: bytes) -> bool:
  165. """See if the first few bytes contain any null characters.
  166. Args:
  167. content: Bytestring to check for binary content
  168. """
  169. return b"\0" in content[:FIRST_FEW_BYTES]
  170. def shortid(hexsha: Optional[bytes]) -> bytes:
  171. if hexsha is None:
  172. return b"0" * 7
  173. else:
  174. return hexsha[:7]
  175. def patch_filename(p: Optional[bytes], root: bytes) -> bytes:
  176. if p is None:
  177. return b"/dev/null"
  178. else:
  179. return root + b"/" + p
  180. def write_object_diff(
  181. f: BinaryIO,
  182. store: "BaseObjectStore",
  183. old_file: tuple[Optional[bytes], Optional[int], Optional[bytes]],
  184. new_file: tuple[Optional[bytes], Optional[int], Optional[bytes]],
  185. diff_binary: bool = False,
  186. ) -> None:
  187. """Write the diff for an object.
  188. Args:
  189. f: File-like object to write to
  190. store: Store to retrieve objects from, if necessary
  191. old_file: (path, mode, hexsha) tuple
  192. new_file: (path, mode, hexsha) tuple
  193. diff_binary: Whether to diff files even if they
  194. are considered binary files by is_binary().
  195. Note: the tuple elements should be None for nonexistent files
  196. """
  197. (old_path, old_mode, old_id) = old_file
  198. (new_path, new_mode, new_id) = new_file
  199. patched_old_path = patch_filename(old_path, b"a")
  200. patched_new_path = patch_filename(new_path, b"b")
  201. def content(mode: Optional[int], hexsha: Optional[bytes]) -> Blob:
  202. from typing import cast
  203. if hexsha is None:
  204. return cast(Blob, Blob.from_string(b""))
  205. elif mode is not None and S_ISGITLINK(mode):
  206. return cast(Blob, Blob.from_string(b"Subproject commit " + hexsha + b"\n"))
  207. else:
  208. obj = store[hexsha]
  209. if isinstance(obj, Blob):
  210. return obj
  211. else:
  212. # Fallback for non-blob objects
  213. return cast(Blob, Blob.from_string(obj.as_raw_string()))
  214. def lines(content: "Blob") -> list[bytes]:
  215. if not content:
  216. return []
  217. else:
  218. return content.splitlines()
  219. f.writelines(
  220. gen_diff_header((old_path, new_path), (old_mode, new_mode), (old_id, new_id))
  221. )
  222. old_content = content(old_mode, old_id)
  223. new_content = content(new_mode, new_id)
  224. if not diff_binary and (is_binary(old_content.data) or is_binary(new_content.data)):
  225. binary_diff = (
  226. b"Binary files "
  227. + patched_old_path
  228. + b" and "
  229. + patched_new_path
  230. + b" differ\n"
  231. )
  232. f.write(binary_diff)
  233. else:
  234. f.writelines(
  235. unified_diff(
  236. lines(old_content),
  237. lines(new_content),
  238. patched_old_path,
  239. patched_new_path,
  240. )
  241. )
  242. # TODO(jelmer): Support writing unicode, rather than bytes.
  243. def gen_diff_header(
  244. paths: tuple[Optional[bytes], Optional[bytes]],
  245. modes: tuple[Optional[int], Optional[int]],
  246. shas: tuple[Optional[bytes], Optional[bytes]],
  247. ) -> Generator[bytes, None, None]:
  248. """Write a blob diff header.
  249. Args:
  250. paths: Tuple with old and new path
  251. modes: Tuple with old and new modes
  252. shas: Tuple with old and new shas
  253. """
  254. (old_path, new_path) = paths
  255. (old_mode, new_mode) = modes
  256. (old_sha, new_sha) = shas
  257. if old_path is None and new_path is not None:
  258. old_path = new_path
  259. if new_path is None and old_path is not None:
  260. new_path = old_path
  261. old_path = patch_filename(old_path, b"a")
  262. new_path = patch_filename(new_path, b"b")
  263. yield b"diff --git " + old_path + b" " + new_path + b"\n"
  264. if old_mode != new_mode:
  265. if new_mode is not None:
  266. if old_mode is not None:
  267. yield (f"old file mode {old_mode:o}\n").encode("ascii")
  268. yield (f"new file mode {new_mode:o}\n").encode("ascii")
  269. else:
  270. yield (f"deleted file mode {old_mode:o}\n").encode("ascii")
  271. yield b"index " + shortid(old_sha) + b".." + shortid(new_sha)
  272. if new_mode is not None and old_mode is not None:
  273. yield (f" {new_mode:o}").encode("ascii")
  274. yield b"\n"
  275. # TODO(jelmer): Support writing unicode, rather than bytes.
  276. def write_blob_diff(
  277. f: BinaryIO,
  278. old_file: tuple[Optional[bytes], Optional[int], Optional["Blob"]],
  279. new_file: tuple[Optional[bytes], Optional[int], Optional["Blob"]],
  280. ) -> None:
  281. """Write blob diff.
  282. Args:
  283. f: File-like object to write to
  284. old_file: (path, mode, hexsha) tuple (None if nonexisting)
  285. new_file: (path, mode, hexsha) tuple (None if nonexisting)
  286. Note: The use of write_object_diff is recommended over this function.
  287. """
  288. (old_path, old_mode, old_blob) = old_file
  289. (new_path, new_mode, new_blob) = new_file
  290. patched_old_path = patch_filename(old_path, b"a")
  291. patched_new_path = patch_filename(new_path, b"b")
  292. def lines(blob: Optional["Blob"]) -> list[bytes]:
  293. if blob is not None:
  294. return blob.splitlines()
  295. else:
  296. return []
  297. f.writelines(
  298. gen_diff_header(
  299. (old_path, new_path),
  300. (old_mode, new_mode),
  301. (getattr(old_blob, "id", None), getattr(new_blob, "id", None)),
  302. )
  303. )
  304. old_contents = lines(old_blob)
  305. new_contents = lines(new_blob)
  306. f.writelines(
  307. unified_diff(old_contents, new_contents, patched_old_path, patched_new_path)
  308. )
  309. def write_tree_diff(
  310. f: BinaryIO,
  311. store: "BaseObjectStore",
  312. old_tree: Optional[bytes],
  313. new_tree: Optional[bytes],
  314. diff_binary: bool = False,
  315. ) -> None:
  316. """Write tree diff.
  317. Args:
  318. f: File-like object to write to.
  319. old_tree: Old tree id
  320. new_tree: New tree id
  321. diff_binary: Whether to diff files even if they
  322. are considered binary files by is_binary().
  323. """
  324. changes = store.tree_changes(old_tree, new_tree)
  325. for (oldpath, newpath), (oldmode, newmode), (oldsha, newsha) in changes:
  326. write_object_diff(
  327. f,
  328. store,
  329. (oldpath, oldmode, oldsha),
  330. (newpath, newmode, newsha),
  331. diff_binary=diff_binary,
  332. )
  333. def git_am_patch_split(
  334. f: Union[TextIO, BinaryIO], encoding: Optional[str] = None
  335. ) -> tuple["Commit", bytes, Optional[bytes]]:
  336. """Parse a git-am-style patch and split it up into bits.
  337. Args:
  338. f: File-like object to parse
  339. encoding: Encoding to use when creating Git objects
  340. Returns: Tuple with commit object, diff contents and git version
  341. """
  342. encoding = encoding or getattr(f, "encoding", "ascii")
  343. encoding = encoding or "ascii"
  344. contents = f.read()
  345. if isinstance(contents, bytes):
  346. bparser = email.parser.BytesParser()
  347. msg = bparser.parsebytes(contents)
  348. else:
  349. uparser = email.parser.Parser()
  350. msg = uparser.parsestr(contents)
  351. return parse_patch_message(msg, encoding)
  352. def parse_patch_message(
  353. msg: "email.message.Message", encoding: Optional[str] = None
  354. ) -> tuple["Commit", bytes, Optional[bytes]]:
  355. """Extract a Commit object and patch from an e-mail message.
  356. Args:
  357. msg: An email message (email.message.Message)
  358. encoding: Encoding to use to encode Git commits
  359. Returns: Tuple with commit object, diff contents and git version
  360. """
  361. c = Commit()
  362. if encoding is None:
  363. encoding = "ascii"
  364. c.author = msg["from"].encode(encoding)
  365. c.committer = msg["from"].encode(encoding)
  366. try:
  367. patch_tag_start = msg["subject"].index("[PATCH")
  368. except ValueError:
  369. subject = msg["subject"]
  370. else:
  371. close = msg["subject"].index("] ", patch_tag_start)
  372. subject = msg["subject"][close + 2 :]
  373. c.message = (subject.replace("\n", "") + "\n").encode(encoding)
  374. first = True
  375. body = msg.get_payload(decode=True)
  376. if isinstance(body, str):
  377. body = body.encode(encoding)
  378. if isinstance(body, bytes):
  379. lines = body.splitlines(True)
  380. else:
  381. # Handle other types by converting to string first
  382. lines = str(body).encode(encoding).splitlines(True)
  383. line_iter = iter(lines)
  384. for line in line_iter:
  385. if line == b"---\n":
  386. break
  387. if first:
  388. if line.startswith(b"From: "):
  389. c.author = line[len(b"From: ") :].rstrip()
  390. else:
  391. c.message += b"\n" + line
  392. first = False
  393. else:
  394. c.message += line
  395. diff = b""
  396. for line in line_iter:
  397. if line == b"-- \n":
  398. break
  399. diff += line
  400. try:
  401. version = next(line_iter).rstrip(b"\n")
  402. except StopIteration:
  403. version = None
  404. return c, diff, version