git-project 0.0.42__tar.gz → 0.0.43__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. {git_project-0.0.42 → git_project-0.0.43}/PKG-INFO +17 -21
  2. {git_project-0.0.42 → git_project-0.0.43}/_version.py +2 -2
  3. {git_project-0.0.42 → git_project-0.0.43}/docs/changelog.rst +23 -1
  4. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/git.py +104 -39
  5. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/project.py +2 -14
  6. {git_project-0.0.42 → git_project-0.0.43}/tests/conftest.py +10 -0
  7. {git_project-0.0.42 → git_project-0.0.43}/tests/test_git.py +100 -46
  8. {git_project-0.0.42 → git_project-0.0.43}/tests/test_project.py +40 -20
  9. {git_project-0.0.42 → git_project-0.0.43}/.gitignore +0 -0
  10. {git_project-0.0.42 → git_project-0.0.43}/CONTRIBUTORS +0 -0
  11. {git_project-0.0.42 → git_project-0.0.43}/COPYING +0 -0
  12. {git_project-0.0.42 → git_project-0.0.43}/MANIFEST.in +0 -0
  13. {git_project-0.0.42 → git_project-0.0.43}/docs/Makefile +0 -0
  14. {git_project-0.0.42 → git_project-0.0.43}/docs/api.rst +0 -0
  15. {git_project-0.0.42 → git_project-0.0.43}/docs/authors.rst +0 -0
  16. {git_project-0.0.42 → git_project-0.0.43}/docs/conf.py +0 -0
  17. {git_project-0.0.42 → git_project-0.0.43}/docs/contributing.rst +0 -0
  18. {git_project-0.0.42 → git_project-0.0.43}/docs/index.rst +0 -0
  19. {git_project-0.0.42 → git_project-0.0.43}/docs/intro.rst +0 -0
  20. {git_project-0.0.42 → git_project-0.0.43}/docs/license.rst +0 -0
  21. {git_project-0.0.42 → git_project-0.0.43}/docs/make.bat +0 -0
  22. {git_project-0.0.42 → git_project-0.0.43}/docs/plugins.rst +0 -0
  23. {git_project-0.0.42 → git_project-0.0.43}/pyproject.toml +0 -0
  24. {git_project-0.0.42 → git_project-0.0.43}/requirements.txt +0 -0
  25. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/__init__.py +0 -0
  26. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/commandline.py +0 -0
  27. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/configobj.py +0 -0
  28. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/exception.py +0 -0
  29. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/gitproject.py +0 -0
  30. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/main.py +0 -0
  31. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/parsermanager.py +0 -0
  32. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/plugin.py +0 -0
  33. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/pluginmanager.py +0 -0
  34. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/py.typed +0 -0
  35. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/runnable.py +0 -0
  36. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/scopedobj.py +0 -0
  37. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/shell.py +0 -0
  38. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/substitutable.py +0 -0
  39. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/test_support/__init__.py +0 -0
  40. {git_project-0.0.42 → git_project-0.0.43}/src/git_project/test_support/common.py +0 -0
  41. {git_project-0.0.42 → git_project-0.0.43}/tests/test_confobj.py +0 -0
  42. {git_project-0.0.42 → git_project-0.0.43}/tests/test_gitproject.py +0 -0
  43. {git_project-0.0.42 → git_project-0.0.43}/tests/test_main.py +0 -0
  44. {git_project-0.0.42 → git_project-0.0.43}/tests/test_parsermanager.py +0 -0
  45. {git_project-0.0.42 → git_project-0.0.43}/tests/test_runnable.py +0 -0
  46. {git_project-0.0.42 → git_project-0.0.43}/tests/test_scopedobj.py +0 -0
  47. {git_project-0.0.42 → git_project-0.0.43}/tests/test_shell.py +0 -0
  48. {git_project-0.0.42 → git_project-0.0.43}/tests/test_substitutable.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: git-project
3
- Version: 0.0.42
3
+ Version: 0.0.43
4
4
  Summary: The extensible stupid project manager
5
5
  Author-email: "David A. Greene" <dag@obbligato.org>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -214,33 +214,29 @@ Authors
214
214
  .. _David Greene: https://github.com/greened
