git-project 0.0.41__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 (49) hide show
  1. {git_project-0.0.41 → git_project-0.0.43}/PKG-INFO +19 -19
  2. {git_project-0.0.41 → git_project-0.0.43}/_version.py +2 -2
  3. {git_project-0.0.41 → git_project-0.0.43}/docs/changelog.rst +50 -1
  4. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/git.py +104 -39
  5. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/main.py +10 -2
  6. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/plugin.py +12 -1
  7. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/project.py +22 -8
  8. {git_project-0.0.41 → git_project-0.0.43}/tests/conftest.py +10 -0
  9. {git_project-0.0.41 → git_project-0.0.43}/tests/test_git.py +100 -46
  10. git_project-0.0.43/tests/test_main.py +125 -0
  11. {git_project-0.0.41 → git_project-0.0.43}/tests/test_project.py +71 -0
  12. git_project-0.0.41/tests/test_main.py +0 -61
  13. {git_project-0.0.41 → git_project-0.0.43}/.gitignore +0 -0
  14. {git_project-0.0.41 → git_project-0.0.43}/CONTRIBUTORS +0 -0
  15. {git_project-0.0.41 → git_project-0.0.43}/COPYING +0 -0
  16. {git_project-0.0.41 → git_project-0.0.43}/MANIFEST.in +0 -0
  17. {git_project-0.0.41 → git_project-0.0.43}/docs/Makefile +0 -0
  18. {git_project-0.0.41 → git_project-0.0.43}/docs/api.rst +0 -0
  19. {git_project-0.0.41 → git_project-0.0.43}/docs/authors.rst +0 -0
  20. {git_project-0.0.41 → git_project-0.0.43}/docs/conf.py +0 -0
  21. {git_project-0.0.41 → git_project-0.0.43}/docs/contributing.rst +0 -0
  22. {git_project-0.0.41 → git_project-0.0.43}/docs/index.rst +0 -0
  23. {git_project-0.0.41 → git_project-0.0.43}/docs/intro.rst +0 -0
  24. {git_project-0.0.41 → git_project-0.0.43}/docs/license.rst +0 -0
  25. {git_project-0.0.41 → git_project-0.0.43}/docs/make.bat +0 -0
  26. {git_project-0.0.41 → git_project-0.0.43}/docs/plugins.rst +0 -0
  27. {git_project-0.0.41 → git_project-0.0.43}/pyproject.toml +0 -0
  28. {git_project-0.0.41 → git_project-0.0.43}/requirements.txt +0 -0
  29. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/__init__.py +0 -0
  30. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/commandline.py +0 -0
  31. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/configobj.py +0 -0
  32. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/exception.py +0 -0
  33. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/gitproject.py +0 -0
  34. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/parsermanager.py +0 -0
  35. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/pluginmanager.py +0 -0
  36. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/py.typed +0 -0
  37. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/runnable.py +0 -0
  38. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/scopedobj.py +0 -0
  39. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/shell.py +0 -0
  40. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/substitutable.py +0 -0
  41. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/test_support/__init__.py +0 -0
  42. {git_project-0.0.41 → git_project-0.0.43}/src/git_project/test_support/common.py +0 -0
  43. {git_project-0.0.41 → git_project-0.0.43}/tests/test_confobj.py +0 -0
  44. {git_project-0.0.41 → git_project-0.0.43}/tests/test_gitproject.py +0 -0
  45. {git_project-0.0.41 → git_project-0.0.43}/tests/test_parsermanager.py +0 -0
  46. {git_project-0.0.41 → git_project-0.0.43}/tests/test_runnable.py +0 -0
  47. {git_project-0.0.41 → git_project-0.0.43}/tests/test_scopedobj.py +0 -0
  48. {git_project-0.0.41 → git_project-0.0.43}/tests/test_shell.py +0 -0
  49. {git_project-0.0.41 → 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.41
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,30 +214,30 @@ Authors
214
214
  .. _David Greene: https://github.com/greened
215
215
 
216
216
 
217
- `0.0.41`_ - 2026-10-06
217
+ `0.0.43`_ - 2026-10-07
218
218
  ----------------------
219
+ Changed
220
+ .......
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
+
219
227
  Removed
220
228
  .......
221
- - The ``GitProjectException`` alias is gone. Use ``GitProjectError``.
222
- core-plugins 0.0.28 is the first release that uses the new name, so an
223
- older core-plugins fails to import with this git-project.
229
+ - ``Git.LsRemotesCallbacks`` and ``Git.RemoteBranchDeleteCallback`` are
230
+ gone, because no git-project method uses them.
224
231
 
225
232
  Fixed
226
233
  .....
227
- - ``prune_worktree`` refused to prune a worktree with the message
228
- ``Will not prune existing worktree {name}``. It now names the worktree.
229
- - ``ParserManagerMock.ParserMock`` compared unequal to an equal mock:
230
- ``==`` returned None, and ``!=`` returned True.
231
-
232
- Security
233
- ........
234
- - Substitution no longer evaluates a config value as a Python f-string.
235
- Before, any expression in braces ran, so a value from an included config
236
- file could run code. Now only ``{name}`` is replaced, and an expression
237
- such as ``{x.replace(...)}`` stays as written. A value may now contain
238
- ``'``, and a backslash in a value stays as written.
239
-
240
- .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.41...HEAD
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``.
237
+
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
240
+ .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
241
241
  .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
242
242
  .. _0.0.40: https://github.com/greened/git-project/compare/v0.0.39...v0.0.40
243
243
  .. _0.0.39: https://github.com/greened/git-project/compare/v0.0.38...v0.0.39
@@ -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.41'
22
- __version_tuple__ = version_tuple = (0, 0, 41)
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,53 @@ 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
+
55
+ `0.0.42`_ - 2026-10-06
56
+ ----------------------
57
+ Added
58
+ .....
59
+ - A command can set ``write_project_defaults=False`` on its parser, so that
60
+ git-project does not write the project's default ``branch`` and
61
+ ``remote`` to the config. A dry run can then leave the config as it was.
62
+ - ``Project.get`` takes ``set_defaults``, True by default. With False, it
63
+ does not write the defaults.
64
+
65
+ Changed
66
+ .......
67
+ - git-project writes the project defaults after the command line is
68
+ parsed, not when it builds the project. So ``-h``, ``--version``,
69
+ ``--menu`` and a command-line error no longer write them. The plugin
70
+ hooks ``add_class_hooks``, ``add_arguments`` and ``modify_arguments``
71
+ can see a project without its default branch and remote.
72
+
73
+ Fixed
74
+ .....
75
+ - ``branch prune``, ``worktree rm`` and ``Project.prune_branch`` stopped
76
+ and kept the local branch when a remote could not be reached, such as
77
+ one whose URL names a host alias from ``~/.ssh/config``, which libgit2
78
+ does not read, or when a remote refused the delete. They now warn about
79
+ that remote on stderr and delete the local branch.
80
+
34
81
  `0.0.41`_ - 2026-10-06
35
82
  ----------------------
36
83
  Removed
@@ -177,7 +224,9 @@ Fixed
177
224
  ``git_project``. No declared environment supplied Sphinx either, so a
178
225
  ``docs`` environment with Sphinx is now declared.
179
226
 
180
- .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.41...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
229
+ .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
181
230
  .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
182
231
  .. _0.0.40: https://github.com/greened/git-project/compare/v0.0.39...v0.0.40
183
232
  .. _0.0.39: https://github.com/greened/git-project/compare/v0.0.38...v0.0.39
@@ -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
@@ -30,12 +30,15 @@ does the work, in this order:
30
30
  file for repeated entries.
31
31
  #. Take the active project's name from the program name, with any ``git-``
32
32
  prefix removed.
33
- #. Build the active Project.
33
+ #. Build the active Project, without its defaults.
34
34
  #. Load the plugins and call each one's ``add_class_hooks``, which receives
35
35
  the project.
36
36
  #. Build the GitProject, now that the class hooks are in place.
37
37
  #. Parse the command line. Every plugin's ``add_arguments`` runs, then every
38
38
  plugin's ``modify_arguments``. See git_project.commandline.
39
+ #. Write the project's missing defaults, branch and remote, unless the
40
+ chosen command set ``write_project_defaults`` to False. See
41
+ Project.set_defaults.
39
42
  #. Call each plugin's ``initialize``.
40
43
  #. Call the chosen command's ``func(git, gitproject, project, clargs)``.
41
44
  #. Check the config file again, and return what ``func`` returned.
@@ -70,7 +73,8 @@ def main_impl(args=None):
70
73
 
71
74
  plugin_manager = git_project.PluginManager()
72
75
 
73
- project = git_project.Project.get(git, project_name)
76
+ # Only the parsed command knows whether it may write the config.
77
+ project = git_project.Project.get(git, project_name, set_defaults=False)
74
78
 
75
79
  plugin_manager.load_plugins(git, project)
76
80
 
@@ -81,6 +85,10 @@ def main_impl(args=None):
81
85
  git, gp, project, plugin_manager, args
82
86
  )
