diff.py 27 KB

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