215
215
 
216
216
 
217
- `0.0.42`_ - 2026-10-06
217
+ `0.0.43`_ - 2026-10-07
218
218
  ----------------------
219
- Added
220
- .....
221
- - A command can set ``write_project_defaults=False`` on its parser, so that
222
- git-project does not write the project's default ``branch`` and
223
- ``remote`` to the config. A dry run can then leave the config as it was.
224
- - ``Project.get`` takes ``set_defaults``, True by default. With False, it
225
- does not write the defaults.
226
-
227
219
  Changed
228
220
  .......
229
- - git-project writes the project defaults after the command line is
230
- parsed, not when it builds the project. So ``-h``, ``--version``,
231
- ``--menu`` and a command-line error no longer write them. The plugin
232
- hooks ``add_class_hooks``, ``add_arguments`` and ``modify_arguments``
233
- can see a project without its default branch and remote.
221
+ - ``Git.remote_branch_exists`` and ``Git.delete_remote_branch`` run the
222
+ git CLI instead of libgit2. They read ``~/.ssh/config`` and use the ssh
223
+ agent, and a delete runs the ``pre-push`` hook. With ``ssh.id`` set they
224
+ also pass ``~/.ssh/<id>`` to ssh. They raise ``GitProjectError``, not
225
+ ``pygit2.GitError``, when the remote cannot be reached or refuses.
226
+
227
+ Removed
228
+ .......
229
+ - ``Git.LsRemotesCallbacks`` and ``Git.RemoteBranchDeleteCallback`` are
230
+ gone, because no git-project method uses them.
234
231
 
235
232
  Fixed
236
233
  .....
237
- - ``branch prune``, ``worktree rm`` and ``Project.prune_branch`` stopped
238
- and kept the local branch when a remote could not be reached, such as
239
- one whose URL names a host alias from ``~/.ssh/config``, which libgit2
240
- does not read, or when a remote refused the delete. They now warn about
241
- that remote on stderr and delete the local branch.
234
+ - ``branch prune``, ``worktree rm`` and ``Project.prune_branch`` now
235
+ delete the remote branch on a remote whose URL names a host alias from
236
+ ``~/.ssh/config``.
242
237
 
243
- .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.42...HEAD
238
+ .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.43...HEAD
239
+ .. _0.0.43: https://github.com/greened/git-project/compare/v0.0.42...v0.0.43
244
240
  .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
245
241
  .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
246
242
  .. _0.0.40: https://github.com/greened/git-project/compare/v0.0.39...v0.0.40
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.0.42'
22
- __version_tuple__ = version_tuple = (0, 0, 42)
21
+ __version__ = version = '0.0.43'
22
+ __version_tuple__ = version_tuple = (0, 0, 43)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -31,6 +31,27 @@ ChangeLog
31
31
  `Unreleased`_
32
32
  -------------
33
33
 
34
+ `0.0.43`_ - 2026-10-07
35
+ ----------------------
36
+ Changed
37
+ .......
38
+ - ``Git.remote_branch_exists`` and ``Git.delete_remote_branch`` run the
39
+ git CLI instead of libgit2. They read ``~/.ssh/config`` and use the ssh
40
+ agent, and a delete runs the ``pre-push`` hook. With ``ssh.id`` set they
41
+ also pass ``~/.ssh/<id>`` to ssh. They raise ``GitProjectError``, not
42
+ ``pygit2.GitError``, when the remote cannot be reached or refuses.
43
+
44
+ Removed
45
+ .......
46
+ - ``Git.LsRemotesCallbacks`` and ``Git.RemoteBranchDeleteCallback`` are
47
+ gone, because no git-project method uses them.
48
+
49
+ Fixed
50
+ .....
51
+ - ``branch prune``, ``worktree rm`` and ``Project.prune_branch`` now
52
+ delete the remote branch on a remote whose URL names a host alias from
53
+ ``~/.ssh/config``.
54
+
34
55
  `0.0.42`_ - 2026-10-06
35
56
  ----------------------
36
57
  Added
@@ -203,7 +224,8 @@ Fixed
203
224
  ``git_project``. No declared environment supplied Sphinx either, so a
204
225
  ``docs`` environment with Sphinx is now declared.
