GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — GitPython/git/diff.py at refs/heads/main · gitpython-developers/GitPython Expand file tree/ Copy pathdiff.pyMore file actions 864 lines (710 loc) · 31.2 KB / Copy pathdiff.pyFile metadata and controls864 lines (710 loc) · 31.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 # Copyright (C) 2008, 2009 Michael Trier ([email protected]) and contributors # # This module is part of GitPython and is released under the # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/ __all__ = ["DiffConstants", "NULL_TREE", "NULL_TREE_SHA", "INDEX", "Diffable", "DiffIndex", "Diff"] import enum import re from git import _backend from git.cmd import Git, handle_process_output from git.compat import defenc, safe_decode from git.objects.base import IndexObject from git.objects.blob import Blob from git.objects.util import mode_str_to_int from git.util import finalize_process, hex_to_bin # typing ------------------------------------------------------------------ from typing import ( Any, Iterator, List, Match, Optional, Sequence, Tuple, TYPE_CHECKING, TypeVar, Union, cast, ) from git.types import PathLike, Literal if TYPE_CHECKING: from subprocess import Popen from git.objects.commit import Commit from git.objects.tree import Tree from git.repo.base import Repo Lit_change_type = Literal["A", "D", "C", "M", "R", "T", "U"] # ------------------------------------------------------------------------ @enum.unique class DiffConstants(enum.Enum): """Special objects for :meth:`Diffable.diff`. See the :meth:`Diffable.diff` method's ``other`` parameter, which accepts various values including these. :note: These constants are also available as attributes of the :mod:`git.diff` module, the :class:`Diffable` class and its subclasses and instances, and the top-level :mod:`git` module. """ NULL_TREE = enum.auto() """Stand-in indicating you want to compare against the empty tree in diffs. Also accessible as :const:`git.NULL_TREE`, :const:`git.diff.NULL_TREE`, and :const:`Diffable.NULL_TREE`. """ INDEX = enum.auto() """Stand-in indicating you want to diff against the index. Also accessible as :const:`git.INDEX`, :const:`git.diff.INDEX`, and :const:`Diffable.INDEX`, as well as :const:`Diffable.Index`. The latter has been kept for backward compatibility and made an alias of this, so it may still be used. """ NULL_TREE: Literal[DiffConstants.NULL_TREE] = DiffConstants.NULL_TREE """Stand-in indicating you want to compare against the empty tree in diffs. See :meth:`Diffable.diff`, which accepts this as a value of its ``other`` parameter. This is an alias of :const:`DiffConstants.NULL_TREE`, which may also be accessed as :const:`git.NULL_TREE` and :const:`Diffable.NULL_TREE`. """ NULL_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" """SHA of Git's canonical empty tree object.""" INDEX: Literal[DiffConstants.INDEX] = DiffConstants.INDEX """Stand-in indicating you want to diff against the index. See :meth:`Diffable.diff`, which accepts this as a value of its ``other`` parameter. This is an alias of :const:`DiffConstants.INDEX`, which may also be accessed as :const:`git.INDEX` and :const:`Diffable.INDEX`, as well as :const:`Diffable.Index`. """ def _unquote_path(path: bytes) -> bytes: result = bytearray() escapes = { ord("a"): 7, ord("b"): 8, ord("f"): 12, ord("n"): 10, ord("r"): 13, ord("t"): 9, ord("v"): 11, } i = 0 while i < len(path): if path[i] != ord("\\") or i + 1 == len(path): result.append(path[i]) i += 1 continue if path[i + 1] in b"0123" and i + 3 < len(path) and all(c in b"01234567" for c in path[i + 2 : i + 4]): result.append(int(path[i + 1 : i + 4], 8)) i += 4 continue escaped = path[i + 1] if escaped in escapes or escaped in b'\\"': result.append(escapes.get(escaped, escaped)) else: result.extend(path[i : i + 2]) i += 2 return bytes(result) def decode_path(path: bytes, has_ab_prefix: bool = True) -> Optional[bytes]: if path == b"/dev/null": return None if path.startswith(b'"') and path.endswith(b'"'): path = _unquote_path(path[1:-1]) if has_ab_prefix: assert path.startswith(b"a/") or path.startswith(b"b/") path = path[2:] return path class Diffable: """Common interface for all objects that can be diffed against another object of compatible type. :note: Subclasses require a :attr:`repo` member, as it is the case for :class:`~git.objects.base.Object` instances. For practical reasons we do not derive from :class:`~git.objects.base.Object`. """ __slots__ = () repo: "Repo" """Repository to operate on. Must be provided by subclass or sibling class.""" NULL_TREE = NULL_TREE """Stand-in indicating you want to compare against the empty tree in diffs. See the :meth:`diff` method, which accepts this as a value of its ``other`` parameter. This is the same as :const:`DiffConstants.NULL_TREE`, and may also be accessed as :const:`git.NULL_TREE` and :const:`git.diff.NULL_TREE`. """ INDEX = INDEX """Stand-in indicating you want to diff against the index. See the :meth:`diff` method, which accepts this as a value of its ``other`` parameter. This is the same as :const:`DiffConstants.INDEX`, and may also be accessed as :const:`git.INDEX` and :const:`git.diff.INDEX`, as well as :class:`Diffable.INDEX`, which is kept for backward compatibility (it is now defined an alias of this). """ Index = INDEX """Stand-in indicating you want to diff against the index (same as :const:`~Diffable.INDEX`). This is an alias of :const:`~Diffable.INDEX`, for backward compatibility. See :const:`~Diffable.INDEX` and :meth:`diff` for details. :note: Although always meant for use as an opaque constant, this was formerly defined as a class. Its usage is unchanged, but static type annotations that attempt to permit only this object must be changed to avoid new mypy errors. This was previously not possible to do, though ``Type[Diffable.Index]`` approximated it. It is now possible to do precisely, using ``Literal[DiffConstants.INDEX]``. """ def _process_diff_args( self, args: List[Union[PathLike, "Diffable"]], ) -> List[Union[PathLike, "Diffable"]]: """ :return: Possibly altered version of the given args list. This method is called right before git command execution. Subclasses can use it to alter the behaviour of the superclass. """ return args def diff( self, other: Union[DiffConstants, "Tree", "Commit", str, None] = INDEX, paths: Union[PathLike, List[PathLike], Tuple[PathLike, ...], None] = None, create_patch: bool = False, allow_unsafe_options: bool = False, **kwargs: Any, ) -> "DiffIndex[Diff]": """Create diffs between two items being trees, trees and index or an index and the working tree. Detects renames automatically. :param other: This the item to compare us with. * If ``None``, we will be compared to the working tree. * If a :class:`~git.types.Tree_ish` or string, it will be compared against the respective tree. * If :const:`INDEX`, it will be compared against the index. * If :const:`NULL_TREE`, it will compare against the empty tree. This parameter defaults to :const:`INDEX` (rather than ``None``) so that the method will not by default fail on bare repositories. :param paths: This a list of paths or a single path to limit the diff to. It will only include at least one of the given path or paths. :param create_patch: If ``True``, the returned :class:`Diff` contains a detailed patch that if applied makes the self to other. Patches are somewhat costly as blobs have to be read and diffed. :param allow_unsafe_options: If ``True``, allow options such as ``--output``, ``--no-index``, and ``-O`` that can write to or read from arbitrary filesystem paths. :param kwargs: Additional arguments passed to :manpage:`git-diff(1)`, such as ``R=True`` to swap both sides of the diff. :return: A :class:`DiffIndex` representing the computed diff. :note: On a bare repository, `other` needs to be provided as :const:`INDEX`, or as an instance of :class:`~git.objects.tree.Tree` or :class:`~git.objects.commit.Commit`, or a git command error will occur. """ if not allow_unsafe_options: Git.check_unsafe_options( options=Git._option_candidates([other], kwargs), unsafe_options=self.repo.unsafe_git_diff_options, clusterable_short_options="46abceflmnpqrstuvwzBCDMNRW", ) from git.refs.symbolic import SymbolicReference if isinstance(other, (str, SymbolicReference)): other = self.repo.rev_parse(Git._check_revision(other)).hexsha native = _backend.tree_diff(self.repo, self, other, paths, create_patch, kwargs) if native is not NotImplemented: return native args: List[Union[PathLike, Diffable]] = [] args.append(f"--abbrev={self.repo._oid_size * 2}") args.append("--full-index") # Get full index paths, not only filenames. args.extend(("--no-ext-diff", "--no-textconv")) # Remove default '-M' arg (check for renames) if user is overriding it. if not any(x in kwargs for x in ("find_renames", "no_renames", "M")): args.append("-M") if create_patch: args.append("-p") args.append("--no-ext-diff") else: args.append("--raw") args.append("-z") # Ensure we never see colored output. # Fixes: https://github.com/gitpython-developers/GitPython/issues/172 args.append("--no-color") if paths is not None and not isinstance(paths, (tuple, list)): paths = [paths] diff_cmd = "diff" if other is INDEX: args.insert(0, "--cached") elif other is NULL_TREE: args.insert(0, "-r") # Recursive diff-tree. args.insert(0, "--root") diff_cmd = "diff_tree" elif other is not None: args.insert(0, "-r") # Recursive diff-tree. args.insert(0, str(other)) diff_cmd = "diff_tree" args.insert(0, self) # paths is a list or tuple here, or None. args.append("--") if paths: args.extend(paths) # END paths handling kwargs["as_process"] = True args = self._process_diff_args(args) proc = self.repo.git._call_process_safe(diff_cmd, *args, _config=["diff.mnemonicPrefix=false"], **kwargs) diff_method = Diff._index_from_patch_format if create_patch else Diff._index_from_raw_format index = diff_method(self.repo, proc) proc.wait() return index T_Diff = TypeVar("T_Diff", bound="Diff") class DiffIndex(List[T_Diff]): R"""An index for diffs, allowing a list of :class:`Diff`\s to be queried by the diff properties. The class improves the diff handling convenience. """ change_type: Sequence[Literal["A", "C", "D", "R", "M", "T"]] = ("A", "C", "D", "R", "M", "T") # noqa: F821 """Change type invariant identifying possible ways a blob can have changed: * ``A`` = Added * ``D`` = Deleted * ``R`` = Renamed * ``M`` = Modified * ``T`` = Changed in the type """ def iter_change_type(self, change_type: Lit_change_type) -> Iterator[T_Diff]: """ :return: Iterator yielding :class:`Diff` instances that match the given `change_type` :param change_type: Member of :attr:`DiffIndex.change_type`, namely: * 'A' for added paths * 'D' for deleted paths * 'R' for renamed paths * 'M' for paths with modified data * 'T' for changed in the type paths """ if change_type not in self.change_type: raise ValueError("Invalid change type: %s" % change_type) for diffidx in self: if diffidx.change_type == change_type: yield diffidx elif change_type == "A" and diffidx.new_file: yield diffidx elif change_type == "D" and diffidx.deleted_file: yield diffidx elif change_type == "C" and diffidx.copied_file: yield diffidx elif change_type == "R" and diffidx.renamed_file: yield diffidx elif change_type == "M" and diffidx.a_blob and diffidx.b_blob and diffidx.a_blob != diffidx.b_blob: yield diffidx # END for each diff class Diff: """A Diff contains diff information between two Trees. It contains two sides a and b of the diff. Members are prefixed with "a" and "b" respectively to indicate that. Diffs keep information about the changed blob objects, the file mode, renames, deletions and new files. For submodule changes, ``a_blob`` and ``b_blob`` are :class:`~git.objects.base.IndexObject` instances whose SHAs refer to commits in the submodule repository. There are a few cases where ``None`` has to be expected as member variable value: New File:: a_mode is None a_blob is None a_path is None Deleted File:: b_mode is None b_blob is None b_path is None Working Tree Blobs: When comparing to working trees, the working tree blob will have a null hexsha as a corresponding object does not yet exist. The mode will be null as well. The path will be available, though. If it is listed in a diff, the working tree version of the file must differ from the version in the index or tree, and hence has been modified. """ # Precompiled regex. re_header = re.compile( rb""" ^diff[ ]--git [ ](?P<header_names>(?P<a_path_fallback>"?[ab]/.+?"?) [ ](?P<b_path_fallback>"?[ab]/.+?"?))\n (?:^old[ ]mode[ ](?P<old_mode>\d+)\n ^new[ ]mode[ ](?P<new_mode>\d+)(?:\n|$))? (?:^similarity[ ]index[ ]\d+%\n ^rename[ ]from[ ](?P<rename_from>.*)\n ^rename[ ]to[ ](?P<rename_to>.*)(?:\n|$))? (?:^new[ ]file[ ]mode[ ](?P<new_file_mode>.+)(?:\n|$))? (?:^deleted[ ]file[ ]mode[ ](?P<deleted_file_mode>.+)(?:\n|$))? (?:^similarity[ ]index[ ]\d+%\n ^copy[ ]from[ ](?P<copied_from_name>.*)\n ^copy[ ]to[ ](?P<copied_file_name>.*)(?:\n|$))? (?:^index[ ](?P<a_blob_id>[0-9A-Fa-f]+) \.\.(?P<b_blob_id>[0-9A-Fa-f]+)[ ]?(?P<b_mode>.+)?(?:\n|$))? (?:^---[ ](?P<a_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))? (?:^\+\+\+[ ](?P<b_path>[^\t\n\r\f\v]*)[\t\r\f\v]*(?:\n|$))? """, re.VERBOSE | re.MULTILINE, ) # These can be used for comparisons. NULL_HEX_SHA = "0" * 40 NULL_BIN_SHA = b"\0" * 20 __slots__ = ( "a_blob", "b_blob", "a_mode", "b_mode", "a_rawpath", "b_rawpath", "new_file", "deleted_file", "copied_file", "raw_rename_from", "raw_rename_to", "diff", "change_type", "score", ) def __init__( self, repo: "Repo", a_rawpath: Optional[bytes], b_rawpath: Optional[bytes], a_blob_id: Union[str, bytes, None], b_blob_id: Union[str, bytes, None], a_mode: Union[bytes, str, None], b_mode: Union[bytes, str, None], new_file: bool, deleted_file: bool, copied_file: bool, raw_rename_from: Optional[bytes], raw_rename_to: Optional[bytes], diff: Union[str, bytes, None], change_type: Optional[Lit_change_type], score: Optional[int], ) -> None: assert a_rawpath is None or isinstance(a_rawpath, bytes) assert b_rawpath is None or isinstance(b_rawpath, bytes) self.a_rawpath = a_rawpath self.b_rawpath = b_rawpath self.a_mode = mode_str_to_int(a_mode) if a_mode else None self.b_mode = mode_str_to_int(b_mode) if b_mode else None # Determine whether this diff references a submodule. If it does then # we need to overwrite "repo" to the corresponding submodule's repo instead. if repo and a_rawpath and (self.a_mode == 0o160000 or self.b_mode == 0o160000): for submodule in repo.submodules: if submodule.path == safe_decode(a_rawpath): if submodule.module_exists(): repo = submodule.module() break # Gitlinks reference commits; generic index objects preserve their path and mode. self.a_blob: Union["IndexObject", None] if a_blob_id is None or not hex_to_bin(a_blob_id).strip(b"\0"): self.a_blob = None else: self.a_blob = (IndexObject if self.a_mode == 0o160000 else Blob)( repo, hex_to_bin(a_blob_id), mode=self.a_mode, path=self.a_path ) self.b_blob: Union["IndexObject", None] if b_blob_id is None or not hex_to_bin(b_blob_id).strip(b"\0"): self.b_blob = None else: self.b_blob = (IndexObject if self.b_mode == 0o160000 else Blob)( repo, hex_to_bin(b_blob_id), mode=self.b_mode, path=self.b_path ) self.new_file: bool = new_file self.deleted_file: bool = deleted_file self.copied_file: bool = copied_file # Be clear and use None instead of empty strings. assert raw_rename_from is None or isinstance(raw_rename_from, bytes) assert raw_rename_to is None or isinstance(raw_rename_to, bytes) self.raw_rename_from = raw_rename_from or None self.raw_rename_to = raw_rename_to or None self.diff = diff self.change_type: Union[Lit_change_type, None] = change_type self.score = score def __eq__(self, other: object) -> bool: for name in self.__slots__: if getattr(self, name) != getattr(other, name): return False # END for each name return True def __ne__(self, other: object) -> bool: return not (self == other) def __hash__(self) -> int: return hash(tuple(getattr(self, n) for n in self.__slots__)) def __str__(self) -> str: h = "%s" if self.a_blob: h %= self.a_blob.path elif self.b_blob: h %= self.b_blob.path msg = "" line = None line_length = 0 for b, n in zip((self.a_blob, self.b_blob), ("lhs", "rhs")): if b: line = "\n%s: %o | %s" % (n, b.mode, b.hexsha) else: line = "\n%s: None" % n # END if blob is not None line_length = max(len(line), line_length) msg += line # END for each blob # Add headline. h += "\n" + "=" * line_length if self.deleted_file: msg += "\nfile deleted in rhs" if self.new_file: msg += "\nfile added in rhs" if self.copied_file: msg += "\nfile %r copied from %r" % (self.b_path, self.a_path) if self.rename_from: msg += "\nfile renamed from %r" % self.rename_from if self.rename_to: msg += "\nfile renamed to %r" % self.rename_to if self.diff: msg += "\n---" try: msg += self.diff.decode(defenc) if isinstance(self.diff, bytes) else self.diff except UnicodeDecodeError: msg += "OMITTED BINARY DATA" # END handle encoding msg += "\n---" # END diff info return h + msg @property def a_path(self) -> Optional[str]: return safe_decode(self.a_rawpath) if self.a_rawpath else None @property def b_path(self) -> Optional[str]: return safe_decode(self.b_rawpath) if self.b_rawpath else None @property def rename_from(self) -> Optional[str]: return safe_decode(self.raw_rename_from) if self.raw_rename_from else None @property def rename_to(self) -> Optional[str]: return safe_decode(self.raw_rename_to) if self.raw_rename_to else None @property def renamed_file(self) -> bool: """:return: ``True`` if the blob of our diff has been renamed""" return self.raw_rename_from != self.raw_rename_to @classmethod def _pick_best_path(cls, path_match: bytes, rename_match: bytes, path_fallback_match: bytes) -> Optional[bytes]: if path_match: return decode_path(path_match) if rename_match: return decode_path(rename_match, has_ab_prefix=False) if path_fallback_match: return decode_path(path_fallback_match) return None @staticmethod def _same_path_in_header(names: bytes) -> Optional[bytes]: """Return the path that a ``diff --git a/<path> b/<path>`` line names twice. git separates the two names with a space but does not quote a path for containing one, so once the path contains ``" a/"`` or ``" b/"`` the line alone does not show where the first name ends. When no ``---``, ``+++``, rename or copy line names the file, both names are the same path, and the split is accepted only where the two halves agree, as ``git_header_name`` in git's ``apply.c`` does. A quoted first name ends at its closing quote. :return: The path without its ``a/`` prefix, or ``None`` if no split agrees. """ if names.startswith(b'"'): end = 1 while end < len(names) and names[end : end + 1] != b'"': end += 2 if names[end : end + 1] == b"\\" else 1 split = end + 1 else: # Equal unquoted paths have equal-length names, so only the midpoint # can separate them. Trying every space would copy the header quadratically. if len(names) % 2 == 0: return None split = len(names) // 2 if names[split : split + 1] != b" ": return None a_name, b_name = names[:split], names[split + 1 :] if a_name.startswith(b'"'): if not (a_name.endswith(b'"') and b_name.startswith(b'"') and b_name.endswith(b'"')): return None a_name, b_name = _unquote_path(a_name[1:-1]), _unquote_path(b_name[1:-1]) if a_name.startswith(b"a/") and b_name.startswith(b"b/") and a_name[2:] == b_name[2:]: return a_name[2:] return None @classmethod def _index_from_patch_format(cls, repo: "Repo", proc: Union["Popen", "Git.AutoInterrupt"]) -> DiffIndex["Diff"]: """Create a new :class:`DiffIndex` from the given process output which must be in patch format. :param repo: The repository we are operating on. :param proc: :manpage:`git-diff(1)` process to read from (supports :class:`Git.AutoInterrupt <git.cmd.Git.AutoInterrupt>` wrapper). :return: :class:`DiffIndex` """ # FIXME: Here SLURPING raw, need to re-phrase header-regexes linewise. text_list: List[bytes] = [] stderr_list: List[bytes] = [] def finalize_process_with_stderr(proc: Union["Popen", "Git.AutoInterrupt"]) -> None: finalize_process(proc, stderr=b"".join(stderr_list)) handle_process_output( proc, text_list.append, stderr_list.append, finalize_process_with_stderr, decode_streams=False ) # For now, we have to bake the stream. text = b"".join(text_list) index: "DiffIndex" = DiffIndex() previous_header: Union[Match[bytes], None] = None header: Union[Match[bytes], None] = None a_path, b_path = None, None # For mypy. a_mode, b_mode = None, None # For mypy. for _header in cls.re_header.finditer(text): ( header_names, a_path_fallback, b_path_fallback, old_mode, new_mode, rename_from, rename_to, new_file_mode, deleted_file_mode, copied_from_name, copied_file_name, a_blob_id, b_blob_id, b_mode, a_path, b_path, ) = _header.groups() new_file, deleted_file, copied_file = ( bool(new_file_mode), bool(deleted_file_mode), bool(copied_file_name), ) # Mode changes, binary files and empty files have no `---` and `+++` lines, # so only the `diff --git` line names them, and it names the same path twice. named_elsewhere = any((a_path, b_path, rename_from, rename_to, copied_from_name, copied_file_name)) same_path = None if named_elsewhere else cls._same_path_in_header(header_names) if same_path is None: a_path = cls._pick_best_path(a_path, rename_from or copied_from_name, a_path_fallback) b_path = cls._pick_best_path(b_path, rename_to or copied_file_name, b_path_fallback) else: a_path = b_path = same_path # Our only means to find the actual text is to see what has not been matched # by our regex, and then retro-actively assign it to our index. if previous_header is not None: index[-1].diff = text[previous_header.end() : _header.start()] # END assign actual diff # Make sure the mode is set if the path is set. Otherwise the resulting blob # is invalid. We just use the one mode we should have parsed. a_mode = old_mode or deleted_file_mode or (a_path and (b_mode or new_mode or new_file_mode)) b_mode = b_mode or new_mode or new_file_mode or (b_path and a_mode) index.append( Diff( repo, a_path, b_path, a_blob_id and a_blob_id.decode(defenc), b_blob_id and b_blob_id.decode(defenc), a_mode and a_mode.decode(defenc), b_mode and b_mode.decode(defenc), new_file, deleted_file, copied_file, decode_path(rename_from, has_ab_prefix=False) if rename_from else None, decode_path(rename_to, has_ab_prefix=False) if rename_to else None, None, None, None, ) ) previous_header = _header header = _header # END for each header we parse if index and header: index[-1].diff = text[header.end() :] # END assign last diff return index @staticmethod def _handle_diff_line(lines_bytes: bytes, repo: "Repo", index: DiffIndex["Diff"]) -> None: # Discard everything before the first colon, and the colon itself. _, _, lines = lines_bytes.partition(b":") # Each record is a metadata field starting with a colon, followed by one path, # or two for copies and renames, each terminated by NUL. A path may itself # start with a colon or contain a line feed, so read the fields in order # instead of splitting at colons. fields = iter(lines.rstrip(b"\n").split(b"\x00")) for meta in fields: if not meta: # The line data is empty, skip. continue metadata = (meta[1:] if meta.startswith(b":") else meta).decode("ascii") a_blob_id: Optional[str] b_blob_id: Optional[str] old_mode, new_mode, a_blob_id, b_blob_id, _change_type = metadata.split(None, 4) # Change type can be R100 # R: status letter # 100: score (in case of copy and rename) change_type: Lit_change_type = cast(Lit_change_type, _change_type[0]) score_str = "".join(_change_type[1:]) score = int(score_str) if score_str.isdigit() else None a_path = b_path = next(fields, b"") deleted_file = False new_file = False copied_file = False rename_from = None rename_to = None # NOTE: We cannot conclude from the existence of a blob to change type, # as diffs with the working do not have blobs yet. if change_type == "D": b_blob_id = None # Optional[str] deleted_file = True elif change_type == "A": a_blob_id = None new_file = True elif change_type == "C": copied_file = True b_path = next(fields, b"") elif change_type == "R": b_path = next(fields, b"") rename_from, rename_to = a_path, b_path elif change_type == "T": # Nothing to do. pass # END add/remove handling diff = Diff( repo, a_path, b_path, a_blob_id, b_blob_id, old_mode, new_mode, new_file, deleted_file, copied_file, rename_from, rename_to, "", change_type, score, ) index.append(diff) @classmethod def _index_from_raw_format(cls, repo: "Repo", proc: "Popen") -> "DiffIndex[Diff]": """Create a new :class:`DiffIndex` from the given process output which must be in raw format. :param repo: The repository we are operating on. :param proc: Process to read output from. :return: :class:`DiffIndex` """ # handles # :100644 100644 687099101... 37c5e30c8... M .gitignore index: "DiffIndex" = DiffIndex() text_list: List[bytes] = [] stderr_list: List[bytes] = [] def finalize_process_with_stderr(proc: Union["Popen", "Git.AutoInterrupt"]) -> None: finalize_process(proc, stderr=b"".join(stderr_list)) # Output is read line by line, but paths may contain line feeds, so parse # the records only once all of it has been read. handle_process_output( proc, text_list.append, stderr_list.append, finalize_process_with_stderr, decode_streams=False ) cls._handle_diff_line(b"".join(text_list), repo, index) return index |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |