diff.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. # diff.py
  2. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  3. #
  4. # This module is part of GitPython and is released under
  5. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  6. import re
  7. from git.cmd import handle_process_output
  8. from git.compat import defenc
  9. from git.util import finalize_process, hex_to_bin
  10. from .objects.blob import Blob
  11. from .objects.util import mode_str_to_int
  12. # typing ------------------------------------------------------------------
  13. from typing import (
  14. Any,
  15. Iterator,
  16. List,
  17. Match,
  18. Optional,
  19. Tuple,
  20. Type,
  21. TypeVar,
  22. Union,
  23. TYPE_CHECKING,
  24. cast,
  25. )
  26. from git.types import PathLike, Literal
  27. if TYPE_CHECKING:
  28. from .objects.tree import Tree
  29. from .objects import Commit
  30. from git.repo.base import Repo
  31. from git.objects.base import IndexObject
  32. from subprocess import Popen
  33. from git import Git
  34. Lit_change_type = Literal["A", "D", "C", "M", "R", "T", "U"]
  35. # def is_change_type(inp: str) -> TypeGuard[Lit_change_type]:
  36. # # return True
  37. # return inp in ['A', 'D', 'C', 'M', 'R', 'T', 'U']
  38. # ------------------------------------------------------------------------
  39. __all__ = ("Diffable", "DiffIndex", "Diff", "NULL_TREE")
  40. # Special object to compare against the empty tree in diffs
  41. NULL_TREE = object()
  42. _octal_byte_re = re.compile(b"\\\\([0-9]{3})")
  43. def _octal_repl(matchobj: Match) -> bytes:
  44. value = matchobj.group(1)
  45. value = int(value, 8)
  46. value = bytes(bytearray((value,)))
  47. return value
  48. def decode_path(path: bytes, has_ab_prefix: bool = True) -> Optional[bytes]:
  49. if path == b"/dev/null":
  50. return None
  51. if path.startswith(b'"') and path.endswith(b'"'):
  52. path = path[1:-1].replace(b"\\n", b"\n").replace(b"\\t", b"\t").replace(b'\\"', b'"').replace(b"\\\\", b"\\")
  53. path = _octal_byte_re.sub(_octal_repl, path)
  54. if has_ab_prefix:
  55. assert path.startswith(b"a/") or path.startswith(b"b/")
  56. path = path[2:]
  57. return path
  58. class Diffable(object):
  59. """Common interface for all object that can be diffed against another object of compatible type.
  60. :note:
  61. Subclasses require a repo member as it is the case for Object instances, for practical
  62. reasons we do not derive from Object."""
  63. __slots__ = ()
  64. # standin indicating you want to diff against the index
  65. class Index(object):
  66. pass
  67. def _process_diff_args(
  68. self, args: List[Union[str, "Diffable", Type["Diffable.Index"], object]]
  69. ) -> List[Union[str, "Diffable", Type["Diffable.Index"], object]]:
  70. """
  71. :return:
  72. possibly altered version of the given args list.
  73. Method is called right before git command execution.
  74. Subclasses can use it to alter the behaviour of the superclass"""
  75. return args
  76. def diff(
  77. self,
  78. other: Union[Type["Index"], "Tree", "Commit", None, str, object] = Index,
  79. paths: Union[PathLike, List[PathLike], Tuple[PathLike, ...], None] = None,
  80. create_patch: bool = False,
  81. **kwargs: Any,
  82. ) -> "DiffIndex":
  83. """Creates diffs between two items being trees, trees and index or an
  84. index and the working tree. It will detect renames automatically.
  85. :param other:
  86. Is the item to compare us with.
  87. If None, we will be compared to the working tree.
  88. If Treeish, it will be compared against the respective tree
  89. If Index ( type ), it will be compared against the index.
  90. If git.NULL_TREE, it will compare against the empty tree.
  91. It defaults to Index to assure the method will not by-default fail
  92. on bare repositories.
  93. :param paths:
  94. is a list of paths or a single path to limit the diff to.
  95. It will only include at least one of the given path or paths.
  96. :param create_patch:
  97. If True, the returned Diff contains a detailed patch that if applied
  98. makes the self to other. Patches are somewhat costly as blobs have to be read
  99. and diffed.
  100. :param kwargs:
  101. Additional arguments passed to git-diff, such as
  102. R=True to swap both sides of the diff.
  103. :return: git.DiffIndex
  104. :note:
  105. On a bare repository, 'other' needs to be provided as Index or as
  106. as Tree/Commit, or a git command error will occur"""
  107. args: List[Union[PathLike, Diffable, Type["Diffable.Index"], object]] = []
  108. args.append("--abbrev=40") # we need full shas
  109. args.append("--full-index") # get full index paths, not only filenames
  110. # remove default '-M' arg (check for renames) if user is overriding it
  111. if not any(x in kwargs for x in ('find_renames', 'no_renames', 'M')):
  112. args.append("-M")
  113. if create_patch:
  114. args.append("-p")
  115. else:
  116. args.append("--raw")
  117. args.append("-z")
  118. # in any way, assure we don't see colored output,
  119. # fixes https://github.com/gitpython-developers/GitPython/issues/172
  120. args.append("--no-color")
  121. if paths is not None and not isinstance(paths, (tuple, list)):
  122. paths = [paths]
  123. if hasattr(self, "Has_Repo"):
  124. self.repo: "Repo" = self.repo
  125. diff_cmd = self.repo.git.diff
  126. if other is self.Index:
  127. args.insert(0, "--cached")
  128. elif other is NULL_TREE:
  129. args.insert(0, "-r") # recursive diff-tree
  130. args.insert(0, "--root")
  131. diff_cmd = self.repo.git.diff_tree
  132. elif other is not None:
  133. args.insert(0, "-r") # recursive diff-tree
  134. args.insert(0, other)
  135. diff_cmd = self.repo.git.diff_tree
  136. args.insert(0, self)
  137. # paths is list here or None
  138. if paths:
  139. args.append("--")
  140. args.extend(paths)
  141. # END paths handling
  142. kwargs["as_process"] = True
  143. proc = diff_cmd(*self._process_diff_args(args), **kwargs)
  144. diff_method = Diff._index_from_patch_format if create_patch else Diff._index_from_raw_format
  145. index = diff_method(self.repo, proc)
  146. proc.wait()
  147. return index
  148. T_Diff = TypeVar("T_Diff", bound="Diff")
  149. class DiffIndex(List[T_Diff]):
  150. """Implements an Index for diffs, allowing a list of Diffs to be queried by
  151. the diff properties.
  152. The class improves the diff handling convenience"""
  153. # change type invariant identifying possible ways a blob can have changed
  154. # A = Added
  155. # D = Deleted
  156. # R = Renamed
  157. # M = Modified
  158. # T = Changed in the type
  159. change_type = ("A", "C", "D", "R", "M", "T")
  160. def iter_change_type(self, change_type: Lit_change_type) -> Iterator[T_Diff]:
  161. """
  162. :return:
  163. iterator yielding Diff instances that match the given change_type
  164. :param change_type:
  165. Member of DiffIndex.change_type, namely:
  166. * 'A' for added paths
  167. * 'D' for deleted paths
  168. * 'R' for renamed paths
  169. * 'M' for paths with modified data
  170. * 'T' for changed in the type paths
  171. """
  172. if change_type not in self.change_type:
  173. raise ValueError("Invalid change type: %s" % change_type)
  174. for diffidx in self:
  175. if diffidx.change_type == change_type:
  176. yield diffidx
  177. elif change_type == "A" and diffidx.new_file:
  178. yield diffidx
  179. elif change_type == "D" and diffidx.deleted_file:
  180. yield diffidx
  181. elif change_type == "C" and diffidx.copied_file:
  182. yield diffidx
  183. elif change_type == "R" and diffidx.renamed:
  184. yield diffidx
  185. elif change_type == "M" and diffidx.a_blob and diffidx.b_blob and diffidx.a_blob != diffidx.b_blob:
  186. yield diffidx
  187. # END for each diff
  188. class Diff(object):
  189. """A Diff contains diff information between two Trees.
  190. It contains two sides a and b of the diff, members are prefixed with
  191. "a" and "b" respectively to inidcate that.
  192. Diffs keep information about the changed blob objects, the file mode, renames,
  193. deletions and new files.
  194. There are a few cases where None has to be expected as member variable value:
  195. ``New File``::
  196. a_mode is None
  197. a_blob is None
  198. a_path is None
  199. ``Deleted File``::
  200. b_mode is None
  201. b_blob is None
  202. b_path is None
  203. ``Working Tree Blobs``
  204. When comparing to working trees, the working tree blob will have a null hexsha
  205. as a corresponding object does not yet exist. The mode will be null as well.
  206. But the path will be available though.
  207. If it is listed in a diff the working tree version of the file must
  208. be different to the version in the index or tree, and hence has been modified."""
  209. # precompiled regex
  210. re_header = re.compile(
  211. rb"""
  212. ^diff[ ]--git
  213. [ ](?P<a_path_fallback>"?[ab]/.+?"?)[ ](?P<b_path_fallback>"?[ab]/.+?"?)\n
  214. (?:^old[ ]mode[ ](?P<old_mode>\d+)\n
  215. ^new[ ]mode[ ](?P<new_mode>\d+)(?:\n|$))?
  216. (?:^similarity[ ]index[ ]\d+%\n
  217. ^rename[ ]from[ ](?P<rename_from>.*)\n
  218. ^rename[ ]to[ ](?P<rename_to>.*)(?:\n|$))?
  219. (?:^new[ ]file[ ]mode[ ](?P<new_file_mode>.+)(?:\n|$))?
  220. (?:^deleted[ ]file[ ]mode[ ](?P<deleted_file_mode>.+)(?:\n|$))?
  221. (?:^similarity[ ]index[ ]\d+%\n
  222. ^copy[ ]from[ ].*\n
  223. ^copy[ ]to[ ](?P<copied_file_name>.*)(?:\n|$))?
  224. (?:^index[ ](?P<a_blob_id>[0-9A-Fa-f]+)
  225. \.\.(?P<b_blob_id>[0-9A-Fa-f]+)[ ]?(?P<b_mode>.+)?(?:\n|$))?
  226. (?:^---[ ](?P<a_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))?
  227. (?:^\+\+\+[ ](?P<b_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))?
  228. """,
  229. re.VERBOSE | re.MULTILINE,
  230. )
  231. # can be used for comparisons
  232. NULL_HEX_SHA = "0" * 40
  233. NULL_BIN_SHA = b"\0" * 20
  234. __slots__ = (
  235. "a_blob",
  236. "b_blob",
  237. "a_mode",
  238. "b_mode",
  239. "a_rawpath",
  240. "b_rawpath",
  241. "new_file",
  242. "deleted_file",
  243. "copied_file",
  244. "raw_rename_from",
  245. "raw_rename_to",
  246. "diff",
  247. "change_type",
  248. "score",
  249. )
  250. def __init__(
  251. self,
  252. repo: "Repo",
  253. a_rawpath: Optional[bytes],
  254. b_rawpath: Optional[bytes],
  255. a_blob_id: Union[str, bytes, None],
  256. b_blob_id: Union[str, bytes, None],
  257. a_mode: Union[bytes, str, None],
  258. b_mode: Union[bytes, str, None],
  259. new_file: bool,
  260. deleted_file: bool,
  261. copied_file: bool,
  262. raw_rename_from: Optional[bytes],
  263. raw_rename_to: Optional[bytes],
  264. diff: Union[str, bytes, None],
  265. change_type: Optional[Lit_change_type],
  266. score: Optional[int],
  267. ) -> None:
  268. assert a_rawpath is None or isinstance(a_rawpath, bytes)
  269. assert b_rawpath is None or isinstance(b_rawpath, bytes)
  270. self.a_rawpath = a_rawpath
  271. self.b_rawpath = b_rawpath
  272. self.a_mode = mode_str_to_int(a_mode) if a_mode else None
  273. self.b_mode = mode_str_to_int(b_mode) if b_mode else None
  274. # Determine whether this diff references a submodule, if it does then
  275. # we need to overwrite "repo" to the corresponding submodule's repo instead
  276. if repo and a_rawpath:
  277. for submodule in repo.submodules:
  278. if submodule.path == a_rawpath.decode(defenc, "replace"):
  279. if submodule.module_exists():
  280. repo = submodule.module()
  281. break
  282. self.a_blob: Union["IndexObject", None]
  283. if a_blob_id is None or a_blob_id == self.NULL_HEX_SHA:
  284. self.a_blob = None
  285. else:
  286. self.a_blob = Blob(repo, hex_to_bin(a_blob_id), mode=self.a_mode, path=self.a_path)
  287. self.b_blob: Union["IndexObject", None]
  288. if b_blob_id is None or b_blob_id == self.NULL_HEX_SHA:
  289. self.b_blob = None
  290. else:
  291. self.b_blob = Blob(repo, hex_to_bin(b_blob_id), mode=self.b_mode, path=self.b_path)
  292. self.new_file: bool = new_file
  293. self.deleted_file: bool = deleted_file
  294. self.copied_file: bool = copied_file
  295. # be clear and use None instead of empty strings
  296. assert raw_rename_from is None or isinstance(raw_rename_from, bytes)
  297. assert raw_rename_to is None or isinstance(raw_rename_to, bytes)
  298. self.raw_rename_from = raw_rename_from or None
  299. self.raw_rename_to = raw_rename_to or None
  300. self.diff = diff
  301. self.change_type: Union[Lit_change_type, None] = change_type
  302. self.score = score
  303. def __eq__(self, other: object) -> bool:
  304. for name in self.__slots__:
  305. if getattr(self, name) != getattr(other, name):
  306. return False
  307. # END for each name
  308. return True
  309. def __ne__(self, other: object) -> bool:
  310. return not (self == other)
  311. def __hash__(self) -> int:
  312. return hash(tuple(getattr(self, n) for n in self.__slots__))
  313. def __str__(self) -> str:
  314. h: str = "%s"
  315. if self.a_blob:
  316. h %= self.a_blob.path
  317. elif self.b_blob:
  318. h %= self.b_blob.path
  319. msg: str = ""
  320. line = None # temp line
  321. line_length = 0 # line length
  322. for b, n in zip((self.a_blob, self.b_blob), ("lhs", "rhs")):
  323. if b:
  324. line = "\n%s: %o | %s" % (n, b.mode, b.hexsha)
  325. else:
  326. line = "\n%s: None" % n
  327. # END if blob is not None
  328. line_length = max(len(line), line_length)
  329. msg += line
  330. # END for each blob
  331. # add headline
  332. h += "\n" + "=" * line_length
  333. if self.deleted_file:
  334. msg += "\nfile deleted in rhs"
  335. if self.new_file:
  336. msg += "\nfile added in rhs"
  337. if self.copied_file:
  338. msg += "\nfile %r copied from %r" % (self.b_path, self.a_path)
  339. if self.rename_from:
  340. msg += "\nfile renamed from %r" % self.rename_from
  341. if self.rename_to:
  342. msg += "\nfile renamed to %r" % self.rename_to
  343. if self.diff:
  344. msg += "\n---"
  345. try:
  346. msg += self.diff.decode(defenc) if isinstance(self.diff, bytes) else self.diff
  347. except UnicodeDecodeError:
  348. msg += "OMITTED BINARY DATA"
  349. # end handle encoding
  350. msg += "\n---"
  351. # END diff info
  352. # Python2 silliness: have to assure we convert our likely to be unicode object to a string with the
  353. # right encoding. Otherwise it tries to convert it using ascii, which may fail ungracefully
  354. res = h + msg
  355. # end
  356. return res
  357. @property
  358. def a_path(self) -> Optional[str]:
  359. return self.a_rawpath.decode(defenc, "replace") if self.a_rawpath else None
  360. @property
  361. def b_path(self) -> Optional[str]:
  362. return self.b_rawpath.decode(defenc, "replace") if self.b_rawpath else None
  363. @property
  364. def rename_from(self) -> Optional[str]:
  365. return self.raw_rename_from.decode(defenc, "replace") if self.raw_rename_from else None
  366. @property
  367. def rename_to(self) -> Optional[str]:
  368. return self.raw_rename_to.decode(defenc, "replace") if self.raw_rename_to else None
  369. @property
  370. def renamed(self) -> bool:
  371. """:returns: True if the blob of our diff has been renamed
  372. :note: This property is deprecated, please use ``renamed_file`` instead.
  373. """
  374. return self.renamed_file
  375. @property
  376. def renamed_file(self) -> bool:
  377. """:returns: True if the blob of our diff has been renamed"""
  378. return self.rename_from != self.rename_to
  379. @classmethod
  380. def _pick_best_path(cls, path_match: bytes, rename_match: bytes, path_fallback_match: bytes) -> Optional[bytes]:
  381. if path_match:
  382. return decode_path(path_match)
  383. if rename_match:
  384. return decode_path(rename_match, has_ab_prefix=False)
  385. if path_fallback_match:
  386. return decode_path(path_fallback_match)
  387. return None
  388. @classmethod
  389. def _index_from_patch_format(cls, repo: "Repo", proc: Union["Popen", "Git.AutoInterrupt"]) -> DiffIndex:
  390. """Create a new DiffIndex from the given text which must be in patch format
  391. :param repo: is the repository we are operating on - it is required
  392. :param stream: result of 'git diff' as a stream (supporting file protocol)
  393. :return: git.DiffIndex"""
  394. ## FIXME: Here SLURPING raw, need to re-phrase header-regexes linewise.
  395. text_list: List[bytes] = []
  396. handle_process_output(proc, text_list.append, None, finalize_process, decode_streams=False)
  397. # for now, we have to bake the stream
  398. text = b"".join(text_list)
  399. index: "DiffIndex" = DiffIndex()
  400. previous_header: Union[Match[bytes], None] = None
  401. header: Union[Match[bytes], None] = None
  402. a_path, b_path = None, None # for mypy
  403. a_mode, b_mode = None, None # for mypy
  404. for _header in cls.re_header.finditer(text):
  405. (
  406. a_path_fallback,
  407. b_path_fallback,
  408. old_mode,
  409. new_mode,
  410. rename_from,
  411. rename_to,
  412. new_file_mode,
  413. deleted_file_mode,
  414. copied_file_name,
  415. a_blob_id,
  416. b_blob_id,
  417. b_mode,
  418. a_path,
  419. b_path,
  420. ) = _header.groups()
  421. new_file, deleted_file, copied_file = (
  422. bool(new_file_mode),
  423. bool(deleted_file_mode),
  424. bool(copied_file_name),
  425. )
  426. a_path = cls._pick_best_path(a_path, rename_from, a_path_fallback)
  427. b_path = cls._pick_best_path(b_path, rename_to, b_path_fallback)
  428. # Our only means to find the actual text is to see what has not been matched by our regex,
  429. # and then retro-actively assign it to our index
  430. if previous_header is not None:
  431. index[-1].diff = text[previous_header.end() : _header.start()]
  432. # end assign actual diff
  433. # Make sure the mode is set if the path is set. Otherwise the resulting blob is invalid
  434. # We just use the one mode we should have parsed
  435. a_mode = old_mode or deleted_file_mode or (a_path and (b_mode or new_mode or new_file_mode))
  436. b_mode = b_mode or new_mode or new_file_mode or (b_path and a_mode)
  437. index.append(
  438. Diff(
  439. repo,
  440. a_path,
  441. b_path,
  442. a_blob_id and a_blob_id.decode(defenc),
  443. b_blob_id and b_blob_id.decode(defenc),
  444. a_mode and a_mode.decode(defenc),
  445. b_mode and b_mode.decode(defenc),
  446. new_file,
  447. deleted_file,
  448. copied_file,
  449. rename_from,
  450. rename_to,
  451. None,
  452. None,
  453. None,
  454. )
  455. )
  456. previous_header = _header
  457. header = _header
  458. # end for each header we parse
  459. if index and header:
  460. index[-1].diff = text[header.end() :]
  461. # end assign last diff
  462. return index
  463. @staticmethod
  464. def _handle_diff_line(lines_bytes: bytes, repo: "Repo", index: DiffIndex) -> None:
  465. lines = lines_bytes.decode(defenc)
  466. # Discard everything before the first colon, and the colon itself.
  467. _, _, lines = lines.partition(":")
  468. for line in lines.split("\x00:"):
  469. if not line:
  470. # The line data is empty, skip
  471. continue
  472. meta, _, path = line.partition("\x00")
  473. path = path.rstrip("\x00")
  474. a_blob_id: Optional[str]
  475. b_blob_id: Optional[str]
  476. old_mode, new_mode, a_blob_id, b_blob_id, _change_type = meta.split(None, 4)
  477. # Change type can be R100
  478. # R: status letter
  479. # 100: score (in case of copy and rename)
  480. # assert is_change_type(_change_type[0]), f"Unexpected value for change_type received: {_change_type[0]}"
  481. change_type: Lit_change_type = cast(Lit_change_type, _change_type[0])
  482. score_str = "".join(_change_type[1:])
  483. score = int(score_str) if score_str.isdigit() else None
  484. path = path.strip()
  485. a_path = path.encode(defenc)
  486. b_path = path.encode(defenc)
  487. deleted_file = False
  488. new_file = False
  489. copied_file = False
  490. rename_from = None
  491. rename_to = None
  492. # NOTE: We cannot conclude from the existence of a blob to change type
  493. # as diffs with the working do not have blobs yet
  494. if change_type == "D":
  495. b_blob_id = None # Optional[str]
  496. deleted_file = True
  497. elif change_type == "A":
  498. a_blob_id = None
  499. new_file = True
  500. elif change_type == "C":
  501. copied_file = True
  502. a_path_str, b_path_str = path.split("\x00", 1)
  503. a_path = a_path_str.encode(defenc)
  504. b_path = b_path_str.encode(defenc)
  505. elif change_type == "R":
  506. a_path_str, b_path_str = path.split("\x00", 1)
  507. a_path = a_path_str.encode(defenc)
  508. b_path = b_path_str.encode(defenc)
  509. rename_from, rename_to = a_path, b_path
  510. elif change_type == "T":
  511. # Nothing to do
  512. pass
  513. # END add/remove handling
  514. diff = Diff(
  515. repo,
  516. a_path,
  517. b_path,
  518. a_blob_id,
  519. b_blob_id,
  520. old_mode,
  521. new_mode,
  522. new_file,
  523. deleted_file,
  524. copied_file,
  525. rename_from,
  526. rename_to,
  527. "",
  528. change_type,
  529. score,
  530. )
  531. index.append(diff)
  532. @classmethod
  533. def _index_from_raw_format(cls, repo: "Repo", proc: "Popen") -> "DiffIndex":
  534. """Create a new DiffIndex from the given stream which must be in raw format.
  535. :return: git.DiffIndex"""
  536. # handles
  537. # :100644 100644 687099101... 37c5e30c8... M .gitignore
  538. index: "DiffIndex" = DiffIndex()
  539. handle_process_output(
  540. proc,
  541. lambda byt: cls._handle_diff_line(byt, repo, index),
  542. None,
  543. finalize_process,
  544. decode_streams=False,
  545. )
  546. return index