patch.py 12 KB

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