patch.py 15 KB

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