205
226
 
206
- .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.42...HEAD
227
+ .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.43...HEAD
228
+ .. _0.0.43: https://github.com/greened/git-project/compare/v0.0.42...v0.0.43
207
229
  .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
208
230
  .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
209
231
  .. _0.0.40: https://github.com/greened/git-project/compare/v0.0.39...v0.0.40
@@ -21,8 +21,12 @@
21
21
  # You should have received a copy of the GNU Affero General Public License along
22
22
  # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
23
 
24
+ import contextlib
24
25
  import os
25
26
  import re
27
+ import shlex
28
+ import signal
29
+ import subprocess
26
30
  import urllib.parse
27
31
  from pathlib import Path
28
32
 
@@ -53,6 +57,12 @@ class Git:
53
57
  passphrase, because git-project offers no passphrase and does not ask an
54
58
  ssh agent. Without ssh.id no keypair is offered.
55
59
 
60
+ remote_branch_exists and delete_remote_branch run the git CLI instead,
61
+ so they read ~/.ssh/config and use the ssh agent. With ssh.id set they
62
+ pass ~/.ssh/<id> to ssh as well. That replaces any core.sshCommand in
63
+ the git config. A GIT_SSH_COMMAND in the environment takes precedence,
64
+ and then ssh.id has no effect.
65
+
56
66
  """
57
67
 
58
68
  @staticmethod
@@ -408,32 +418,6 @@ class Git:
408
418
  if section.is_empty():
409
419
  del self._sections[section_name]
410
420
 
411
- class RemoteBranchDeleteCallback(pygit2.RemoteCallbacks):
412
- def __init__(self, ssh_id: str | None):
413
- self.ssh_id = ssh_id
414
-
415
- """Check the result of remove branch prune operations."""
416
-
417
- def credentials(self, url, username_from_url, allowed_types):
418
- return Git._ssh_credentials(
419
- self.ssh_id, username_from_url, allowed_types
420
- )
421
-
422
- def push_update_reference(self, refname, message):
423
- if message is not None:
424
- raise GitProjectError(
425
- f"Could not prune remote branch: {message}"
426
- )
427
-
428
- class LsRemotesCallbacks(pygit2.RemoteCallbacks):
429
- def __init__(self, ssh_id: str | None):
430
- self.ssh_id = ssh_id
431
-
432
- def credentials(self, url, username_from_url, allowed_types):
433
- return Git._ssh_credentials(
434
- self.ssh_id, username_from_url, allowed_types
435
- )
436
-
437
421
  # Repository-wide info
438
422
  def __init__(self):
439
423
  self.reinit(Path.cwd())
@@ -921,28 +905,109 @@ class Git:
921
905
  branch_name = self.refname_to_branch_name(branch_name)
922
906
  self._repo.branches.delete(branch_name)
923
907
 
908
+ # A remote call through the git CLI gives up after this many seconds.
909
+ REMOTE_TIMEOUT = 60
910
+
911
+ def _run_remote_git(self, args):
912
+ """Run the git CLI with args on this repository and return the
913
+ CompletedProcess, or None if git could not run or timed out.
914
+
915
+ """
916
+ command = ["git"]
917
+ ssh_id = self.get_ssh_id()
918
+ if ssh_id:
919
+ # git runs core.sshCommand through a shell.
920
+ key = shlex.quote(str(Path.home() / ".ssh" / ssh_id))
921
+ command += ["-c", f"core.sshCommand=ssh -i {key}"]
922
+ command += ["--git-dir", self._repo.path, *args]
923
+ # Fail rather than prompt for credentials. An empty GIT_ASKPASS
924
+ # stops git from running an askpass program, and a new session has
925
+ # no terminal for ssh to prompt on.
926
+ env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_ASKPASS="")
927
+ env["SSH_ASKPASS_REQUIRE"] = "never"
928
+ # --git-dir makes the cwd the top of the work tree, and a pre-push
929
+ # hook runs there.
930
+ cwd = self._repo.workdir or self._repo.path
931
+ try:
932
+ proc = subprocess.Popen(
933
+ command,
934
+ cwd=cwd,
935
+ env=env,
936
+ stdin=subprocess.DEVNULL,
937
+ stdout=subprocess.PIPE,
938
+ # Nothing reads it, and it may hold the URL.
939
+ stderr=subprocess.DEVNULL,
940
+ text=True,
941
+ # A hook or the remote may write any bytes.
942
+ errors="replace",
943
+ start_new_session=True,
944
+ )
945
+ except OSError:
946
+ return None
947
+ try:
948
+ out, _ = proc.communicate(timeout=self.REMOTE_TIMEOUT)
949
+ except subprocess.TimeoutExpired:
950
+ # Kill ssh as well as git.
951
+ with contextlib.suppress(ProcessLookupError):
952
+ os.killpg(proc.pid, signal.SIGKILL)
953
+ # A child that left the group may still hold the pipe, so do not
954
+ # read it to the end.
955
+ proc.stdout.close()
956
+ proc.wait()
957
+ return None
958
+ return subprocess.CompletedProcess(command, proc.returncode, out)
959
+
924
960
  def remote_branch_exists(self, branch_name, remote):
925
- """Return whether the given branch exists on the given remote."""
961
+ """Return whether the given branch exists on the given remote. Raise
962
+ GitProjectError if the remote cannot be reached.
963
+
964
+ """
926
965
  refname = self.branch_name_to_refname(branch_name)
927
966
  # FIXME: There is no way to get the branch's name on the remote side,
928
967
  # so assume it matches the local name.
929
- for item in self._repo.remotes[remote].list_heads(
930
- callbacks=Git.LsRemotesCallbacks(self.get_ssh_id())
931
- ):
932
- if not item.local and item.name == refname:
968
+ result = self._run_remote_git(
969
+ ["ls-remote", "--exit-code", "--", remote, refname]
970
+ )
971
+ # ls-remote exits with 2 when no ref matches.
972
+ if result is None or result.returncode not in (0, 2):
973
+ raise GitProjectError(
974
+ f"cannot reach remote {remote} to check {branch_name}"
975
+ )
976
+ # A pattern matches any ref that ends with it, so check the name.
977
+ for line in result.stdout.splitlines():
978
+ if line.partition("\t")[2] == refname:
933
979
  return True
934
980
  return False
935
981
 
936
982
  def delete_remote_branch(self, branch_name, remote):
937
- """Remove the given local branch from the given remote."""
938
- # FIXME: What if the remote branch is not in refs/heads? For some
939
- # reason push :branch_name doesn't work. push
940
- # :remotes/<remote>/branch_name also doesn't work.
983
+ """Remove the given local branch from the given remote. Raise
984
+ GitProjectError if the remote cannot be reached or refuses.
985
+
986
+ """
987
+ # FIXME: What if the remote branch is not in refs/heads?
941
988
  refname = self.branch_name_to_refname(branch_name)
942
- callback = self.RemoteBranchDeleteCallback(self.get_ssh_id())
943
- refspecs = [f":{refname}"]
944
- remote = self._repo.remotes[remote]
945
- remote.push(refspecs, callback)
989
+ result = self._run_remote_git(
990
+ ["push", "--porcelain", "--delete", "--", remote, refname]
991
+ )
992
+ if result is not None and result.returncode == 0:
993
+ return
994
+ # Each porcelain ref line is flag, refspec and summary, separated by
995
+ # tabs. The summary gives the reason, and the line holds no URL.
996
+ reason = ""
997
+ if result is not None:
998
+ for line in result.stdout.splitlines():
999
+ fields = line.split("\t")
1000
+ if len(fields) == 3 and fields[1] == f":{refname}":
1001
+ # The remote may write the reason, so drop control
1002
+ # characters.
1003
+ reason = "".join(c for c in fields[2] if c.isprintable())
1004
+ if reason:
1005
+ raise GitProjectError(
1006
+ f"remote {remote} refused to delete {branch_name}: {reason}"
1007
+ )
1008
+ raise GitProjectError(
1009
+ f"cannot delete {branch_name} on remote {remote}"
1010
+ )
946
1011
 
947
1012
  def validate_config(self):
948
1013
  """Ensure the git config is sane. This is primarily a development debugging