83
87
 
88
+ # Before initialize, which may read them.
89
+ if getattr(clargs, "write_project_defaults", True):
90
+ project.set_defaults()
91
+
84
92
  plugin_manager.initialize_plugins(git, gp, project)
85
93
 
86
94
  rc = clargs.func(git, gp, project, clargs)
@@ -81,7 +81,9 @@ plugin before the next hook:
81
81
  this hook.
82
82
  #. ``add_arguments``. Add commands and options.
83
83
  #. ``modify_arguments``. Change what other plugins added.
84
- #. The command line is parsed.
84
+ #. The command line is parsed, and the project's missing defaults are
85
+ written unless the command opts out (see Commands). Until then, a
86
+ project read can miss its default branch and remote.
85
87
  #. ``initialize``. Set up state, such as pushing a scope.
86
88
  #. The chosen command's function runs.
87
89
 
@@ -102,6 +104,15 @@ GitProject for the repository, project is the active Project and clargs is
102
104
  the parsed command line. An int return is the exit status. Any other return
103
105
  exits with 0.
104
106
 
107
+ Before a command runs, git-project writes the project's ``branch`` and
108
+ ``remote`` to the config when they are unset. A command that must not
109
+ write the config, such as a dry run, opts out::
110
+
111
+ parser.set_defaults(write_project_defaults=False)
112
+
113
+ The command then sees no default branch or remote unless the config has
114
+ one.
115
+
105
116
  A plugin extends another plugin's command in ``modify_arguments``. Find its
