|
| 1 | +"""Optional native implementation of library-managed Git operations. |
| 2 | +
|
| 3 | +Installing ``GitPython[gix]`` makes the ``gix`` module available. Unsupported |
| 4 | +operations return ``NotImplemented`` *before* doing work and use the existing |
| 5 | +CLI implementation. Native failures are never retried as CLI mutations. |
| 6 | +""" |
| 7 | + |
| 8 | +from collections import Counter |
| 9 | +from importlib import import_module |
| 10 | +import logging |
| 11 | +import os |
| 12 | +from threading import Lock |
| 13 | +from typing import Any, Callable, Dict, List, Sequence, Tuple |
| 14 | + |
| 15 | +from git.compat import safe_decode |
| 16 | +from git.exc import GitCommandError |
| 17 | + |
| 18 | +try: |
| 19 | + gix: Any = import_module("gix") |
| 20 | +except ModuleNotFoundError as exc: |
| 21 | + if exc.name != "gix": |
| 22 | + raise |
| 23 | + gix = None |
| 24 | + |
| 25 | +name = "gix" if gix is not None else "cli" |
| 26 | +_counts: Counter = Counter() |
| 27 | +_lock = Lock() |
| 28 | +_logger = logging.getLogger("git.backend") |
| 29 | + |
| 30 | + |
| 31 | +def record(method: str, outcome: str) -> None: |
| 32 | + with _lock: |
| 33 | + _counts[method, outcome] += 1 |
| 34 | + _logger.debug("%s: %s", method, outcome) |
| 35 | + |
| 36 | + |
| 37 | +def statistics() -> Dict[Tuple[str, str], int]: |
| 38 | + """Return counts by operation and native/fallback reason for this process.""" |
| 39 | + with _lock: |
| 40 | + return dict(_counts) |
| 41 | + |
| 42 | + |
| 43 | +class _Unsupported(Exception): |
| 44 | + """A capability decision made before a native mutation.""" |
| 45 | + |
| 46 | + |
| 47 | +def _fallback(method: str, reason: str) -> Any: |
| 48 | + record(method, "CLI: " + reason) |
| 49 | + return NotImplemented |
| 50 | + |
| 51 | + |
| 52 | +def _repository(command: Any, env: Dict[str, Any], *, query_config: bool = False) -> Any: |
| 53 | + if command._git_options or command._persistent_git_options: |
| 54 | + raise _Unsupported("global command options") |
| 55 | + overrides = {**command.environment(), **env} |
| 56 | + effective = {**os.environ, **overrides} |
| 57 | + path = overrides.get("GIT_DIR") |
| 58 | + if not path: |
| 59 | + raise _Unsupported("repository not bound") |
| 60 | + if not os.path.isabs(path): |
| 61 | + path = os.path.join(command.working_dir or os.getcwd(), path) |
| 62 | + for key in ("GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE"): |
| 63 | + if effective.get(key): |
| 64 | + raise _Unsupported("storage environment") |
| 65 | + supported = {"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"} |
| 66 | + supported.update( |
| 67 | + "GIT_%s_%s" % (role, field) for role in ("AUTHOR", "COMMITTER") for field in ("NAME", "EMAIL", "DATE") |
| 68 | + ) |
| 69 | + if any(key not in supported and value != os.environ.get(key) for key, value in overrides.items()): |
| 70 | + raise _Unsupported("command environment") |
| 71 | + options = gix.OpenOptions().open_path_as_is(True).bail_if_untrusted(True).strict_config(True) |
| 72 | + if not query_config: |
| 73 | + options = options.config_overrides( |
| 74 | + ["core.fsmonitor=false", "gc.auto=0", "maintenance.auto=false", "core.hooksPath=" + os.devnull] |
| 75 | + ) |
| 76 | + repo = gix.open_opts(path, options) |
| 77 | + if repo.config_snapshot().string("extensions.refStorage") == b"reftable": |
| 78 | + raise _Unsupported("reftable (GIX-1)") |
| 79 | + if effective.get("GIT_WORK_TREE"): |
| 80 | + workdir = effective["GIT_WORK_TREE"] |
| 81 | + if not os.path.isabs(workdir): |
| 82 | + workdir = os.path.join(command.working_dir or os.getcwd(), workdir) |
| 83 | + repo.set_workdir(workdir) |
| 84 | + return repo |
| 85 | + |
| 86 | + |
| 87 | +_HANDLERS: Dict[str, Callable[[Any, List[str], Dict[str, Any]], bytes]] = {} |
| 88 | + |
| 89 | + |
| 90 | +def dispatch( |
| 91 | + command: Any, method: str, args: Tuple[Any, ...], kwargs: Dict[str, Any], config: Sequence[str] = () |
| 92 | +) -> Any: |
| 93 | + if gix is None: |
| 94 | + return NotImplemented |
| 95 | + handler = _HANDLERS.get(method) |
| 96 | + if handler is None: |
| 97 | + return _fallback(method, "not converted") |
| 98 | + allowed = {"env", "stdout_as_string", "strip_newline_in_stdout", "with_extended_output"} |
| 99 | + if method == "merge_base": |
| 100 | + allowed.add("all") |
| 101 | + if method in ("hash_object", "mktree", "commit_tree"): |
| 102 | + allowed.add("istream") |
| 103 | + if kwargs.keys() - allowed: |
| 104 | + return _fallback(method, "command/process options") |
| 105 | + if config and method != "commit_tree": |
| 106 | + return _fallback(method, "configuration overrides") |
| 107 | + if config: |
| 108 | + kwargs = dict(kwargs, _config=config) |
| 109 | + kwargs = dict(kwargs, env={**command.environment(), **(kwargs.get("env") or {})}) |
| 110 | + try: |
| 111 | + args_list = command._unpack_args([arg for arg in args if arg is not None]) |
| 112 | + repo = _repository(command, kwargs.get("env", {}), query_config=method == "config") |
| 113 | + output = handler(repo, args_list, kwargs) |
| 114 | + except _Unsupported as exc: |
| 115 | + return _fallback(method, str(exc)) |
| 116 | + except GitCommandError: |
| 117 | + record(method, "native") |
| 118 | + raise |
| 119 | + except gix.Error as exc: |
| 120 | + _logger.debug("%s native read: %s", method, exc) |
| 121 | + return _fallback(method, "native read diagnostics") |
| 122 | + record(method, "native") |
| 123 | + if kwargs.get("strip_newline_in_stdout", True) and output.endswith(b"\n"): |
| 124 | + output = output[:-1] |
| 125 | + result = safe_decode(output) if kwargs.get("stdout_as_string", True) else output |
| 126 | + return (0, result, "") if kwargs.get("with_extended_output") else result |
0 commit comments