@@ -24,8 +24,6 @@
24
24
 
25
25
  import sys
26
26
 
27
- import pygit2
28
-
29
27
  from .exception import GitProjectError
30
28
  from .git import Git
31
29
  from .scopedobj import ScopedConfigObject
@@ -226,21 +224,11 @@ class Project(ScopedConfigObject):
226
224
  # as a remote refusal.
227
225
  self._git.get_ssh_id()
228
226
  for remote in self.iterremotes():
229
- # A remote failure must not stop the local delete. libgit2
230
- # does not read ~/.ssh/config, so a host alias there does not
231
- # resolve.
227
+ # A remote failure must not stop the local delete.
232
228
  try:
233
229
  if self._git.remote_branch_exists(branch, remote):
234
230
  self._git.delete_remote_branch(branch, remote)
235
- except pygit2.GitError:
236
- # The error may hold the URL, so it is not printed.
237
- print(
238
- f"warning: cannot reach remote {remote} to check or "
239
- f"delete {branch}",
240
- file=sys.stderr,
241
- )
242
231
  except GitProjectError as error:
243
- # The remote refused the delete, and says why.
244
- print(f"warning: {remote}: {error}", file=sys.stderr)
232
+ print(f"warning: {error}", file=sys.stderr)
245
233
  if self._git.committish_exists(branch):