106
117
  parser by key with ``parser_manager.find_parser(key)``, add options to it,
107
118
  and wrap its function::
@@ -22,6 +22,9 @@
22
22
  # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
23
 
24
24
 
25
+ import sys
26
+
27
+ from .exception import GitProjectError
25
28
  from .git import Git
26
29
  from .scopedobj import ScopedConfigObject
27
30
 
@@ -38,8 +41,8 @@ class Project(ScopedConfigObject):
38
41
  it, so reading a project attribute gives the value from the topmost scope
39
42
  that has it. See git_project.scopedobj.
40
43
 
41
- Building a project sets the defaults branch and remote when they are
42
- missing. See set_defaults.
44
+ get sets the default branch and remote when they are missing, unless
45
+ set_defaults is False. See set_defaults.
43
46
 
44
47
  """
45
48
 
@@ -60,10 +63,8 @@ class Project(ScopedConfigObject):
60
63
  """
61
64
  super().__init__(git, section, subsection, ident, **kwargs)
62
65
 
63
- self.set_defaults()
64
-
65
66
  @classmethod
66
- def get(cls, git, section, **kwargs):
67
+ def get(cls, git, section, set_defaults=True, **kwargs):
67
68
  """A factory to construct the active project from its git config.
68
69
 
69
70
  cls: The derived class being constructed.
@@ -73,10 +74,14 @@ class Project(ScopedConfigObject):
73
74
  section: The project name. It is mapped to a git config section name, so
74
75
  '.' and '_' become '-'.
75
76
 
77
+ set_defaults: Whether to call set_defaults, which may write the config.
78
+
76
79
  kwargs: Keyword arguments of property values to set upon construction.
77
80
 
78
81
  """
79
82
  project = super().get(git, section, None, None, **kwargs)
83
+ if set_defaults:
84
+ project.set_defaults()
80
85
  return project
81
86
 
82
87
  def set_defaults(self):
@@ -204,7 +209,9 @@ class Project(ScopedConfigObject):
204
209
 
205
210
  def prune_branch(self, branch, keep_remote_branch=False):
206
211
  """Delete a branch locally and, unless keep_remote_branch is set, on any
207
- remotes on which it exists.
212
+ remotes on which it exists. A remote that cannot be reached, or that
213
+ refuses the delete, gets a warning, and the local branch is deleted
214
+ anyway.
208
215
 
209
216
  branch: The branch to delete.
210
217
 
@@ -213,8 +220,15 @@ class Project(ScopedConfigObject):
213
220
 
214
221
  """
215
222
  if not keep_remote_branch:
223
+ # Raise a bad ssh.id here, so the handler below cannot report it
224
+ # as a remote refusal.
225
+ self._git.get_ssh_id()
216
226
  for remote in self.iterremotes():
