# 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", "INDEX", "Diffable", "DiffIndex", "Diff"]
import enum
import re
import warnings
from git.cmd import handle_process_output
from git.compat import defenc
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,
Tuple,
TYPE_CHECKING,
TypeVar,
Union,
cast,
)
from git.types import Literal, PathLike
if TYPE_CHECKING:
from subprocess import Popen
from git.cmd import Git
from git.objects.base import IndexObject
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`.
"""
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`.
"""
_octal_byte_re = re.compile(rb"\\([0-9]{3})")
def _octal_repl(matchobj: Match) -> bytes:
value = matchobj.group(1)
value = int(value, 8)
value = bytes(bytearray((value,)))
return value
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 = path[1:-1].replace(b"\\n", b"\n").replace(b"\\t", b"\t").replace(b'\\"', b'"').replace(b"\\\\", b"\\")
path = _octal_byte_re.sub(_octal_repl, path)
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,
**kwargs: Any,
) -> "DiffIndex":
"""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 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.
"""
args: List[Union[PathLike, Diffable]] = []
args.append("--abbrev=40") # We need full shas.
args.append("--full-index") # Get full index paths, not only filenames.
# 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 = self.repo.git.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 = self.repo.git.diff_tree
elif other is not None:
args.insert(0, "-r") # Recursive diff-tree.
args.insert(0, other)
diff_cmd = self.repo.git.diff_tree
args.insert(0, self)
# paths is a list or tuple here, or None.
if paths:
args.append("--")
args.extend(paths)
# END paths handling
kwargs["as_process"] = True
proc = diff_cmd(*self._process_diff_args(args), **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 = ("A", "C", "D", "R", "M", "T")
"""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:
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.
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