246
234
  self._git.delete_branch(Git.refname_to_branch_name(branch))
@@ -21,6 +21,8 @@
21
21
  # You should have received a copy of the GNU Affero General Public License along
22
22
  # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
23
 
24
+ import pytest
25
+
24
26
  from git_project.test_support import (
25
27
  bare_git,
26
28
  git,
@@ -49,3 +51,11 @@ __all__ = [
49
51
  "remote_repository",
50
52
  "reset_directory",
51
53
  ]
54
+
55
+
56
+ @pytest.fixture(autouse=True)
57
+ def no_user_git_config(monkeypatch):
58
+ # A remote delete runs git push, which would run the user's global
59
+ # pre-push hook.
60
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", "/dev/null")
61
+ monkeypatch.setenv("GIT_CONFIG_NOSYSTEM", "1")
@@ -22,8 +22,11 @@
22
22
  # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
23
 
24
24
  import os
25
+ import shlex
25
26
  import shutil
26
27
  import subprocess
28
+ import sys
29
+ import time
27
30
  from pathlib import Path
28
31
 
29
32
  import pygit2
@@ -814,6 +817,103 @@ def test_git_remote_branch_exists(reset_directory, local_repository):
814
817
  assert not git.remote_branch_exists("unmerged", "origin")
815
818
 
816
819
 
820
+ def test_git_remote_branch_exists_timeout(
821
+ reset_directory, local_repository, monkeypatch
822
+ ):
823
+ os.chdir(local_repository.path)
824
+
825
+ git = git_project.Git()
826
+ git.config.set_item("remote.origin", "url", "ssh://example.invalid/x")
827
+ pidfile = Path.cwd() / "ssh.pid"
828
+ ssh = Path.cwd() / "slow-ssh"
829
+ ssh.write_text(f"#!/bin/sh\necho $$ > {pidfile}\nexec sleep 30\n")
830
+ ssh.chmod(0o755)
831
+ monkeypatch.setenv("GIT_SSH_COMMAND", str(ssh))
832
+ monkeypatch.setattr(git_project.Git, "REMOTE_TIMEOUT", 3)
833
+
834
+ with pytest.raises(git_project.GitProjectError, match="cannot reach"):
835
+ git.remote_branch_exists("pushed", "origin")
836
+
837
+ # The kill reaches ssh, not only git.
838
+ pid = int(pidfile.read_text())
839
+ for _ in range(50):
840
+ try:
841
+ os.kill(pid, 0)
842
+ except ProcessLookupError:
843
+ break
844
+ time.sleep(0.1)
845
+ else:
846
+ pytest.fail("ssh outlived the timeout")
847
+
848
+
849
+ def test_git_delete_remote_branch_timeout_escaped_child(
850
+ reset_directory, local_repository, monkeypatch
851
+ ):
852
+ os.chdir(local_repository.path)
853
+
854
+ git = git_project.Git()
855
+ git.create_branch("todelete", "HEAD")
856
+ # The hook leaves a child in a new session, out of reach of the kill,
857
+ # and the child holds the stdout pipe open.
858
+ escape = "import os, time; os.setsid(); time.sleep(20)"
859
+ hook = Path(git._repo.path) / "hooks" / "pre-push"
860
+ hook.parent.mkdir(exist_ok=True)
861
+ hook.write_text(
862
+ f"#!/bin/sh\n{shlex.quote(sys.executable)} -c '{escape}' &\n"
863
+ "sleep 20\n"
864
+ )
865
+ hook.chmod(0o755)
866
+ monkeypatch.setattr(git_project.Git, "REMOTE_TIMEOUT", 1)
867
+
868
+ start = time.monotonic()
869
+ with pytest.raises(git_project.GitProjectError, match="cannot delete"):
870
+ git.delete_remote_branch("todelete", "origin")
871
+ assert time.monotonic() - start < 10
872
+
873
+
874
+ def test_git_remote_branch_exists_no_git(
875
+ reset_directory, local_repository, monkeypatch, tmp_path_factory
876
+ ):
877
+ os.chdir(local_repository.path)
878
+
879
+ git = git_project.Git()
880
+ monkeypatch.setenv("PATH", str(tmp_path_factory.mktemp("empty-path")))
881
+
882
+ with pytest.raises(git_project.GitProjectError, match="cannot reach"):
883
+ git.remote_branch_exists("pushed", "origin")
884
+
885
+
886
+ def test_git_remote_git_passes_ssh_id(
887
+ reset_directory, local_repository, monkeypatch
888
+ ):
889
+ os.chdir(local_repository.path)
890
+
891
+ git = git_project.Git()
892
+ git.config.set_item("ssh", "id", "my key")
893
+
894
+ commands = []
895
+
896
+ class Recorder:
897
+ def __init__(self, command, **kwargs):
898
+ commands.append(command)
899
+ self.returncode = 2
900
+
901
+ def communicate(self, timeout=None):
902
+ return "", ""
903
+
904
+ monkeypatch.setattr(subprocess, "Popen", Recorder)
905
+
906
+ assert not git.remote_branch_exists("pushed", "origin")
907
+ assert commands[0][1] == "-c"
908
+ name, _, value = commands[0][2].partition("=")
909
+ assert name == "core.sshCommand"
910
+ assert shlex.split(value) == [
911
+ "ssh",
912
+ "-i",
913
+ str(Path.home() / ".ssh" / "my key"),
914
+ ]
915
+
916
+
817
917
  def test_git_delete_remote_refname(
818
918
  reset_directory, local_repository, remote_repository
819
919
  ):
@@ -1175,49 +1275,3 @@ def test_git_remote_credentials(reset_directory):
1175
1275
  )