217
- if self._git.remote_branch_exists(branch, remote):
218
- self._git.delete_remote_branch(branch, remote)
227
+ # A remote failure must not stop the local delete.
228
+ try:
229
+ if self._git.remote_branch_exists(branch, remote):
230
+ self._git.delete_remote_branch(branch, remote)
231
+ except GitProjectError as error:
232
+ print(f"warning: {error}", file=sys.stderr)
219
233
  if self._git.committish_exists(branch):
220
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
- )
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # SPDX-FileCopyrightText: 2020-present David A. Greene <dag@obbligato.org>
4
+
5
+ # SPDX-License-Identifier: AGPL-3.0-or-later
6
+
7
+ # Copyright 2024 David A. Greene
8
+
9
+ # This file is part of git-project
10
+
11
+ # git-project is free software: you can redistribute it and/or modify it under
12
+ # the terms of the GNU Affero General Public License as published by the Free
13
+ # Software Foundation, either version 3 of the License, or (at your option) any
14
+ # later version.
15
+
16
+ # This program is distributed in the hope that it will be useful, but WITHOUT
17
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18
+ # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19
+ # details.
20
+
21
+ # You should have received a copy of the GNU Affero General Public License along
22
+ # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
+
24
+
25
+ import pytest
26
+
27
+ import git_project
28
+ from git_project.test_support import check_config_file
29
+
30
+
31
+ def test_main_no_dup(reset_directory, git, project):
32
+ project._git.validate_config()
33
+
34
+ project._git.validate_config()
35
+ git_project.main_impl(["config", "branch"])
36
+
37
+ project.build = "devrel"
38
+
39
+ project._git.validate_config()
40
+ git_project.main_impl(["config", "branch"])
41
+
42
+ project.add_item("build", "check-devrel")
43
+
44
+ project._git.validate_config()
45
+ git_project.main_impl(["config", "branch"])
46
+
47
+ check_config_file("project", "build", {"devrel", "check-devrel"})
48
+
49
+ project._git.validate_config()
50
+ git_project.main_impl(["config", "branch"])
51
+
52
+ check_config_file("project", "build", {"devrel", "check-devrel"})
53
+
54
+
55
+ def test_main_help_shows_summary(reset_directory, git, capsys):
56
+ with pytest.raises(SystemExit):
57
+ git_project.main_impl(["--help"])
58
+
59
+ out = capsys.readouterr().out
60
+ assert "git <project> <command> [<options>]" in out
61
+ assert "The name git-project runs under selects the active project." in out
62
+
63
+
64
+ class _DefaultsPlugin(git_project.Plugin):
65
+ """Adds 'look', which may write the defaults, and 'peek', which may not."""
66
+
67
+ def __init__(self):
68
+ super().__init__("defaults")
69
+ self.branch_at_initialize = None
70
+
71
+ def initialize(self, git, gitproject, project, plugin_manager):
72
+ self.branch_at_initialize = project.has_item("branch")
73
+
74
+ def add_arguments(
75
+ self, git, gitproject, project, parser_manager, plugin_manager
76
+ ):
77
+ look = git_project.add_top_level_command(
78
+ parser_manager, "look", "look"
79
+ )
80
+ look.set_defaults(func=lambda *args: 0)
81
+ peek = git_project.add_top_level_command(
82
+ parser_manager, "peek", "peek"
83
+ )
84
+ peek.set_defaults(func=lambda *args: 0, write_project_defaults=False)
85
+
86
+
87
+ @pytest.fixture
88
+ def defaults_plugin(monkeypatch):
89
+ plugin = _DefaultsPlugin()
90
+
91
+ def load_plugins(self, git, project):
92
+ self.plugins.append(plugin)
93
+
94
+ monkeypatch.setattr(
95
+ git_project.PluginManager, "load_plugins", load_plugins
96
+ )
97
+ monkeypatch.setattr("sys.argv", ["git-project"])
98
+ return plugin
99
+
100
+
101
+ @pytest.mark.parametrize("command, written", [("look", True), ("peek", False)])
102
+ def test_main_project_defaults(
103
+ reset_directory, git, defaults_plugin, command, written
104
+ ):
105
+ assert not git.config.has_item("project", "branch")
106
+ assert not git.config.has_item("project", "remote")
107
+
108
+ git_project.main_impl([command])
109
+
110
+ config = git_project.Git().config
111
+ assert config.has_item("project", "branch") == written
112
+ assert config.has_item("project", "remote") == written
113
+ if written:
114
+ assert config.get_item("project", "branch") == "master"
115
+ assert config.get_item("project", "remote") == "origin"
116
+
117
+
118
+ def test_main_project_defaults_before_initialize(
119
+ reset_directory, git, defaults_plugin
120
+ ):
121
+ assert not git.config.has_item("project", "branch")
122
+
123
+ git_project.main_impl(["look"])
124
+
125
+ assert defaults_plugin.branch_at_initialize is True
@@ -208,3 +208,74 @@ def test_project_branch_is_pushed_indirectly(project):
208
208
 
209
209
  def test_project_branch_is_merged_indirectly(project):
210
210
  assert project.branch_is_merged("pushed_indirectly")
211
+
212
+
213
+ def test_project_prune_branch_unreachable_remote(
214
+ reset_directory, remote_repository, tmp_path_factory, capsys
215
+ ):
216
+ project = clone_with_pushed_branch(remote_repository, tmp_path_factory)
217
+ missing = tmp_path_factory.mktemp("missing") / "none.git"
218
+ project._git.config.set_item("remote.origin", "url", f"file://{missing}")
219
+
220
+ project.prune_branch("pushed")
221
+
222
+ assert not project._git.committish_exists("pushed")
223
+ err = capsys.readouterr().err
224
+ assert "warning: cannot reach remote origin to check pushed" in err
225
+ assert str(missing) not in err
226
+
227
+
228
+ def test_project_prune_branch_remote_refuses_delete(
229
+ reset_directory, remote_repository, tmp_path_factory, capsys
230
+ ):
231
+ project = clone_with_pushed_branch(remote_repository, tmp_path_factory)
232
+ url = project._git.config.get_item("remote.origin", "url")
233
+ git_project.capture_command(
234
+ ["git", "--git-dir", url, "config", "receive.denyDeletes", "true"]
235
+ )
236
+
237
+ project.prune_branch("pushed")
238
+
239
+ assert not project._git.committish_exists("pushed")
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)
273
+
274
+
275
+ def test_project_get_without_defaults(git):
276
+ project = git_project.Project.get(git, "project", set_defaults=False)
277
+
278
+ assert not project.has_item("remote")
279
+ assert not project.has_item("branch")
280
+ assert not git.config.has_item("project", "remote")
281
+ assert not git.config.has_item("project", "branch")
@@ -1,61 +0,0 @@
1
- #!/usr/bin/env python3
2
- #
3
- # SPDX-FileCopyrightText: 2020-present David A. Greene <dag@obbligato.org>
4
-
5
- # SPDX-License-Identifier: AGPL-3.0-or-later
6
-
7
- # Copyright 2024 David A. Greene
8
-
9
- # This file is part of git-project
10
-
11
- # git-project is free software: you can redistribute it and/or modify it under
12
- # the terms of the GNU Affero General Public License as published by the Free
13
- # Software Foundation, either version 3 of the License, or (at your option) any
14
- # later version.
15
-
16
- # This program is distributed in the hope that it will be useful, but WITHOUT
17
- # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18
- # FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19
- # details.
20
-
21
- # You should have received a copy of the GNU Affero General Public License along
22
- # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
-
24
-
25
- import pytest
26
-
27
- import git_project
28
- from git_project.test_support import check_config_file
29
-
30
-
31
- def test_main_no_dup(reset_directory, git, project):
32
- project._git.validate_config()
33
-
34
- project._git.validate_config()
35
- git_project.main_impl(["config", "branch"])
36
-
37
- project.build = "devrel"
38
-
39
- project._git.validate_config()
40
- git_project.main_impl(["config", "branch"])
41
-
42
- project.add_item("build", "check-devrel")
43
-
44
- project._git.validate_config()
45
- git_project.main_impl(["config", "branch"])
46
-
47
- check_config_file("project", "build", {"devrel", "check-devrel"})
48
-
49
- project._git.validate_config()
50
- git_project.main_impl(["config", "branch"])
51
-
52
- check_config_file("project", "build", {"devrel", "check-devrel"})
53
-
54
-
55
- def test_main_help_shows_summary(reset_directory, git, capsys):
56
- with pytest.raises(SystemExit):
57
- git_project.main_impl(["--help"])
58
-
59
- out = capsys.readouterr().out
60
- assert "git <project> <command> [<options>]" in out
61
- assert "The name git-project runs under selects the active project." in out
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes