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/test/test_submodule.py at main · gitpython-developers/GitPython Expand file tree/ Copy pathtest_submodule.pyMore file actions 2748 lines (2367 loc) · 117 KB / Copy pathtest_submodule.pyFile metadata and controls2748 lines (2367 loc) · 117 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 # This module is part of GitPython and is released under the # 3-Clause BSD License: https://opensource.org/license/bsd-3-clause/ import gc from io import BytesIO import os import os.path as osp from pathlib import Path import shutil import sys from types import SimpleNamespace from unittest import mock, skipUnless import pytest import git from git.cmd import Git from git.config import GitConfigParser, cp from git.exc import ( GitCommandError, InvalidGitRepositoryError, RepositoryDirtyError, UnsafeOptionError, UnsafeProtocolError, ) from git.objects.submodule.base import Submodule from git.objects.submodule.root import RootModule, RootUpdateProgress from git.objects.submodule.util import resolve_relative_url from git.repo.fun import find_submodule_git_dir, touch from git.util import cwd, join_path_native, to_native_path_linux from test.lib import TestBase, patch_git_config, with_rw_repo, PathLikeMock from test.lib.fixtures import fixture_repo, read_only_fixture, writable_fixture @pytest.mark.parametrize("scenario, name", [("ascii-name", "module"), ("byte-name", "module-\udcff")]) def test_submodule_configuration_preserves_non_utf8_bytes(scenario, name): with fixture_repo("submodule-bytes.sh", scenario) as repo: data = repo.git.config("list", "--null", "--file", ".gitmodules", stdout_as_string=False) assert b".path\npath-\xfe\0" in data assert b".url\nurl-\xfd\0" in data assert b".branch\nrefs/heads/branch-\xfc\0" in data submodule = repo.submodules[0] assert submodule.name == name assert submodule.path == "path-\udcfe" assert submodule.url == "url-\udcfd" assert submodule.branch_path == "refs/heads/branch-\udcfc" submodule._clear_cache() assert (submodule.path, submodule.url, submodule.branch_path) == ( "path-\udcfe", "url-\udcfd", "refs/heads/branch-\udcfc", ) @pytest.mark.skipif(git._backend.name != "gix", reason="requires the native backend") def test_native_submodule_configuration_preserves_non_utf8_values(): path = read_only_fixture("submodule-bytes.sh", "ascii-name") / "repo" / ".gitmodules" with mock.patch.object(Git, "execute", side_effect=AssertionError("Git must not run")): native = git._backend.submodule_config(BytesIO(path.read_bytes())) assert native == {"module": {"path": "path-\udcfe", "url": "url-\udcfd", "branch": "refs/heads/branch-\udcfc"}} @pytest.mark.parametrize("state", ["unborn", "untracked", "detached"]) @pytest.mark.parametrize("remote", [None, ".", "origin"], ids=["working-tree", "local-origin", "origin"]) @patch_git_config("protocol.file.allow", "always") def test_add_relative_submodule_without_tracking_remote(state, remote): # Origins and submodule URLs refer to this private fixture's absolute paths. with writable_fixture("submodule-relative.sh", "add", state, remote, execute=True) as fixture: root = fixture.path().resolve() with git.Repo(root / "parent") as parent, git.Repo(root / (root / "source-path").read_text()) as source: submodule = parent.create_submodule("module", "module", "./source") assert submodule.url == "./source" with submodule.module() as module: assert module.head.commit == source.head.commit assert Path(module.remotes.origin.url).samefile(source.working_tree_dir) parent.index.commit("Add submodule") submodule.remove(configuration=False) submodule.update(init=True) with submodule.module() as module: assert module.head.commit == source.head.commit assert Path(module.remotes.origin.url).samefile(source.working_tree_dir) @pytest.mark.parametrize("url", ["./source", "../source", "./../source"]) def test_add_preserves_relative_url_on_cygwin(url): with writable_fixture("submodule-relative.sh", "cygwin") as fixture: root = fixture.path().resolve() with git.Repo(root / "parent") as parent, git.Repo(root / "source") as source: with mock.patch.object(Submodule, "_clone_repo", return_value=source): with mock.patch.object(Git, "is_cygwin", return_value=True): submodule = parent.create_submodule("module", "module", url, no_checkout=True) assert submodule.url == url with submodule.config_reader() as reader: assert reader.get_value("url") == url with parent.config_reader() as reader: assert reader.get_value('submodule "module"', "url") == url @patch_git_config("protocol.file.allow", "always") def test_update_resolves_local_relative_remote_once(): with writable_fixture("submodule-relative.sh", "local-remote") as fixture: root = fixture.path().resolve() with git.Repo(root / "parent") as parent, git.Repo(root / "repos" / "child.git") as source: submodule = Submodule( parent, source.head.commit.binsha, name="module", path="module", url="../child.git", branch_path="refs/heads/master", ) submodule.update(init=True) with submodule.module() as module: assert module.head.commit == source.head.commit assert Path(module.remotes.origin.url).samefile(source.working_tree_dir) module.remotes.origin.fetch() @pytest.mark.parametrize("no_fetch", [False, True]) @pytest.mark.parametrize("scenario", ["root-anchor", "root-single"]) @patch_git_config("protocol.file.allow", "always") def test_root_update_resolves_relative_remote_url(scenario, no_fetch): # Module origins and .gitmodules URLs contain this private fixture's absolute paths. with writable_fixture("submodule-relative.sh", scenario, execute=True) as fixture: root = fixture.path().resolve() with git.Repo(root / "parent") as parent, git.Repo( root / (root / "replacement-path").read_text() ) as replacement: previous = (root / "previous").read_text().strip() RootModule(parent).update(previous_commit=previous, no_fetch=no_fetch) with parent.submodules[0].module() as module: assert Path(module.remotes.origin.url).samefile(replacement.working_tree_dir) assert module.head.commit == replacement.head.commit module.remotes.origin.fetch() @pytest.mark.parametrize("dry_run", [False, True]) def test_root_update_skips_old_url_resolution_when_remote_matches(dry_run): # The matching remote and .gitmodules URL refer to this private fixture's source. with writable_fixture("submodule-relative.sh", "root-matches", execute=True) as fixture: root = fixture.path().resolve() with git.Repo(root / "parent") as parent, git.Repo(root / "source") as source: previous = (root / "previous").read_text().strip() resolve_url = Submodule._resolved_url with parent.submodules[0].module() as module: original_url = module.remotes.origin.url assert Path(original_url).samefile(source.working_tree_dir) def resolve_current_url(sm): assert sm.url != "../source", "Previous URL does not need resolving" return resolve_url(sm) with mock.patch.object(Submodule, "_resolved_url", autospec=True, side_effect=resolve_current_url): RootModule(parent).update(previous_commit=previous, no_fetch=True, dry_run=dry_run) with parent.submodules[0].module() as module: assert module.remotes.origin.url == original_url assert Path(module.remotes.origin.url).samefile(source.working_tree_dir) assert module.head.commit == source.head.commit @patch_git_config("protocol.file.allow", "user") def test_update_applies_git_transport_policy_to_gitmodules_url(monkeypatch): monkeypatch.setenv("GIT_PROTOCOL_FROM_USER", "1") # The cloned origins and .gitmodules URLs point to this private source. with writable_fixture("submodule-transport.sh", "update", execute=True) as fixture: root = fixture.path().resolve() with git.Repo(root / "source") as source, git.Repo(root / "clone") as clone, git.Repo( root / "baseline" ) as baseline: submodule = clone.submodules[0] with pytest.raises(GitCommandError, match="transport 'file' not allowed"): baseline.git.submodule("update", "--init") assert not Path(baseline.working_tree_dir, "module", ".git").exists() with pytest.raises(GitCommandError, match="transport 'file' not allowed"): submodule.update(init=True) assert not submodule.module_exists() with patch_git_config("protocol.file.allow", "always"): baseline.git.submodule("update", "--init") submodule.update(init=True) with submodule.module() as module, git.Repo(root / "baseline" / "module") as baseline_module: assert module.head.commit.hexsha == baseline_module.git.rev_parse("HEAD") == source.head.commit.hexsha source.index.commit("Second commit", skip_hooks=True) with pytest.raises(GitCommandError, match="transport 'file' not allowed"): baseline.git.submodule("update", "--remote") with pytest.raises(GitCommandError, match="transport 'file' not allowed"): submodule.update(to_latest_revision=True) assert module.head.commit.hexsha == baseline_module.git.rev_parse("HEAD") != source.head.commit.hexsha with patch_git_config("protocol.file.allow", "always"): baseline.git.submodule("update", "--remote") submodule.update(to_latest_revision=True, allow_unsafe_protocols=True) assert module.head.commit.hexsha == baseline_module.git.rev_parse("HEAD") == source.head.commit.hexsha @patch_git_config("protocol.file.allow", "user") def test_root_update_applies_git_transport_policy_to_changed_url(monkeypatch): monkeypatch.setenv("GIT_PROTOCOL_FROM_USER", "1") # The submodule URLs point to this private source and replacement. with writable_fixture("submodule-transport.sh", "changed-url", execute=True) as fixture: root = fixture.path().resolve() with git.Repo(root / "source") as source, git.Repo(root / "parent") as parent, git.Repo( root / "baseline" ) as baseline, git.Repo(root / "baseline" / "module") as baseline_module: submodule = parent.submodules[0] previous = (root / "previous").read_text().strip() # A rejected fetch preserves the original remote and checked-out commit. with baseline_module.git.custom_environment(GIT_PROTOCOL_FROM_USER="0"): with pytest.raises(GitCommandError, match="transport 'file' not allowed"): baseline_module.git.fetch(str(root / "replacement")) assert Path(baseline_module.remotes.origin.url).samefile(source.working_tree_dir) assert baseline_module.git.rev_parse("HEAD") == source.head.commit.hexsha baseline.git.submodule("sync") with pytest.raises(GitCommandError, match="transport 'file' not allowed"): baseline.git.submodule("update", "--remote") with pytest.raises(GitCommandError, match="transport 'file' not allowed"): RootModule(parent).update(previous_commit=previous) with submodule.module() as module: assert Path(module.remotes.origin.url).samefile(source.working_tree_dir) assert module.head.commit.hexsha == baseline_module.git.rev_parse("HEAD") == source.head.commit.hexsha @pytest.mark.parametrize( "scenario,name", [ ("plain", "module"), ("dollar", "$GITPYTHON_TEST_SECRET"), ("braced-dollar", "prefix-${GITPYTHON_TEST_SECRET}-suffix"), ("percent", "%GITPYTHON_TEST_SECRET%"), ], ) @patch_git_config("protocol.file.allow", "always") def test_submodule_update_preserves_literal_name(monkeypatch, caplog, scenario, name): monkeypatch.setenv("GITPYTHON_TEST_SECRET", "sensitive-value") caplog.set_level("DEBUG", logger="git.cmd") # Cloned origins and submodule URLs refer to this private fixture's absolute paths. with writable_fixture("submodule-special.sh", "literal-name", scenario, execute=True) as fixture: with git.Repo(fixture.path().resolve() / "source") as source, git.Repo( fixture.path().resolve() / "clone" ) as clone: assert clone.git.config("--file", ".gitmodules", f"submodule.{name}.path") == "module" clone.submodule_update(init=True, recursive=True) modules_dir = Path(clone.git_dir, "modules") assert {path.name for path in modules_dir.iterdir()} == {name} # Exercise relative gitfile conversion on every platform. with mock.patch.object(Git, "is_cygwin", return_value=True): resolved_git_dir = find_submodule_git_dir(Path(clone.working_tree_dir, "module", ".git")) assert resolved_git_dir is not None assert (modules_dir / name).samefile(resolved_git_dir) with clone.submodules[0].module() as module: assert (modules_dir / name).samefile(module.git_dir) assert module.head.commit == source.head.commit assert "sensitive-value" not in caplog.text def test_reconnect_preserves_existing_gitfile(movable_submodule, monkeypatch): """Reconnecting must not rename already-connected metadata onto itself.""" sm = movable_submodule metadata = str(Path(sm.repo.git_dir, "modules", sm.name)) commit = sm.hexsha moved = Path(sm.abspath).with_name("moved") original = (moved / ".git").read_bytes() execute = Git.execute def reject_reinitialization(self, command, *args, **kwargs): if "init" in command: # Git for Windows can reject renaming a nonempty directory onto # itself, even when both paths name the same existing repository. raise GitCommandError(command, 128, "unable to move metadata to itself: Directory not empty") return execute(self, command, *args, **kwargs) monkeypatch.setattr(Git, "execute", reject_reinitialization) Submodule._connect_module(moved, metadata) assert (moved / ".git").read_bytes() == original with git.Repo(moved) as reopened: assert Path(reopened.git_dir).samefile(metadata) assert Path(reopened.working_tree_dir).samefile(moved) assert reopened.head.commit.hexsha == commit assert (moved / "file").read_text() == "content" def test_reconnect_validates_connected_metadata(movable_submodule): sm = movable_submodule metadata = Path(sm.repo.git_dir, "modules", sm.name) config = metadata / "config" before = config.read_bytes() with pytest.raises(GitCommandError): Submodule._connect_module(sm.abspath, str(metadata)) assert config.read_bytes() == before @pytest.mark.parametrize("object_format", ["sha1", "sha256"]) @pytest.mark.parametrize("ref_format", ["files", "reftable"]) def test_submodule_cli_lifecycle(monkeypatch, object_format, ref_format): """Git owns submodule storage throughout add, move, reconnect, and removal.""" monkeypatch.setenv("GIT_AUTHOR_NAME", "Test") monkeypatch.setenv("GIT_COMMITTER_NAME", "Test") with writable_fixture("submodule-special.sh", "lifecycle", object_format, ref_format) as fixture: with git.Repo(fixture.path().resolve() / "source") as source, git.Repo( fixture.path().resolve() / "parent" ) as parent: commit = source.head.commit module = parent.create_submodule("logical-name", "module", source.working_tree_dir) with module.module() as child: if child.git.rev_parse("--show-ref-format") != ref_format: child.git.refs("migrate", "--ref-format=" + ref_format) parent.index.commit("Add submodule", skip_hooks=True) module.move("moved") parent.index.commit("Move submodule", skip_hooks=True) assert module.name == "logical-name" module.deinit(force=True) module.update(init=True, no_fetch=True) with module.module() as child: assert child.head.commit == commit assert not child.is_dirty(untracked_files=True) metadata = Path(child.git_dir) module.remove(force=True) assert not Path(parent.working_tree_dir, "moved").exists() assert metadata.is_dir() assert not parent.submodules @pytest.mark.skipif(os.name == "nt", reason="'*' is not a valid Windows filename") @pytest.mark.parametrize("operation", ["remove", "move"]) def test_submodule_index_update_matches_its_path_literally(operation): with fixture_repo("submodule-special.sh", "glob-path", write=True, subdir="parent") as repo: submodule = repo.submodules[0] assert submodule.path == "*" if operation == "remove": submodule.remove() expected = {".gitmodules", "README"} else: submodule.move("moved", module=False) expected = {".gitmodules", "README", "moved"} assert {entry.path for entry in repo.index.iter_entries()} == expected @pytest.mark.skipif(sys.platform != "win32", reason="Windows locks files against directory renames") @pytest.mark.parametrize("use_short_path", [False, True]) def test_submodule_reconnect_with_open_metadata_file(use_short_path): # The gitfile must point to this fixture's final metadata directory. with writable_fixture("submodule-special.sh", "open-metadata", execute=True) as fixture: root = fixture.path().resolve() if use_short_path: import ctypes buffer = ctypes.create_unicode_buffer(32768) if not ctypes.windll.kernel32.GetShortPathNameW(str(root), buffer, len(buffer)): raise ctypes.WinError() if buffer.value == str(root): pytest.skip("This filesystem does not provide Windows 8.3 path aliases") root = Path(buffer.value) assert root.samefile(fixture.path()) checkout = root / "checkout" metadata = fixture.path().resolve() / "metadata" with git.Repo(checkout) as repo: # Like a retained pack mapping, this open file prevents renaming metadata. object_file = metadata / "objects" / "held-open" with object_file.open("rb"): Submodule._connect_module(checkout, metadata) assert Path(repo.git.rev_parse("--absolute-git-dir")).samefile(metadata) with git.Repo(checkout) as reopened: assert Path(reopened.working_tree_dir).samefile(checkout) assert Path(reopened.git_dir).samefile(metadata) @pytest.fixture(scope="module") def submodule_source(): return read_only_fixture("submodule-source.sh") / "source" @pytest.fixture(scope="module") def movable_submodule_baseline(submodule_source): def prepare(name): return read_only_fixture("submodule-layout.sh", str(submodule_source), name) / "parent" return prepare @pytest.fixture def movable_submodule(request, submodule_source): arguments = [str(submodule_source), getattr(request, "param", "logical-name")] if request.node.originalname == "test_reconnect_preserves_existing_gitfile": arguments.extend(["reconnect-moved"]) elif request.node.originalname == "test_reconnect_validates_connected_metadata": arguments.extend(["unknown-extension"]) elif request.node.originalname == "test_update_closes_checkout_processes_retained_by_logging": arguments.extend(["logging", request.node.callspec.params["operation"]]) with fixture_repo( "submodule-layout.sh", *arguments, write=True, subdir="parent", ) as parent: yield parent.submodules[0] @pytest.fixture def configured_submodule(request, submodule_source): params = getattr(request.node, "callspec", None) params = {} if params is None else params.params # These scenarios intentionally point symlinks at fixture-local absolute paths. with fixture_repo( "submodule-symlinks.sh", str(submodule_source), getattr(request, "param", "logical-name"), request.node.originalname, params.get("kind", params.get("link_kind", "none")), str(params.get("dangling", False)), params.get("operation", "none"), str(params.get("relative_target", False)), write=True, execute=True, subdir="parent", ) as parent: if params.get("link_kind") == "gitmodules": with git.Repo(submodule_source) as source: yield Submodule( parent, source.head.commit.binsha, name="logical-name", path="module", url=str(submodule_source) ) else: yield parent.submodules[0] def test_movable_submodule_copies_are_isolated(movable_submodule, movable_submodule_baseline): sm = movable_submodule baseline = movable_submodule_baseline(sm.name) for relative in (".git/index", ".git/config", ".git/modules/logical-name/config", "module/file"): copy = Path(sm.repo.working_tree_dir, relative) original = baseline / relative assert copy.read_bytes() == original.read_bytes() assert not copy.samefile(original) Path(sm.abspath, "file").write_text("changed", encoding="utf-8") sm.repo.create_head("copy-only") assert (baseline / "module/file").read_text(encoding="utf-8") == "content" with git.Repo(baseline) as original: assert "copy-only" not in original.heads @pytest.fixture def nested_metadata_submodule(submodule_source): with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "nested", write=True, subdir="parent" ) as parent: yield parent.submodules[0], parent.submodules[1] @pytest.fixture def existing_nested_metadata(submodule_source, state): # The separate Git directory is recorded as an absolute path in the checkout. with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "existing-nested", state, write=True, execute=True, subdir="parent", ) as parent: yield parent.submodules[0] @pytest.fixture def separate_metadata_submodule(submodule_source): # The separate Git directory is recorded as an absolute path in the checkout. with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "separate", write=True, execute=True, subdir="separate", ) as parent: yield parent.submodules[0] @pytest.fixture def intermediate_symlink_submodule(submodule_source, target_kind): with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "intermediate-link", target_kind, write=True, execute=True, subdir="parent", ) as parent: root = Path(parent.working_tree_dir).parent target = root / "parent/target" if target_kind == "internal" else root / "outside" yield parent.submodules[0], target @pytest.fixture def leaf_metadata_submodule(submodule_source, metadata_dir): # Linked worktree metadata and its symlink contain fixture-local absolute paths. with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "leaf-metadata", metadata_dir, write=True, execute=True, subdir="worktree", ) as parent: yield parent.submodules[0] @pytest.fixture def retained_metadata_submodule(submodule_source): with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "retained", write=True, subdir="parent" ) as parent: sm = parent.head.commit.tree["module"] yield Submodule(parent, sm.binsha, name="logical-name", path="module", url=str(submodule_source)) def _move_snapshot(submodule): """Capture index, configuration, and path state to detect side effects of rejected moves.""" parent = submodule.repo with submodule.module() as module: config = Path(module.git_dir, "config").read_bytes() return ( Path(parent.index.path).read_bytes(), Path(parent.working_tree_dir, ".gitmodules").read_bytes(), Path(submodule.abspath, ".git").read_bytes(), config, submodule.path, ) @pytest.mark.parametrize( "path", [ ".git/child", ".GiT/child", "nested/.git/child", "git~1/child", "GIT~1 . /child", ".git. /child", ".git:stream/child", ".git::$INDEX_ALLOCATION/child", "nested\\.git\\child", "C:relative", "nul\0name", ] + [ f".g{chr(codepoint)}it/child" for codepoint in (*range(0x200C, 0x2010), *range(0x202A, 0x202F), *range(0x206A, 0x2070), 0xFEFF) ], ) @pytest.mark.parametrize("operation", ["add", "clone", "update", "move", "move-module", "move-config"]) def test_submodule_rejects_unsafe_checkout_before_mutation(movable_submodule, path, operation): sm = movable_submodule root = Path(sm.repo.working_tree_dir) before = _move_snapshot(sm) paths = set(root.rglob("*")) # Check the portable metadata aliases against Git's index validation as well. if operation == "clone" and path not in ("C:relative", "nul\0name"): with sm.repo.git.custom_environment(GIT_INDEX_FILE=str(root.parent / "validation-index")): with patch_git_config("core.protectHFS", "true"), patch_git_config("core.protectNTFS", "true"): with pytest.raises(GitCommandError): sm.repo.git.update_index("--add", "--cacheinfo", f"160000,{sm.hexsha},{path}") with mock.patch.object(git.Repo, "clone_from", side_effect=AssertionError("clone attempted")): with pytest.raises(ValueError): if operation == "add": sm.repo.create_submodule("new", path, sm.url) elif operation == "clone": Submodule._clone_repo(sm.repo, sm.url, path, "new") elif operation == "update": Submodule(sm.repo, sm.binsha, name="new", path=path, url=sm.url).update(init=True) else: sm.move(path, configuration=operation != "move-module", module=operation != "move-config") assert _move_snapshot(sm) == before assert set(root.rglob("*")) == paths def test_add_rejects_metadata_checkout_without_writing_files(movable_submodule): sm = movable_submodule before = _move_snapshot(sm) with pytest.raises(ValueError, match="Git metadata"): sm.repo.create_submodule("new", ".git/new", sm.url) assert not Path(sm.repo.git_dir, "new").exists() assert not Path(sm.repo.git_dir, "modules/new").exists() assert _move_snapshot(sm) == before @pytest.mark.parametrize("absolute_path", [False, True]) @pytest.mark.parametrize("metadata_name", ["metadata", "MeTaDaTa"]) @pytest.mark.parametrize("operation", ["add", "clone", "update", "move"]) def test_submodule_rejects_checkout_in_separate_metadata( separate_metadata_submodule, absolute_path, metadata_name, operation ): sm = separate_metadata_submodule parent = sm.repo root = Path(parent.working_tree_dir) if not (root / metadata_name).is_dir(): pytest.skip("Requires a case-insensitive filesystem") before = _move_snapshot(sm) paths = set(root.rglob("*")) path = root / metadata_name / "new" if absolute_path else f"{metadata_name}/new" with pytest.raises(ValueError, match="Git metadata"): if operation == "add": parent.create_submodule("new", path, sm.url) elif operation == "clone": Submodule._clone_repo(parent, sm.url, path, "new") elif operation == "update": Submodule(parent, sm.binsha, name="new", path=path, url=sm.url).update(init=True) else: sm.move(path) assert _move_snapshot(sm) == before assert set(root.rglob("*")) == paths @pytest.mark.parametrize("operation", ["add", "clone", "update"]) def test_submodule_rejects_nested_metadata_before_mutation(nested_metadata_submodule, operation): sm, other = nested_metadata_submodule root = Path(sm.repo.working_tree_dir) before = _move_snapshot(sm), _move_snapshot(other) paths = set(root.rglob("*")) name = f"{sm.name}/child" with pytest.raises(ValueError, match="inside.*Git directory"): if operation == "add": sm.repo.create_submodule(name, "new", sm.url) elif operation == "clone": Submodule._clone_repo(sm.repo, sm.url, "new", name) elif operation == "update": Submodule(sm.repo, sm.binsha, name=name, path="new", url=sm.url).update(init=True) assert (_move_snapshot(sm), _move_snapshot(other)) == before assert set(root.rglob("*")) == paths @pytest.mark.parametrize("state", ["retained", "checked-out"]) def test_update_rejects_existing_nested_metadata(existing_nested_metadata, state): sm = existing_nested_metadata name = f"{sm.name}/child" before = _move_snapshot(sm) paths = set(Path(sm.repo.working_tree_dir).rglob("*")) with pytest.raises(ValueError, match="inside.*Git directory"): Submodule(sm.repo, sm.binsha, name=name, path="new", url=sm.url).update(init=True, no_fetch=True) assert _move_snapshot(sm) == before assert set(Path(sm.repo.working_tree_dir).rglob("*")) == paths @pytest.mark.parametrize( "path", [ "CON", "con.txt", "CONIN$", "conout$.txt", "AUX .txt", "PRN", "NUL", "COM9", "LPT1", "name:stream", "space ", "period.", "line\nbreak", "star*", 'quote"', "question?", "angle<", "angle>", "pipe|", ], ) def test_submodule_rejects_windows_destination_names_before_mutation(movable_submodule, path): sm = movable_submodule before = _move_snapshot(sm) paths = set(Path(sm.repo.working_tree_dir).rglob("*")) with mock.patch("git.objects.submodule.base.sys", SimpleNamespace(platform="win32")): with mock.patch.object(git.Repo, "clone_from", side_effect=AssertionError("clone attempted")): with pytest.raises(ValueError): sm.repo.create_submodule("new", f"nested/{path}", sm.url) with pytest.raises(ValueError): sm.repo.create_submodule(f"nested/{path}", "new", sm.url) assert _move_snapshot(sm) == before assert set(Path(sm.repo.working_tree_dir).rglob("*")) == paths @pytest.mark.parametrize("path", ["nested/space ", "nested/period."]) def test_windows_destination_validation_precedes_normalization(path): parent = SimpleNamespace(working_tree_dir=str(read_only_fixture("empty.sh"))) # Windows' GetFullPathName removes trailing spaces and periods. with mock.patch("git.objects.submodule.base._to_relative_path", return_value=path.rstrip(" .")): with mock.patch("git.objects.submodule.base.sys", SimpleNamespace(platform="win32")): with pytest.raises(ValueError, match="Invalid submodule path on Windows"): Submodule._to_relative_path(parent, path) def test_submodule_move_keeps_its_own_metadata(movable_submodule): sm = movable_submodule name = sm.name sm.move(f"{name}/child") assert sm.name == name assert Path(sm.abspath, "file").read_text() == "content" with sm.module() as module: assert Path(module.git_dir) == Path(sm.repo.git_dir, "modules", sm.name) def test_clone_disables_metadata_that_becomes_nested(movable_submodule, monkeypatch): sm = movable_submodule clone_from = git.Repo.clone_from ancestor = Path(sm.repo.git_dir, "modules/new") prepared = read_only_fixture("empty.sh", "sha1", "files", "master", "true") / "repo" def clone_and_create_ancestor(*args, **kwargs): clone = clone_from(*args, **kwargs) shutil.copytree(prepared, ancestor, dirs_exist_ok=True) return clone monkeypatch.setattr(git.Repo, "clone_from", clone_and_create_ancestor) with pytest.raises(ValueError, match="inside.*Git directory"): Submodule._clone_repo(sm.repo, sm.url, "new", "new/child") assert not (ancestor / "child/HEAD").exists() assert (ancestor / "HEAD").is_file() @pytest.mark.parametrize("ref_format", ["files", "reftable"]) def test_readd_retained_submodule_without_checkout(submodule_source, ref_format): with fixture_repo( "submodule-layout.sh", str(submodule_source), "logical-name", "readd-retained", ref_format, write=True, subdir="parent", ) as parent: root = Path(parent.working_tree_dir).parent before = (root / "retained-refs").read_text().rstrip("\n") branch = (root / "retained-branch").read_text().strip() commit = (root / "retained-commit").read_text().strip() url = (root / "retained-url").read_text().strip() assert Path(url).samefile(submodule_source) replacement = Submodule.add(parent, "logical-name", "module", url, branch=branch, no_checkout=True) assert not Path(replacement.abspath, "file").exists() with replacement.module() as module: assert module.remotes.origin.url == url assert module.git.for_each_ref("--format=%(refname) %(objectname)") == before assert module.git.rev_parse("--show-ref-format") == ref_format assert module.head.reference.name == branch assert module.head.commit.hexsha == commit @pytest.mark.parametrize("change", ["url", "clone-options", "branch", "depth"]) def test_readd_retained_submodule_rejects_incompatible_options(retained_metadata_submodule, change): sm = retained_metadata_submodule name, path, url = sm.name, sm.path, sm.url root = Path(sm.repo.working_tree_dir) def snapshot(): return {str(path.relative_to(root)): path.read_bytes() for path in root.rglob("*") if path.is_file()} before = snapshot() options = {"no_checkout": True} if change == "url": url += "-other" elif change == "clone-options": options["clone_multi_options"] = ["--filter=blob:none"] elif change == "branch": options["branch"] = "other" else: options["depth"] = 1 with pytest.raises(ValueError): Submodule.add(sm.repo, name, path, url, **options) assert not (root / path).exists() assert snapshot() == before @pytest.mark.parametrize("target_kind", ["relative", "absolute", "internal", "dangling"]) @pytest.mark.parametrize("configuration,module", [(True, True), (False, True), (True, False)]) @pytest.mark.parametrize("absolute_path", [False, True]) def test_move_rejects_intermediate_symlink( intermediate_symlink_submodule, target_kind, configuration, module, absolute_path ): """Reject intermediate symlinks before changing repository state or their targets. Cover relative and absolute destinations in every move mode, including links within the repository and dangling links, which must also be rejected. """ submodule, target = intermediate_symlink_submodule parent = submodule.repo root = Path(parent.working_tree_dir) tree = parent.git.write_tree() before = _move_snapshot(submodule) destination = root / "nested/link/new/moved" if absolute_path else "nested/link/new/moved" with pytest.raises(ValueError, match="contains a symbolic link"): submodule.move(destination, configuration=configuration, module=module) assert _move_snapshot(submodule) == before assert parent.git.write_tree() == tree assert Path(submodule.abspath, "file").read_text(encoding="utf-8") == "content" if target_kind == "dangling": assert not target.exists() else: assert list(target.iterdir()) == [] @pytest.mark.parametrize("absolute_path", [False, True]) def test_move_normal_destination(movable_submodule, absolute_path): """Allow ordinary relative and absolute moves, and make a repeated move a no-op.""" submodule = movable_submodule root = Path(submodule.repo.working_tree_dir) destination = root / "nested/moved" if absolute_path else "nested/moved" assert submodule.move(destination) is submodule assert Path(submodule.abspath, "file").read_text(encoding="utf-8") == "content" assert not (root / "module").exists() assert submodule.path == "nested/moved" submodule.repo.git.write_tree() before = _move_snapshot(submodule) assert submodule.move(destination) is submodule assert _move_snapshot(submodule) == before @pytest.mark.parametrize("metadata_dir", ["git_dir", "common_dir"]) @patch_git_config("protocol.file.allow", "always") def test_move_rejects_leaf_symlink_to_metadata(leaf_metadata_submodule, metadata_dir): submodule = leaf_metadata_submodule parent = submodule.repo root = Path(parent.working_tree_dir) assert not osp.samefile(parent.git_dir, parent.common_dir) target = Path(getattr(parent, metadata_dir)) destination = root / "destination" before = _move_snapshot(submodule) with pytest.raises(ValueError, match="Git metadata"): submodule.move("destination", module=False) assert _move_snapshot(submodule) == before assert destination.is_symlink() assert destination.samefile(target) assert Path(submodule.abspath, "file").read_text(encoding="utf-8") == "content" @pytest.mark.parametrize("kind", ["empty", "nonempty", "file", "dangling"]) def test_move_leaf_symlink_compatibility(configured_submodule, kind): """Preserve leaf-symlink replacement without modifying the external target. Moving onto a link to an empty directory replaces the link; nonempty, file, and dangling targets fail without changing repository state. Direct checkout path access must still reject every leaf symlink. """ submodule = configured_submodule root = Path(submodule.repo.working_tree_dir) tmp_path = Path(configured_submodule.repo.working_tree_dir).parent target = tmp_path / "outside" destination = root / "destination" with pytest.raises(ValueError, match="contains a symbolic link"): Submodule(submodule.repo, Submodule.NULL_BIN_SHA, name="unused", path="destination").abspath before = _move_snapshot(submodule) if kind == "empty": assert submodule.move("destination") is submodule assert not destination.is_symlink() assert (destination / "file").is_file() assert list(target.iterdir()) == [] else: with pytest.raises(OSError if kind == "dangling" else ValueError): submodule.move("destination") assert _move_snapshot(submodule) == before assert destination.is_symlink() if kind == "nonempty": assert (target / "keep").read_text(encoding="utf-8") == "keep" elif kind == "file": assert target.read_text(encoding="utf-8") == "keep" else: assert not target.exists() @pytest.mark.parametrize("leaf", [False, True]) @pytest.mark.parametrize("dangling", [False, True]) @pytest.mark.parametrize("operation", ["add", "clone"]) @pytest.mark.parametrize("gitfile", [False, True]) def test_clone_rejects_checkout_symlinks(configured_submodule, leaf, dangling, operation, gitfile): """Reject checkout symlinks before add or clone creates metadata or touches the target. Cover leaf and intermediate links, including dangling targets, with both embedded and separate Git directories. """ sm = configured_submodule tmp_path = Path(configured_submodule.repo.working_tree_dir).parent target = tmp_path / "outside" path = "link" if leaf else "link/new/module" before = _move_snapshot(sm) with mock.patch.object(Submodule, "_need_gitfile_submodules", return_value=gitfile): with pytest.raises(ValueError, match="contains a symbolic link"): if operation == "add": Submodule.add(sm.repo, "new", path, sm.url) else: Submodule._clone_repo(sm.repo, sm.url, path, "new") assert _move_snapshot(sm) == before assert not (Path(sm.repo.git_dir) / "modules/new").exists() assert not target.exists() if dangling else list(target.iterdir()) == [] @pytest.mark.parametrize("link_kind", ["gitmodules", "checkout"]) @pytest.mark.parametrize("operation", ["update", "move", "remove"]) def test_submodule_rejects_checkout_and_gitmodules_symlinks(configured_submodule, link_kind, operation): """Reject operations on symlinked checkouts or .gitmodules without side effects. Update, move, and forced removal must preserve the external target, repository configuration, index, checkout, and any existing move destination. """ sm = configured_submodule root = Path(sm.repo.working_tree_dir) tmp_path = Path(configured_submodule.repo.working_tree_dir).parent path = root / (".gitmodules" if link_kind == "gitmodules" else "module") target = tmp_path / "outside" before = ( {p.relative_to(target): p.read_bytes() for p in target.rglob("*") if p.is_file()} if target.is_dir() else target.read_bytes() ) config = Path(sm.repo.git_dir, "config").read_bytes() index = Path(sm.repo.index.path).read_bytes() gitmodules = (root / ".gitmodules").read_bytes() with pytest.raises(ValueError, match="contains a symbolic link"): if operation == "update": sm.update() elif operation == "move": sm.move("moved") else: sm.remove(force=True) after = ( {p.relative_to(target): p.read_bytes() for p in target.rglob("*") if p.is_file()} if target.is_dir() else target.read_bytes() ) assert after == before assert Path(sm.repo.git_dir, "config").read_bytes() == config assert Path(sm.repo.index.path).read_bytes() == index assert (root / ".gitmodules").read_bytes() == gitmodules assert (root / "module/file").read_text() == "content" assert path.is_symlink() assert (root / "moved").is_dir() @pytest.mark.parametrize("implementation", ["git", "gitpython"]) @pytest.mark.parametrize("operation", ["update", "remove"]) @pytest.mark.parametrize("kind", ["leaf", "intermediate"]) def test_submodule_writes_use_checked_worktree(configured_submodule, implementation, operation, kind): """A configured worktree must not redirect writes past the checked checkout.""" sm = configured_submodule root = Path(sm.repo.working_tree_dir) outside = root.parent / "outside" if kind == "intermediate": outside /= "worktree" before = {path.name: path.read_bytes() for path in outside.iterdir()} if implementation == "git": if operation == "update": sm.repo.git.submodule("update", "--force", "--no-fetch", "--", sm.path) else: sm.repo.git.submodule("deinit", "--force", "--", sm.path) elif operation == "update": sm.update(force=True, no_fetch=True) else: sm.remove(configuration=False) assert outside.is_dir() assert {path.name: path.read_bytes() for path in outside.iterdir()} == before assert (root / "redirect").is_symlink() if operation == "update": assert (root / "module/file").read_text() == "updated" else: assert not (root / "module/file").exists() def test_add_closes_checkout_processes(movable_submodule, monkeypatch): """Adding a submodule must not leave a child process holding its checkout open.""" # Native reads have no persistent process; keep exercising the CLI fallback. monkeypatch.setattr(git._backend, "object_data", lambda *args, **kwargs: NotImplemented) sm = movable_submodule checkout = Path(sm.repo.working_tree_dir, "new") execute = Git.execute processes = [] def capture_process(self, command, *args, **kwargs): result = execute(self, command, *args, **kwargs) if ( kwargs.get("as_process") and "cat-file" in command and Path(self.working_dir).resolve() == checkout.resolve() ): processes.append(result.proc) return result |
| 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. |