1176
1276
  is None
1177
1277
  )
1178
-
1179
-
1180
- def test_git_remote_branch_delete_credentials(reset_directory):
1181
- callback = git_project.Git.RemoteBranchDeleteCallback(ssh_id="id_rsa")
1182
-
1183
- key_result = callback.credentials(
1184
- "ssh:me@my.org/test.git", "me", pygit2.enums.CredentialType.SSH_KEY
1185
- )
1186
- name_result = callback.credentials(
1187
- "ssh:me@my.org/test.git", "me", pygit2.enums.CredentialType.USERNAME
1188
- )
1189
-
1190
- assert isinstance(key_result, pygit2.Keypair)
1191
- assert isinstance(name_result, pygit2.Username)
1192
-
1193
- no_id = git_project.Git.RemoteBranchDeleteCallback(ssh_id=None)
1194
-
1195
- assert (
1196
- no_id.credentials(
1197
- "ssh:me@my.org/test.git", "me", pygit2.enums.CredentialType.SSH_KEY
1198
- )
1199
- is None
1200
- )
1201
-
1202
-
1203
- def test_git_ls_remotes_credentials(reset_directory):
1204
- callback = git_project.Git.LsRemotesCallbacks(ssh_id="id_rsa")
1205
-
1206
- key_result = callback.credentials(
1207
- "ssh:me@my.org/test.git", "me", pygit2.enums.CredentialType.SSH_KEY
1208
- )
1209
- name_result = callback.credentials(
1210
- "ssh:me@my.org/test.git", "me", pygit2.enums.CredentialType.USERNAME
1211
- )
1212
-
1213
- assert isinstance(key_result, pygit2.Keypair)
1214
- assert isinstance(name_result, pygit2.Username)
1215
-
1216
- no_id = git_project.Git.LsRemotesCallbacks(ssh_id=None)
1217
-
1218
- assert (
1219
- no_id.credentials(
1220
- "ssh:me@my.org/test.git", "me", pygit2.enums.CredentialType.SSH_KEY
1221
- )
1222
- is None
1223
- )
@@ -220,36 +220,56 @@ def test_project_prune_branch_unreachable_remote(
220
220
  project.prune_branch("pushed")
221
221
 
222
222
  assert not project._git.committish_exists("pushed")
223
- assert (
224
- "warning: cannot reach remote origin to check or delete pushed"
225
- in capsys.readouterr().err
226
- )
223
+ err = capsys.readouterr().err
224
+ assert "warning: cannot reach remote origin to check pushed" in err
225
+ assert str(missing) not in err
227
226
 
228
227
 
229
228
  def test_project_prune_branch_remote_refuses_delete(
230
- reset_directory, remote_repository, tmp_path_factory, capsys, monkeypatch
229
+ reset_directory, remote_repository, tmp_path_factory, capsys
231
230
  ):
232
231
  project = clone_with_pushed_branch(remote_repository, tmp_path_factory)
233
-
234
- # libgit2's local transport ignores receive.denyDeletes, so make the push
235
- # callback refuse, as it does for a server's rejection.
236
- def refuse(self, refname, message):
237
- raise git_project.GitProjectError(
238
- "Could not prune remote branch: deletion prohibited"
239
- )
240
-
241
- monkeypatch.setattr(
242
- git_project.Git.RemoteBranchDeleteCallback,
243
- "push_update_reference",
244
- refuse,
232
+ url = project._git.config.get_item("remote.origin", "url")
233
+ git_project.capture_command(
234
+ ["git", "--git-dir", url, "config", "receive.denyDeletes", "true"]
245
235
  )
246
236
 
247
237
  project.prune_branch("pushed")
248
238
 
249
239
  assert not project._git.committish_exists("pushed")
250
- assert "warning: origin: Could not prune remote branch" in (
251
- capsys.readouterr().err
252
- )
240
+ assert project._git.remote_branch_exists("pushed", "origin")
241
+ err = capsys.readouterr().err
242
+ assert (
243
+ "warning: remote origin refused to delete pushed: "
244
+ "[remote rejected] (deletion prohibited)"
245
+ ) in err
246
+ assert url not in err
247
+
248
+
249
+ def test_project_prune_branch_pre_push_hook_refuses(
250
+ reset_directory, remote_repository, tmp_path_factory, capsys
251
+ ):
252
+ project = clone_with_pushed_branch(remote_repository, tmp_path_factory)
253
+ url = project._git.config.get_item("remote.origin", "url")
254
+ hook = Path(project._git._repo.path) / "hooks" / "pre-push"
255
+ hook.parent.mkdir(exist_ok=True)
256
+ # Undecodable output must not stop the prune.
257
+ hook.write_text("#!/bin/sh\npwd > hook-cwd\nprintf '\\377\\376'\nexit 1\n")
258
+ hook.chmod(0o755)
259
+ subdir = Path(project._git._repo.workdir) / "sub"
260
+ subdir.mkdir()
261
+ os.chdir(subdir)
262
+
263
+ project.prune_branch("pushed")
264
+
265
+ assert not project._git.committish_exists("pushed")
266
+ assert project._git.remote_branch_exists("pushed", "origin")
267
+ err = capsys.readouterr().err
268
+ assert "warning: cannot delete pushed on remote origin" in err
269
+ assert url not in err
270
+ # The hook runs at the top of the work tree, not in the cwd.
271
+ workdir = Path(project._git._repo.workdir)
272
+ assert (workdir / "hook-cwd").read_text().strip() == str(workdir)
253
273
 
254
274
 
255
275
  def test_project_get_without_defaults(git):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes