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/_backend.py at main · gitpython-developers/GitPython Expand file tree/ Copy path_backend.pyMore file actions 1267 lines (1148 loc) · 54.9 KB / Copy path_backend.pyFile metadata and controls1267 lines (1148 loc) · 54.9 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 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 """Optional native implementation of library-managed Git operations. Installing ``GitPython[gix]`` makes the ``gix`` module available. Unsupported operations return ``NotImplemented`` before mutation and use the existing CLI implementation. Native mutation failures are never retried through the CLI. """ from collections import Counter from importlib import import_module import io from itertools import islice import logging import os import re import stat from threading import Lock from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple, cast from git.compat import defenc, safe_decode, safe_encode from git.exc import GitCommandError _selection = os.environ.get("GIT_PYTHON_BACKEND") if _selection not in (None, "cli", "gix"): raise ValueError("GIT_PYTHON_BACKEND must be 'cli' or 'gix'") gix: Any = None if _selection != "cli": try: gix = import_module("gix") except ModuleNotFoundError as exc: if exc.name != "gix" or _selection == "gix": raise name = "gix" if gix is not None else "cli" _counts: Counter = Counter() _lock = Lock() _logger = logging.getLogger("git.backend") def record(method: str, outcome: str) -> None: with _lock: _counts[method, outcome] += 1 _logger.debug("%s: %s", method, outcome) def statistics() -> Dict[Tuple[str, str], int]: """Return counts by operation and native/fallback reason for this process.""" with _lock: return dict(_counts) class _Unsupported(Exception): """A capability decision made before a native mutation.""" def _fallback(method: str, reason: str) -> Any: record(method, "CLI: " + reason) return NotImplemented def discover_repository(path: str, environment: Dict[str, Any], *, from_worktree: bool = False) -> Any: """Open one discovery candidate; the caller controls parent traversal.""" if gix is None: return NotImplemented effective = {**os.environ, **environment} if any( effective.get(key) for key in ("GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE") ) or any(value != os.environ.get(key) for key, value in environment.items() if key != "GIT_WORK_TREE"): return _fallback("Repo.open", "storage or command environment") options = gix.OpenOptions().open_path_as_is(True).bail_if_untrusted(True).strict_config(True) options = options.config_overrides( ["core.fsmonitor=false", "gc.auto=0", "maintenance.auto=false", "core.hooksPath=" + os.devnull] ) try: repo = gix.open_opts(path, options) if os.path.isfile(path) and from_worktree: # Canonicalize the supplied checkout path and let Gix resolve both # its Git directory and worktree from that .git file. repo = gix.open_opts(os.path.realpath(path), options) elif os.path.isfile(path): # Reopening also makes Gix derive the worktree from its Git directory, # rather than retaining an arbitrary gitfile's location as a worktree. repo = gix.open_opts(os.path.realpath(repo.git_dir()), options) snapshot = repo.config_snapshot() if snapshot.string("extensions.refStorage") == b"reftable": return _fallback("Repo.open", "reftable (GIX-1)") if snapshot.string("extensions.compatObjectFormat") is not None: return _fallback("Repo.open", "compatibility object format (GIX-19)") # Discovery accepts undecodable HEADs; force the native reference decoder. repo.head() if not repo.is_bare() and repo.workdir() is None and not effective.get("GIT_WORK_TREE"): return _fallback("Repo.open", "missing native worktree metadata (GIX-14)") commondir = os.path.join(repo.git_dir(), "commondir") if os.path.lexists(commondir): # Gix ignores invalid commondir files on common repositories. A common # directory must have been resolved and contain actual shared storage. if os.path.realpath(repo.common_dir()) == os.path.realpath(repo.git_dir()) or not all( os.path.isdir(os.path.join(repo.common_dir(), entry)) for entry in ("objects", "refs") ): return _fallback("Repo.open", "common-directory validation (GIX-14)") record("Repo.open", "native") return repo except gix.Error as exc: # Retain Git's rejection/diagnostics for layouts Gix cannot open yet. _logger.debug("native discovery: %s", exc) return _fallback("Repo.open", "native discovery diagnostics") except RuntimeError as exc: if str(exc) != "native worker panicked": raise # Undecodable Windows commondir paths panic in GixPython 0.1.0. # Discovery is read-only; keep Git's validation and error contract. _logger.debug("native discovery: %s", exc) return _fallback("Repo.open", "native discovery worker panic (GIX-14)") def _repository(command: Any, env: Dict[str, Any], *, query_config: bool = False) -> Any: owner = command._repo() if command._repo is not None else None if owner is not None: return owner._get_gix_repository(command=command, env=env, query_config=query_config) return _open_repository(command, env, query_config=query_config) def _open_repository(command: Any, env: Dict[str, Any], *, query_config: bool = False) -> Any: if command._git_options or command._persistent_git_options: raise _Unsupported("global command options") overrides = {**command.environment(), **env} effective = {**os.environ, **overrides} path = overrides.get("GIT_DIR") if not path: raise _Unsupported("repository not bound") if not os.path.isabs(path): path = os.path.join(command.working_dir or os.getcwd(), path) for key in ("GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE"): if effective.get(key): raise _Unsupported("storage environment") supported = {"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"} supported.update( "GIT_%s_%s" % (role, field) for role in ("AUTHOR", "COMMITTER") for field in ("NAME", "EMAIL", "DATE") ) if any(key not in supported and value != os.environ.get(key) for key, value in overrides.items()): raise _Unsupported("command environment") options = gix.OpenOptions().open_path_as_is(True).bail_if_untrusted(True).strict_config(True) if not query_config: options = options.config_overrides( ["core.fsmonitor=false", "gc.auto=0", "maintenance.auto=false", "core.hooksPath=" + os.devnull] ) repo = gix.open_opts(path, options) snapshot = repo.config_snapshot() if snapshot.string("extensions.refStorage") == b"reftable": raise _Unsupported("reftable (GIX-1)") if snapshot.string("extensions.compatObjectFormat") is not None: raise _Unsupported("compatibility object format (GIX-19)") if effective.get("GIT_WORK_TREE"): workdir = effective["GIT_WORK_TREE"] if not os.path.isabs(workdir): workdir = os.path.join(command.working_dir or os.getcwd(), workdir) repo.set_workdir(workdir) return repo def _canonical_repository(repo: Any) -> Any: """Have Gix resolve repository metadata again from a canonical input path.""" path = os.fspath(repo.git_dir()) canonical = os.path.realpath(path) return gix.open_opts(canonical, repo.open_options()) if path != canonical else repo def _check_revision_grammar(ref: str) -> None: if ref.startswith(":/") or "^{/" in ref or "-dirty" in ref or re.search(r"-\d+-g[0-9a-fA-F]+|^[0-9a-fA-F]+-", ref): raise _Unsupported("revision grammar differences (GIX-17)") def _oid(repo: Any, ref: Any, env: Optional[Dict[str, Any]] = None) -> Any: ref = safe_decode(ref) if isinstance(ref, bytes) else str(ref) if re.fullmatch(r"[a-fA-F0-9]{40}|[a-fA-F0-9]{64}", ref): return gix.ObjectId(ref) _check_revision_grammar(ref) if ref.startswith(":"): _index(repo, {"env": env or {}}) if not hasattr(repo, "rev_parse_single"): raise _Unsupported("revision feature disabled") return repo.rev_parse_single(safe_encode(ref)) def object_data(command: Any, ref: bytes, *, stream: bool = False) -> Any: """Use native object reads without changing the public cat-file interface.""" if gix is None: return NotImplemented method = "stream_object_data" if stream else "get_object_header" try: repo = _repository(command, {}) oid = _oid(repo, ref, command.environment()) header = repo.try_find_header(oid) if header is None: raise ValueError("SHA %s could not be resolved" % oid) result: Tuple[Any, ...] = (str(oid), header.kind(), header.size()) if stream: # ponytail: native lookup buffers the object; use CLI above 8 MiB until GIX-2 provides streaming. if header.size() > 8 * 1024 * 1024: raise _Unsupported("large object streaming (GIX-2)") result += (io.BytesIO(repo.find_object(oid).data),) except _Unsupported as exc: return _fallback(method, str(exc)) except gix.Error as exc: _logger.debug("%s native read: %s", method, exc) return _fallback(method, "native read diagnostics") record(method, "native") return result def object_metadata(command: Any, oid: str, kind: str) -> Any: """Decode commit/tag fields through Gix's structured object APIs.""" if gix is None: return NotImplemented try: repo = _repository(command, {}) obj = getattr(repo, "find_" + kind)(gix.ObjectId(oid)) data = obj.decode() if kind == "commit": if data.encoding is not None and data.encoding.lower() not in (b"utf-8", b"utf8"): raise _Unsupported("commit text encoding (GIX-29)") if any(key == b"encoding" for key, _ in data.extra_headers): raise _Unsupported("commit encoding header order (GIX-30)") result = { "tree": data.tree.decode("ascii"), "parents": tuple(parent.decode("ascii") for parent in data.parents), "encoding": data.encoding, "message": data.message, "extra_headers": data.extra_headers, "author": obj.author(), "committer": obj.committer(), } else: result = { "target": data.target.decode("ascii"), "target_kind": data.target_kind, "name": data.name, "message": data.message, "signature": data.signature, "tagger": obj.tagger(), } signatures = ( ((data.author, result["author"]), (data.committer, result["committer"])) if kind == "commit" else ((data.tagger, result["tagger"]),) ) for raw, signature in signatures: # Gix reads a time zone of 0 with trailing fields (GIX-34); accept either UTC sign. if signature is not None and not raw.replace(b" -0000", b" +0000").endswith(b"> " + _date(signature)): raise _Unsupported("signature trailing fields (GIX-34)") except _Unsupported as exc: return _fallback(kind + ".decode", str(exc)) except gix.Error as exc: _logger.debug("%s native metadata: %s", kind, exc) return _fallback(kind + ".decode", "native decoder diagnostics") record(kind + ".decode", "native") return result def revision_info(command: Any, ref: str) -> Any: """Resolve an object and its tree/index path metadata in one native parse.""" if gix is None: return NotImplemented try: _check_revision_grammar(ref) repo = _repository(command, {}) if ref.startswith(":"): _index(repo, {"env": command.environment()}) spec = repo.rev_parse(safe_encode(ref)) oid = spec.single() if oid is None: raise _Unsupported("multiple revisions") metadata = spec.path_and_mode() except _Unsupported as exc: return _fallback("Repo.rev_parse", str(exc)) except gix.Error as exc: _logger.debug("native revision metadata: %s", exc) return _fallback("Repo.rev_parse", "native read diagnostics") record("Repo.rev_parse", "native") return str(oid), metadata def _rev_parse(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: from git.util import to_native_path_linux if args[:2] == ["--path-format=absolute", "--git-path"]: if len(args) != 3 or args[2] not in ("modules", "COMMIT_EDITMSG"): raise _Unsupported("Git metadata path resolution (GIX-22)") # Git keeps these fixed leaves in the private Git directory, including # linked worktrees. Other names have their own config/environment rules. path = os.path.join(_canonical_repository(repo).git_dir(), args[2]) if os.path.islink(path): raise _Unsupported("symlinked metadata path (GIX-22)") return os.fsencode(to_native_path_linux(path)) + b"\n" if args == ["--path-format=absolute", "--git-common-dir"]: return os.fsencode(to_native_path_linux(os.path.abspath(repo.common_dir()))) + b"\n" if args == ["--is-bare-repository"]: return b"true\n" if repo.is_bare() and repo.workdir() is None else b"false\n" if args == ["--show-object-format"]: return str(repo.object_hash()).encode("ascii") + b"\n" if args == ["--show-ref-format"]: # Config identifies reftable and HEAD reports it as unsupported, but # neither validates unknown repository extensions as Git's query does. raise _Unsupported("reference storage format query (GIX-1)") if args == ["--show-toplevel"] and repo.workdir() is not None: return os.fsencode(to_native_path_linux(os.path.abspath(repo.workdir()))) + b"\n" if args[:1] != ["--verify"] or args[-2:-1] != ["--end-of-options"]: raise _Unsupported("discovery or revision options") if args[:-2] not in (["--verify"], ["--verify", "--quiet"]): raise _Unsupported("revision options") return str(_oid(repo, args[-1], kwargs.get("env"))).encode("ascii") + b"\n" def _ls_tree(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) != 3 or args[:2] != ["-z", "--full-tree"]: raise _Unsupported("tree options") with repo.find_tree(_oid(repo, args[2])).iter() as entries: return b"".join( b"%06o %s %s\t%s\0" % ( entry.mode(), b"tree" if entry.kind() == "tree" else b"commit" if entry.kind() == "commit" else b"blob", str(entry.id()).encode("ascii"), entry.filename(), ) for entry in entries ) def check_ref_name(name: str) -> Any: """Validate a full reference name without opening a repository.""" if gix is None: return NotImplemented try: gix.Target.Symbolic(safe_encode(name)) except gix.Error as exc: if "/" not in name: return _fallback("Reference.validate", "standalone reference names (GIX-20)") record("Reference.validate", "native") raise ValueError("Invalid reference %r" % name) from exc record("Reference.validate", "native") return None def reference_info(command: Any, path: str) -> Any: """Read an exact reference target, including an absent reference, in one lookup.""" if gix is None: return NotImplemented try: if path != "HEAD" and not path.startswith("refs/"): raise _Unsupported("partial reference names") repo = _repository(command, {}) encoded_path = safe_encode(path) reference = repo.try_find_reference(encoded_path) result = None if reference is not None: if reference.name() != encoded_path: raise _Unsupported("partial reference lookup") target = reference.target() name = target.try_name() result = (None, safe_decode(name)) if name is not None else (str(target.try_id()), None) except _Unsupported as exc: return _fallback("Reference.read", str(exc)) except gix.Error as exc: _logger.debug("native reference read: %s", exc) return _fallback("Reference.read", "native read diagnostics") record("Reference.read", "native") return result def _symbolic_ref(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) != 4 or args[:3] != ["--quiet", "--no-recurse", "--"]: raise _Unsupported("reference mutation or options") reference = repo.try_find_reference(safe_encode(args[-1])) if reference is None or reference.name() != safe_encode(args[-1]): raise _Unsupported("missing reference diagnostics") target = reference.target().try_name() if target is None: raise GitCommandError(["git", "symbolic-ref"], 1) return target + b"\n" def _for_each_ref(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if not args or args[0] != "--format=%(refname)": raise _Unsupported("reference format/options") split = args.index("--") if "--" in args else len(args) if args[1:split] or len(args[split + 1 :]) > 1: raise _Unsupported("root refs or reference options") prefix = safe_encode(args[-1]) if len(args) > split + 1 else b"" if any(char in prefix for char in b"*?["): raise _Unsupported("reference glob patterns") with repo.references().all() as refs: names = [] for ref in refs: names.append(ref.name()) if ref.target().try_name() is not None: # Git omits dangling symbolic refs; defer their diagnostics to it. ref.follow_to_object() return b"".join( name + b"\n" for name in sorted(names) if not prefix or name == prefix or name.startswith(prefix.rstrip(b"/") + b"/") ) def submodule_config(source: Any) -> Any: """Read the fields used by submodule objects from their selected config source.""" if gix is None: return NotImplemented try: if isinstance(source, io.BytesIO): data = source.getvalue() else: with open(source, "rb") as stream: data = stream.read() # ponytail: no bound section enumeration; conservatively reject other '[' # occurrences and duplicate sections until GIX-12 can preserve their order. if b"\0" in data or re.search(rb"\[(?!submodule[ \t])", data, re.I): raise _Unsupported("non-submodule configuration sections (GIX-12)") modules = gix.ModulesFile.from_bytes(data) with modules.names() as cursor: names = list(cursor) if data.count(b"[") != len(names): raise _Unsupported("duplicate or ambiguous configuration sections (GIX-12)") config = modules.config() result = {} for raw_name in names: name = raw_name.decode(defenc) values = {} for option in ("path", "url", "branch"): key = "submodule." + name + "." + option value = config.string(key) if value is None: if option != "branch" or config.boolean(key) is not None: raise _Unsupported("missing or implicit submodule fields") else: values[option] = safe_decode(value) result[name] = values except _Unsupported as exc: return _fallback("Submodule.config", str(exc)) except (gix.Error, OSError, UnicodeError) as exc: _logger.debug("native submodule configuration: %s", exc) return _fallback("Submodule.config", "native parse diagnostics") record("Submodule.config", "native") return result def _config(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) == 2 and args[0] == "--get": snapshot = repo.config_snapshot() value = snapshot.string(args[1]) if value is None: if snapshot.boolean(args[1]) is None: raise GitCommandError(["git", "config"], 1) value = b"" # An implicit boolean is an empty value in --get output. return value + b"\n" raise _Unsupported("config file parsing, enumeration, or mutation (GIX-12)") def _worktree(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: from git.util import to_native_path_linux if args != ["list", "--porcelain", "-z"] or not hasattr(repo, "worktrees"): raise _Unsupported("worktree operation or feature disabled") proxies = repo.worktrees() if any(proxy.is_prunable() for proxy in proxies): raise _Unsupported("prunable worktree diagnostics") main = _canonical_repository(repo.main_repo()) def describe(local: Any) -> List[bytes]: workdir = local.workdir() fields = [b"worktree " + os.fsencode(to_native_path_linux(os.fspath(workdir or local.git_dir())))] # Gix's is_bare() reflects configuration, even for a linked worktree. if local.is_bare() and workdir is None: fields.append(b"bare") else: head = local.head() oid = head.id() fields.append( b"HEAD " + (str(oid).encode("ascii") if oid is not None else b"0" * local.object_hash().len_in_hex()) ) fields.append(b"detached" if head.is_detached() else b"branch " + head.referent_name()) return fields records = [b"\0".join(describe(main)) + b"\0\0"] for proxy in sorted(proxies, key=lambda proxy: os.fsencode(proxy.base())): fields = describe(proxy.into_repo()) if proxy.is_locked(): reason = proxy.lock_reason() fields.append(b"locked" + (b" " + reason if reason else b"")) records.append(b"\0".join(fields) + b"\0\0") return b"".join(records) def _worktree_root(command: Any, repo: Any) -> str: root = repo.workdir() if ( root is None or repo.prefix() is not None or os.path.realpath(command.working_dir or os.getcwd()) != os.path.realpath(root) ): raise _Unsupported("worktree or command working directory") return os.fspath(root) def is_dirty(command: Any, index: bool, working_tree: bool, untracked: bool, submodules: bool, path: Any) -> Any: if gix is None: return NotImplemented method = "Repo.is_dirty" try: repo = _repository(command, {}) _worktree_root(command, repo) if not hasattr(repo, "status"): raise _Unsupported("status feature disabled") patterns = [os.fspath(path)] if path else [] if any("\0" in pattern for pattern in patterns): raise _Unsupported("invalid pathspec") status = ( repo.status() .index(_index(repo, {"env": command.environment()})) .untracked_files("files" if untracked else "none") .tree_index_track_renames(None) .index_worktree_rewrites(None) .index_worktree_submodules("configured" if submodules else "all", check_dirty=submodules) ) dirty = False with status.into_iter([safe_encode(pattern) for pattern in patterns]) as entries: for item in entries: if item.summary() is None: continue if item.kind == "TreeIndex": if index and (submodules or item.details["entry_mode"] != 0o160000): dirty = True break elif item.details["kind"] == "DirectoryContents": if untracked and item.details["entry"]["status"] == "Untracked": dirty = True break elif working_tree: dirty = True break except _Unsupported as exc: return _fallback(method, str(exc)) except gix.Error as exc: _logger.debug("is_dirty native read: %s", exc) return _fallback(method, "native read diagnostics") record(method, "native") return dirty def untracked_files(command: Any, args: Tuple[Any, ...], options: Dict[str, Any]) -> Any: if gix is None: return NotImplemented method = "Repo.untracked_files" try: if options.keys() - {"ignore_submodules"}: raise _Unsupported("status options") repo = _repository(command, {}) _worktree_root(command, repo) if not hasattr(repo, "dirwalk_iter"): raise _Unsupported("dirwalk feature disabled") index = _index(repo, {"env": command.environment()}) patterns = command._unpack_args([arg for arg in args if arg is not None]) if any("\0" in path for path in patterns): raise _Unsupported("invalid pathspec") walk_options = repo.dirwalk_options().emit_untracked("matching").emit_tracked(False) result = [] with repo.dirwalk_iter(index, [safe_encode(pattern) for pattern in patterns], walk_options) as entries: for item in entries: entry = item.entry if entry.status == "Untracked": path = entry.rela_path if entry.disk_kind in ("Directory", "Repository"): path += b"/" result.append(path) result.sort() except _Unsupported as exc: return _fallback(method, str(exc)) except gix.Error as exc: _logger.debug("untracked_files native read: %s", exc) return _fallback(method, "native read diagnostics") record(method, "native") return [safe_decode(path) for path in result] def ignored(command: Any, paths: Sequence[Any]) -> Any: if gix is None: return NotImplemented method = "Repo.ignored" try: repo = _repository(command, {}) root = _worktree_root(command, repo) if not hasattr(repo, "excludes"): raise _Unsupported("excludes feature disabled") index = _index(repo, {"env": command.environment()}) excludes = repo.excludes(index) with index.entries() as entries: tracked = {entry.path() for entry in entries} result = [] for path in paths: path = os.fspath(path) relative = os.path.relpath(path, root) if os.path.isabs(path) else path relative = relative.replace(os.sep, "/") if any(part in (".", "..", ".git") for part in relative.split("/")) or relative.startswith(":"): raise _Unsupported("ignore path normalization") # check-ignore rejects traversal through symlinks and tracked gitlinks. parent = relative.rstrip("/") while "/" in parent: parent = parent.rsplit("/", 1)[0] if os.path.islink(os.path.join(root, parent)) or os.fsencode(parent) in tracked: raise _Unsupported("ignore path traverses symlink or submodule") if os.fsencode(relative.rstrip("/")) in tracked: continue mode: Optional[int] try: mode = os.lstat(os.path.join(root, relative)).st_mode except FileNotFoundError: mode = stat.S_IFDIR if relative.endswith("/") else None except OSError as exc: raise _Unsupported("ignore path metadata unavailable") from exc else: mode = 0o40000 if stat.S_ISDIR(mode) else 0o120000 if stat.S_ISLNK(mode) else 0o100644 if excludes.at_entry(os.fsencode(relative), mode).is_excluded(): result.append(path) except _Unsupported as exc: return _fallback(method, str(exc)) except gix.Error as exc: _logger.debug("ignored native read: %s", exc) return _fallback(method, "native read diagnostics") record(method, "native") return result def _merge_base(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if not hasattr(repo, "merge_base"): raise _Unsupported("revision feature disabled") ancestor = args[:1] == ["--is-ancestor"] if ancestor: args = args[1:] if len(args) != 3 or args[0] != "--": raise _Unsupported("merge-base options") one, two = (_oid(repo, value) for value in args[1:]) if kwargs.get("all"): ids = repo.merge_bases_many(one, [two]) else: base = repo.merge_base(one, two) ids = [base] if base is not None else [] if not ids or (ancestor and ids[0] != one): raise GitCommandError(["git", "merge-base"], 1) return b"" if ancestor else b"".join(str(oid).encode("ascii") + b"\n" for oid in ids) def _walk(repo: Any, rev: str, options: Dict[str, Any]) -> Iterator[str]: if not hasattr(repo, "rev_walk"): raise _Unsupported("revision feature disabled") if options.keys() - {"max_count", "skip", "first_parent"}: raise _Unsupported("history options or ordering (GIX-8)") if options.get("first_parent") not in (None, True, False): raise _Unsupported("history options") start, count = options.get("skip", 0), options.get("max_count") if type(start) is not int or start < 0 or (count is not None and (type(count) is not int or count < 0)): raise _Unsupported("history limits") tip = repo.find_object(_oid(repo, rev)).peel_to_commit().id platform = repo.rev_walk([tip]) if options.get("first_parent"): platform = platform.first_parent_only() cursor = platform.all() def iterate() -> Iterator[str]: try: with cursor: for item in islice(cursor, start, None if count is None else start + count): yield str(item.id) except gix.Error as exc: raise GitCommandError(["gix", "rev-list", rev], 128, str(exc)) from exc return iterate() def history(command: Any, rev: str, paths: Any, options: Dict[str, Any], *, count: bool = False) -> Any: """Count reachable commits, or lazily walk the first-parent chain.""" if gix is None: return NotImplemented method = "Commit.count" if count else "Commit.iter_items" try: if paths: raise _Unsupported("history path filtering") if ( not count and not options.get("first_parent") and not (options.get("max_count") == 1 and not options.get("skip")) ): raise _Unsupported("Git history ordering (GIX-8)") iterator = _walk(_repository(command, {}), rev, options) result = sum(1 for _ in iterator) if count else iterator except _Unsupported as exc: return _fallback(method, str(exc)) except gix.Error as exc: _logger.debug("%s native preparation: %s", method, exc) return _fallback(method, "native preparation diagnostics") record(method, "native") return result def _date(signature: Any) -> bytes: offset = signature.time.offset hours, minutes = divmod(abs(offset) // 60, 60) return b"%d %s%02d%02d" % (signature.time.seconds, b"-" if offset < 0 else b"+", hours, minutes) def _reflog(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) == 3 and args[:2] == ["exists", "--"]: reference = repo.try_find_reference(safe_encode(args[-1])) if reference is None: raise _Unsupported("orphan reflog lookup") if not reference.log_exists(): raise GitCommandError(["git", "reflog", "exists"], 1) return b"" if ( len(args) != 10 or args[:8] != [ "show", "--format=%H%x00%gn%x00%ge%x00%gD%x00%gs", "--date=raw", "-z", "--no-abbrev", "--no-decorate", "--no-notes", "--no-color", ] or args[-1] != "--" ): raise _Unsupported("reflog writing or format") reference = repo.try_find_reference(safe_encode(args[-2])) if reference is None: raise _Unsupported("orphan reflog lookup") cursor = reference.log_iter().rev() if cursor is None: return b"" output = [] with cursor: for line in cursor: if not repo.has_object(line.new_oid) or repo.find_header(line.new_oid).kind() != "commit": continue signature = line.signature output.append( b"\0".join( [ str(line.new_oid).encode("ascii"), signature.name, signature.email, os.fsencode(args[-2]) + b"@{" + _date(signature) + b"}", line.message, ] ) + b"\0" ) return b"".join(output) def _index(repo: Any, kwargs: Dict[str, Any]) -> Any: if not hasattr(repo, "index_or_empty"): raise _Unsupported("index feature disabled") path = kwargs.get("env", {}).get("GIT_INDEX_FILE", os.environ.get("GIT_INDEX_FILE")) if path and not os.path.isabs(path): raise _Unsupported("relative index path") if path and os.path.abspath(path) != os.path.abspath(repo.index_path()): raise _Unsupported("custom index path (GIX-3)") index = repo.index_or_empty() if index.is_sparse(): raise _Unsupported("sparse index (GIX-4)") return index def _ls_files(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if args != ["--stage", "-v", "-z", "--full-name"]: raise _Unsupported("index listing options") with _index(repo, kwargs).entries() as entries: output = [] for entry in entries: flag = b"S" if entry.flags & (1 << 30) else b"M" if entry.stage() else b"H" if entry.flags & (1 << 15): flag = flag.lower() output.append( b"%s %06o %s %d\t%s\0" % (flag, entry.mode, str(entry.id).encode("ascii"), entry.stage(), entry.path()) ) return b"".join(output) def _update_index(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if args != ["--show-index-version"]: raise _Unsupported("index mutation options") return str(_index(repo, kwargs).version()).encode("ascii") + b"\n" def _index_from_tree(repo: Any, tree: Any) -> Any: if not hasattr(repo, "index_from_tree"): raise _Unsupported("index feature disabled") if ( repo.config_snapshot().integer("index.version") not in (None, 2) or os.environ.get("GIT_INDEX_VERSION", "2") != "2" ): raise _Unsupported("new index version selection (GIX-13)") return repo.index_from_tree(tree) def _write(method: str, function: Callable[[], Any]) -> Any: """Once a write starts, an error must not cause a second attempt through Git.""" try: return function() except gix.Error as exc: raise GitCommandError(["gix", method], 128, str(exc)) from exc def _input(kwargs: Dict[str, Any]) -> bytes: stream = kwargs.get("istream") if stream is None or not hasattr(stream, "seekable") or not stream.seekable(): raise _Unsupported("nonseekable input") start = stream.tell() try: stream.seek(0, 2) if stream.tell() - start > 8 * 1024 * 1024: raise _Unsupported("large object streaming (GIX-2)") stream.seek(start) data = stream.read() finally: stream.seek(start) if not isinstance(data, bytes): raise _Unsupported("nonbinary input") return data def _hash_object(repo: Any, args: List[str], kwargs: Dict[str, Any]) -> bytes: if len(args) not in (3, 4) or args[0] != "-t" or args[-1] != "--stdin": raise _Unsupported("object hashing options") write = args[2:-1] == ["-w"] if args[2:-1] not in ([], ["-w"]): raise _Unsupported("object hashing options") kind = args[1] if kind not in ("blob", "tree", "commit", "tag"): raise _Unsupported("object kind") if kind == "tag": raise _Unsupported("strict tag object validation (GIX-28)") data = _input(kwargs) # Validate and check the encoded bytes in memory before touching object storage. memory = repo.with_object_memory() oid = memory.write_object(kind, data) if memory.find_object(oid).data != data: raise _Unsupported("object serialization changes bytes (GIX-5)") if write: oid = _write("hash_object", lambda: repo.write_object(kind, data)) kwargs["istream"].seek(len(data), 1) return str(oid).encode("ascii") + b"\n" _ENTRY_KINDS = {0o100644: "blob", 0o100755: "exe", 0o120000: "link", 0o160000: "commit", 0o40000: "tree"} def _write_tree(repo: Any, entries: Sequence[Tuple[bytes, int, str]]) -> str: names = {name for name, _mode, _oid in entries} if len(names) != len(entries): raise _Unsupported("duplicate or overlapping tree paths") for name in names: while b"/" in name: name = name.rsplit(b"/", 1)[0] if name in names: raise _Unsupported("duplicate or overlapping tree paths") for _path, mode, oid in entries: object_id = gix.ObjectId(oid) if object_id.is_null(): raise _Unsupported("null tree object IDs") header = repo.try_find_header(object_id) if header is None: if mode != 0o160000: raise _Unsupported("missing tree children (GIX-7)") elif header.kind() != ("tree" if mode == 0o40000 else "commit" if mode == 0o160000 else "blob"): raise _Unsupported("tree child object kind") with repo.empty_tree().edit() as editor: for path, mode, oid in entries: editor.upsert(path, _ENTRY_KINDS[mode], gix.ObjectId(oid)) return str(_write("write_tree", editor.write)) def write_tree(command: Any, entries: Sequence[Tuple[bytes, int, str]]) -> Any: if gix is None: return NotImplemented try: result = _write_tree(_repository(command, {}), entries) except _Unsupported as exc: return _fallback("IndexFile.write_tree", str(exc)) except gix.Error as exc: _logger.debug("write_tree native preparation: %s", exc) return _fallback("IndexFile.write_tree", "native preparation diagnostics") record("IndexFile.write_tree", "native") return result def tree_diff(repository: Any, left: Any, right: Any, paths: Any, patch: bool, options: Dict[str, Any]) -> Any: """Build GitPython's raw tree diff directly from native change records.""" if gix is None: return NotImplemented from git.diff import Diff, DiffIndex, Lit_change_type method = "Diffable.diff" try: if not hasattr(left, "hexsha") or not (hasattr(right, "hexsha") or isinstance(right, str)): raise _Unsupported("index/worktree/root diff") if patch or paths: raise _Unsupported("patch formatting or path filtering") if options.keys() - {"R", "no_renames"} or any(type(value) is not bool for value in options.values()): raise _Unsupported("diff options") if "no_renames" in options and not options["no_renames"]: raise _Unsupported("configured rename detection") repo = _repository(repository.git, {}) if not hasattr(repo, "diff_tree_to_tree"): raise _Unsupported("tree-diff feature disabled") before = repo.find_object(_oid(repo, left.hexsha)).peel_to_tree() after = repo.find_object(_oid(repo, getattr(right, "hexsha", right))).peel_to_tree() if options.get("R"): before, after = after, before diff_options = gix.DiffOptions().track_path().track_rewrites(None) changes = repo.diff_tree_to_tree(before, after, diff_options) if not options.get("no_renames"): added = [str(c.id()) for c in changes if c.kind == "Addition" and c.entry_mode() != 0o40000] deleted = [str(c.id()) for c in changes if c.kind == "Deletion" and c.entry_mode() != 0o40000] if added and deleted: if (set(added) - set(deleted) and set(deleted) - set(added)) or ( len(set(added)) != len(added) or len(set(deleted)) != len(deleted) ): raise _Unsupported("inexact or ambiguous rename detection (GIX-11)") # Exact rewrites need no blob filters, textconv, or external diff drivers. diff_options = diff_options.track_rewrites(gix.Rewrites(percentage=None)) changes = repo.diff_tree_to_tree(before, after, diff_options) result: DiffIndex[Diff] = DiffIndex() for change in changes: details = change.details kind, path, mode, oid = change.kind, change.location(), change.entry_mode(), str(change.id()) previous_mode = details.get("previous_entry_mode", details.get("source_entry_mode", mode)) previous_oid = str(details.get("previous_id", details.get("source_id", change.id()))) if mode == 0o40000 or previous_mode == 0o40000: if mode != previous_mode: raise _Unsupported("directory type change") continue new_file, deleted_file, renamed = kind == "Addition", kind == "Deletion", kind == "Rewrite" change_type = ( "A" if new_file else "D" if deleted_file else "R" if renamed else ("T" if mode & 0o170000 != previous_mode & 0o170000 else "M") ) source = change.source_location() if renamed else path result.append( Diff( repository, source, path, None if new_file else previous_oid, None if deleted_file else oid, "%06o" % (0 if new_file else previous_mode), "%06o" % (0 if deleted_file else mode), new_file, deleted_file, False, source if renamed else None, path if renamed else None, "", cast(Lit_change_type, change_type), 100 if renamed else None, ) ) result.sort(key=lambda diff: diff.b_rawpath or b"") except _Unsupported as exc: return _fallback(method, str(exc)) except gix.Error as exc: _logger.debug("tree_diff native read: %s", exc) return _fallback(method, "native read diagnostics") record(method, "native") return result def commit_stats(commit: Any) -> Any: """Count changed lines natively, retaining Git's statistics representation.""" if gix is None: return NotImplemented from git.util import Stats method = "Commit.stats" try: repo = _repository(commit.repo.git, {}) if not hasattr(repo, "diff_tree_to_tree") or not hasattr(repo, "attributes_only"): raise _Unsupported("diff or attributes feature disabled") if repo.config_snapshot().string("diff.algorithm") not in (None, b"myers", b"default"): raise _Unsupported("statistics diff algorithm") native = repo.find_commit(gix.ObjectId(commit.hexsha)) with native.parent_ids() as parents: parent = next(parents, None) |
| You are visitor 01402520 — 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. |