git-project 0.0.40__tar.gz → 0.0.42__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.40 → git_project-0.0.42}/PKG-INFO +30 -31
  2. {git_project-0.0.40 → git_project-0.0.42}/_version.py +2 -2
  3. {git_project-0.0.40 → git_project-0.0.42}/docs/changelog.rst +52 -1
  4. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/__init__.py +10 -9
  5. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/exception.py +0 -4
  6. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/git.py +1 -1
  7. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/main.py +10 -2
  8. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/plugin.py +12 -1
  9. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/project.py +34 -8
  10. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/substitutable.py +35 -42
  11. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/test_support/common.py +1 -0
  12. {git_project-0.0.40 → git_project-0.0.42}/tests/test_git.py +8 -2
  13. git_project-0.0.42/tests/test_main.py +125 -0
  14. {git_project-0.0.40 → git_project-0.0.42}/tests/test_parsermanager.py +13 -0
  15. {git_project-0.0.40 → git_project-0.0.42}/tests/test_project.py +51 -0
  16. {git_project-0.0.40 → git_project-0.0.42}/tests/test_substitutable.py +112 -5
  17. git_project-0.0.40/tests/test_main.py +0 -61
  18. {git_project-0.0.40 → git_project-0.0.42}/.gitignore +0 -0
  19. {git_project-0.0.40 → git_project-0.0.42}/CONTRIBUTORS +0 -0
  20. {git_project-0.0.40 → git_project-0.0.42}/COPYING +0 -0
  21. {git_project-0.0.40 → git_project-0.0.42}/MANIFEST.in +0 -0
  22. {git_project-0.0.40 → git_project-0.0.42}/docs/Makefile +0 -0
  23. {git_project-0.0.40 → git_project-0.0.42}/docs/api.rst +0 -0
  24. {git_project-0.0.40 → git_project-0.0.42}/docs/authors.rst +0 -0
  25. {git_project-0.0.40 → git_project-0.0.42}/docs/conf.py +0 -0
  26. {git_project-0.0.40 → git_project-0.0.42}/docs/contributing.rst +0 -0
  27. {git_project-0.0.40 → git_project-0.0.42}/docs/index.rst +0 -0
  28. {git_project-0.0.40 → git_project-0.0.42}/docs/intro.rst +0 -0
  29. {git_project-0.0.40 → git_project-0.0.42}/docs/license.rst +0 -0
  30. {git_project-0.0.40 → git_project-0.0.42}/docs/make.bat +0 -0
  31. {git_project-0.0.40 → git_project-0.0.42}/docs/plugins.rst +0 -0
  32. {git_project-0.0.40 → git_project-0.0.42}/pyproject.toml +0 -0
  33. {git_project-0.0.40 → git_project-0.0.42}/requirements.txt +0 -0
  34. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/commandline.py +0 -0
  35. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/configobj.py +0 -0
  36. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/gitproject.py +0 -0
  37. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/parsermanager.py +0 -0
  38. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/pluginmanager.py +0 -0
  39. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/py.typed +0 -0
  40. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/runnable.py +0 -0
  41. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/scopedobj.py +0 -0
  42. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/shell.py +0 -0
  43. {git_project-0.0.40 → git_project-0.0.42}/src/git_project/test_support/__init__.py +0 -0
  44. {git_project-0.0.40 → git_project-0.0.42}/tests/conftest.py +0 -0
  45. {git_project-0.0.40 → git_project-0.0.42}/tests/test_confobj.py +0 -0
  46. {git_project-0.0.40 → git_project-0.0.42}/tests/test_gitproject.py +0 -0
  47. {git_project-0.0.40 → git_project-0.0.42}/tests/test_runnable.py +0 -0
  48. {git_project-0.0.40 → git_project-0.0.42}/tests/test_scopedobj.py +0 -0
  49. {git_project-0.0.40 → git_project-0.0.42}/tests/test_shell.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: git-project
3
- Version: 0.0.40
3
+ Version: 0.0.42
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
@@ -148,14 +148,16 @@ the value of ``name``. A name can be:
148
148
  The root of the current worktree
149
149
 
150
150
  Substitution repeats until the value stops changing, so a value can name
151
- another value that itself contains ``{name}``. A value may not name itself.
152
- To write a literal brace, write ``{{}`` for ``{`` and ``{}}`` for ``}``.
151
+ another value that itself contains ``{name}``. A value may not name itself. To
152
+ write a literal brace, write ``{{}`` for ``{`` and ``{}}`` for ``}``. A name is
153
+ ASCII letters, digits and underscores, and does not start with a digit. Other
154
+ text in single braces, such as ``{x.upper()}`` or ``{}``, stays as written, but
155
+ a doubled ``{{`` or ``}}`` becomes one brace. A name that is not defined is an
156
+ error.
153
157
 
154
- **A value is evaluated as Python.** git-project substitutes a value by
155
- evaluating it as a Python f-string. So ``{1+1}`` becomes ``2``, and any
156
- Python expression in braces runs when the value is substituted. Treat the
157
- git config as code, and do not include config from a source you do not
158
- trust. A value that contains a ``'`` cannot be substituted.
158
+ Substitution inserts each value as written, and the ``run`` plugin runs
159
+ its commands through a shell. Treat the git config as code, and do not
160
+ include config from a source you do not trust.
159
161
 
160
162
  Getting help
161
163
  ============
@@ -212,38 +214,35 @@ Authors
212
214
  .. _David Greene: https://github.com/greened
213
215
 
214
216
 
215
- `0.0.40`_ - 2026-10-05
217
+ `0.0.42`_ - 2026-10-06
216
218
  ----------------------
217
219
  Added
218
220
  .....
219
- - ``capture_command`` takes a list of arguments as well as a string.
220
- - The package ships a ``py.typed`` marker, so mypy checks code that
221
- uses git-project against its annotations.
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.
222
226
 
223
227
  Changed
224
228
  .......
225
- - ``GitProjectException`` is now ``GitProjectError``. The old name still
226
- works as an alias, and a later release removes it.
227
- - The ``git_project._contributing`` module is gone. The guide to working
228
- on git-project is in the docs only, and its Tests section is now the
229
- ``git_project.test_support`` package documentation.
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.
230
234
 
231
235
  Fixed
232
236
  .....
233
- - ``substitute_value``, ``substitute_command`` and ``run`` shared one
234
- default ``formats`` dict across calls, and ``substitute_value`` added its
235
- names to it. So within one process, an object could resolve a name it does
236
- not define to another object's value. Each call now works on its own copy,
237
- and a ``formats`` dict passed in is no longer changed.
238
- - Removing one value of a config key failed when the value held a space.
239
- It was split into several arguments to ``git config --unset``. The pattern
240
- now reaches git as given, so a pattern escaped twice to get through that
241
- split must be escaped once.
242
- - ``Git.get_git_common_dir`` returns an absolute path in a worktree that plain
243
- ``git worktree add`` made. It returned the relative path that git writes, so
244
- ``{git_common_dir}`` substituted ``../..`` there.
245
-
246
- .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.40...HEAD
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.
242
+
243
+ .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.42...HEAD
244
+ .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
245
+ .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
247
246
  .. _0.0.40: https://github.com/greened/git-project/compare/v0.0.39...v0.0.40
248
247
  .. _0.0.39: https://github.com/greened/git-project/compare/v0.0.38...v0.0.39
249
248
  .. _0.0.38: https://github.com/greened/git-project/compare/v0.0.37...v0.0.38
@@ -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.40'
22
- __version_tuple__ = version_tuple = (0, 0, 40)
21
+ __version__ = version = '0.0.42'
22
+ __version_tuple__ = version_tuple = (0, 0, 42)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -31,6 +31,55 @@ ChangeLog
31
31
  `Unreleased`_
32
32
  -------------
33
33
 
34
+ `0.0.42`_ - 2026-10-06
35
+ ----------------------
36
+ Added
37
+ .....
38
+ - A command can set ``write_project_defaults=False`` on its parser, so that
39
+ git-project does not write the project's default ``branch`` and
40
+ ``remote`` to the config. A dry run can then leave the config as it was.
41
+ - ``Project.get`` takes ``set_defaults``, True by default. With False, it
42
+ does not write the defaults.
43
+
44
+ Changed
45
+ .......
46
+ - git-project writes the project defaults after the command line is
47
+ parsed, not when it builds the project. So ``-h``, ``--version``,
48
+ ``--menu`` and a command-line error no longer write them. The plugin
49
+ hooks ``add_class_hooks``, ``add_arguments`` and ``modify_arguments``
50
+ can see a project without its default branch and remote.
51
+
52
+ Fixed
53
+ .....
54
+ - ``branch prune``, ``worktree rm`` and ``Project.prune_branch`` stopped
55
+ and kept the local branch when a remote could not be reached, such as
56
+ one whose URL names a host alias from ``~/.ssh/config``, which libgit2
57
+ does not read, or when a remote refused the delete. They now warn about
58
+ that remote on stderr and delete the local branch.
59
+
60
+ `0.0.41`_ - 2026-10-06
61
+ ----------------------
62
+ Removed
63
+ .......
64
+ - The ``GitProjectException`` alias is gone. Use ``GitProjectError``.
65
+ core-plugins 0.0.28 is the first release that uses the new name, so an
66
+ older core-plugins fails to import with this git-project.
67
+
68
+ Fixed
69
+ .....
70
+ - ``prune_worktree`` refused to prune a worktree with the message
71
+ ``Will not prune existing worktree {name}``. It now names the worktree.
72
+ - ``ParserManagerMock.ParserMock`` compared unequal to an equal mock:
73
+ ``==`` returned None, and ``!=`` returned True.
74
+
75
+ Security
76
+ ........
77
+ - Substitution no longer evaluates a config value as a Python f-string.
78
+ Before, any expression in braces ran, so a value from an included config
79
+ file could run code. Now only ``{name}`` is replaced, and an expression
80
+ such as ``{x.replace(...)}`` stays as written. A value may now contain
81
+ ``'``, and a backslash in a value stays as written.
82
+
34
83
  `0.0.40`_ - 2026-10-05
35
84
  ----------------------
36
85
  Added
@@ -154,7 +203,9 @@ Fixed
154
203
  ``git_project``. No declared environment supplied Sphinx either, so a
155
204
  ``docs`` environment with Sphinx is now declared.
156
205
 
157
- .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.40...HEAD
206
+ .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.42...HEAD
207
+ .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
208
+ .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
158
209
  .. _0.0.40: https://github.com/greened/git-project/compare/v0.0.39...v0.0.40
159
210
  .. _0.0.39: https://github.com/greened/git-project/compare/v0.0.38...v0.0.39
160
211
  .. _0.0.38: https://github.com/greened/git-project/compare/v0.0.37...v0.0.38
@@ -140,14 +140,16 @@ the value of ``name``. A name can be:
140
140
  The root of the current worktree
141
141
 
142
142
  Substitution repeats until the value stops changing, so a value can name
143
- another value that itself contains ``{name}``. A value may not name itself.
144
- To write a literal brace, write ``{{}`` for ``{`` and ``{}}`` for ``}``.
143
+ another value that itself contains ``{name}``. A value may not name itself. To
144
+ write a literal brace, write ``{{}`` for ``{`` and ``{}}`` for ``}``. A name is
145
+ ASCII letters, digits and underscores, and does not start with a digit. Other
146
+ text in single braces, such as ``{x.upper()}`` or ``{}``, stays as written, but
147
+ a doubled ``{{`` or ``}}`` becomes one brace. A name that is not defined is an
148
+ error.
145
149
 
146
- **A value is evaluated as Python.** git-project substitutes a value by
147
- evaluating it as a Python f-string. So ``{1+1}`` becomes ``2``, and any
148
- Python expression in braces runs when the value is substituted. Treat the
149
- git config as code, and do not include config from a source you do not
150
- trust. A value that contains a ``'`` cannot be substituted.
150
+ Substitution inserts each value as written, and the ``run`` plugin runs
151
+ its commands through a shell. Treat the git config as code, and do not
152
+ include config from a source you do not trust.
151
153
 
152
154
  Getting help
153
155
  ============
@@ -175,7 +177,7 @@ from .commandline import (
175
177
  parse_arguments,
176
178
  )
177
179
  from .configobj import ConfigObject
178
- from .exception import GitProjectError, GitProjectException
180
+ from .exception import GitProjectError
179
181
  from .git import Git
180
182
  from .gitproject import GitProject
181
183
  from .main import main_impl
@@ -193,7 +195,6 @@ __all__ = [
193
195
  "Git",
194
196
  "GitProject",
195
197
  "GitProjectError",
196
- "GitProjectException",
197
198
  "ParserManager",
198
199
  "Plugin",
199
200
  "PluginManager",
@@ -42,7 +42,3 @@ class GitProjectError(Exception):
42
42
  def message(self):
43
43
  command = Path(sys.argv[0]).name
44
44
  return f"{command}: {self._message}"
45
-
46
-
47
- # The old name, kept so that plugins written against it still import.
48
- GitProjectException = GitProjectError
@@ -893,7 +893,7 @@ class Git:
893
893
  """
894
894
  worktree = self._repo.lookup_worktree(name)
895
895
  if os.path.exists(worktree.path):
896
- raise GitProjectError("Will not prune existing worktree {name}")
896
+ raise GitProjectError(f"Will not prune existing worktree {name}")
897
897
 
898
898
  # Prune the worktree. For some reason, libgit2 treats a worktree as
899
899
  # valid unless both the worktree directory and data dir under
@@ -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,11 @@
22
22
  # with git-project. If not, see <https://www.gnu.org/licenses/>.
23
23
 
24
24
 
25
+ import sys
26
+
27
+ import pygit2
28
+
29
+ from .exception import GitProjectError
25
30
  from .git import Git
26
31
  from .scopedobj import ScopedConfigObject
27
32
 
@@ -38,8 +43,8 @@ class Project(ScopedConfigObject):
38
43
  it, so reading a project attribute gives the value from the topmost scope
39
44
  that has it. See git_project.scopedobj.
40
45
 
41
- Building a project sets the defaults branch and remote when they are
42
- missing. See set_defaults.
46
+ get sets the default branch and remote when they are missing, unless
47
+ set_defaults is False. See set_defaults.
43
48
 
44
49
  """
45
50
 
@@ -60,10 +65,8 @@ class Project(ScopedConfigObject):
60
65
  """
61
66
  super().__init__(git, section, subsection, ident, **kwargs)
62
67
 
63
- self.set_defaults()
64
-
65
68
  @classmethod
66
- def get(cls, git, section, **kwargs):
69
+ def get(cls, git, section, set_defaults=True, **kwargs):
67
70
  """A factory to construct the active project from its git config.
68
71
 
69
72
  cls: The derived class being constructed.
@@ -73,10 +76,14 @@ class Project(ScopedConfigObject):
73
76
  section: The project name. It is mapped to a git config section name, so
74
77
  '.' and '_' become '-'.
75
78
 
79
+ set_defaults: Whether to call set_defaults, which may write the config.
80
+
76
81
  kwargs: Keyword arguments of property values to set upon construction.
77
82
 
78
83
  """
79
84
  project = super().get(git, section, None, None, **kwargs)
85
+ if set_defaults:
86
+ project.set_defaults()
80
87
  return project
81
88
 
82
89
  def set_defaults(self):
@@ -204,7 +211,9 @@ class Project(ScopedConfigObject):
204
211
 
205
212
  def prune_branch(self, branch, keep_remote_branch=False):
206
213
  """Delete a branch locally and, unless keep_remote_branch is set, on any
207
- remotes on which it exists.
214
+ remotes on which it exists. A remote that cannot be reached, or that
215
+ refuses the delete, gets a warning, and the local branch is deleted
216
+ anyway.
208
217
 
209
218
  branch: The branch to delete.
210
219
 
@@ -213,8 +222,25 @@ class Project(ScopedConfigObject):
213
222
 
214
223
  """
215
224
  if not keep_remote_branch:
225
+ # Raise a bad ssh.id here, so the handler below cannot report it
226
+ # as a remote refusal.
227
+ self._git.get_ssh_id()
216
228
  for remote in self.iterremotes():
217
- if self._git.remote_branch_exists(branch, remote):
218
- self._git.delete_remote_branch(branch, remote)
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.
232
+ try:
233
+ if self._git.remote_branch_exists(branch, remote):
234
+ 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
+ except GitProjectError as error:
243
+ # The remote refused the delete, and says why.
244
+ print(f"warning: {remote}: {error}", file=sys.stderr)
219
245
  if self._git.committish_exists(branch):
220
246
  self._git.delete_branch(Git.refname_to_branch_name(branch))
@@ -40,16 +40,27 @@ The names come from four places, and a later one wins over an earlier one:
40
40
  A name that none of them define is looked up as a scope name through
41
41
  ``get_scope``, and gives that scope's ident.
42
42
 
43
- The string is evaluated as a Python f-string with these names as its
44
- globals, again and again until it stops changing. So substitution runs any
45
- Python expression in braces. Treat config values as code.
43
+ Substitution replaces each ``{name}`` whose name is ASCII letters, digits and
44
+ underscores and does not start with a digit, and repeats until the string stops
45
+ changing. Nothing is evaluated. Other text in single braces, such as
46
+ ``{x.replace("a", "b")}``, ``{x[0]}`` or ``{}``, stays as written. A doubled
47
+ ``{{`` or ``}}`` becomes one brace on each pass. A name that no source defines
48
+ and that names no scope raises ``NameError``.
46
49
 
47
50
  """
48
51
 
52
+ import re
49
53
  from pathlib import Path
50
54
 
51
55
  from .configobj import ConfigObject
52
56
 
57
+ # One alternation, scanned left to right like an f-string: a doubled
58
+ # brace is a literal brace, and only a bare identifier is a field.
59
+ _FIELD = re.compile(r"\{\{|\}\}|\{([A-Za-z_][A-Za-z0-9_]*)\}")
60
+ # Git config cannot hold NUL, so a config value cannot collide with these.
61
+ _LBRACE = "\x00("
62
+ _RBRACE = "\x00)"
63
+
53
64
 
54
65
  class SubstitutableConfigObject(ConfigObject):
55
66
  """Base class for objects that use git-config as a backing store and allow
@@ -143,51 +154,33 @@ class SubstitutableConfigObject(ConfigObject):
143
154
  f"Recursive substitution: {key} is in {value}"
144
155
  )
145
156
 
146
- def try_format(string, formats):
147
- return eval(f"f'{string}'", formats)
148
-
149
157
  def add_scope(project, key, formats):
150
158
  scope = project.get_scope(key)
151
159
  if scope:
152
160
  value = scope.get_ident()
153
161
  formats[key] = value
154
162
 
155
- # Allow escaping braces by surrounding each brace with braces. This is
156
- # not valid f-string syntax and is unlikely to be used in ordinary
157
- # config values. Replace with an equally unlikely sequence, then
158
- # substitute on that string.
159
-
160
- escaped_braces = False
163
+ def expand(match):
164
+ token = match.group(0)
165
+ if token == "{{":
166
+ return "{"
167
+ if token == "}}":
168
+ return "}"
169
+ name = match.group(1)
170
+ if name not in formats:
171
+ add_scope(project, name, formats)
172
+ if name not in formats:
173
+ raise NameError(f"name {name!r} is not defined", name=name)
174
+ return str(formats[name])
175
+
176
+ # Hide escaped braces on every pass, so that neither an escape in
177
+ # the string nor one in a substituted value is read as a field.
161
178
  while True:
162
- escaped_braces = (
163
- escaped_braces or "{{}" in string or "{}}" in string
164
- )
165
- if escaped_braces:
166
- string = string.replace("{{}", "[[[")
167
- string = string.replace("{}}", "]]]")
168
- try:
169
- newstring = try_format(string, formats)
170
- except KeyError as exception:
171
- # See if this is a scope name.
172
- for key in exception.args:
173
- add_scope(project, key, formats)
174
- # Try again after adding scopes.
175
- newstring = try_format(string, formats)
176
- except NameError as exception:
177
- # args is simply the error message, with the name surrounded by
178
- # '. Use .name attribute after upgrading to python 3.10.
179
- for arg in exception.args:
180
- key = arg.split("'")[1]
181
- add_scope(project, key, formats)
182
- # Try again after adding scopes.
183
- newstring = try_format(string, formats)
184
-
185
- changed = False if newstring == string else True
186
- string = newstring
187
- if not changed:
188
- if escaped_braces:
189
- string = string.replace("[[[", "{")
190
- string = string.replace("]]]", "}")
179
+ string = string.replace("{{}", _LBRACE)
180
+ string = string.replace("{}}", _RBRACE)
181
+ newstring = _FIELD.sub(expand, string)
182
+ if newstring == string:
191
183
  break
184
+ string = newstring
192
185
 
193
- return string
186
+ return string.replace(_LBRACE, "{").replace(_RBRACE, "}")
@@ -92,6 +92,7 @@ class ParserManagerMock:
92
92
  return False
93
93
  if self_default[1] != other_default[1]:
94
94
  return False
95
+ return True
95
96
 
96
97
  def __hash__(self):
97
98
  raise TypeError(f"unhashable type: '{type(self).__name__}'")
@@ -342,7 +342,10 @@ def test_git_worktree(reset_directory, local_repository):
342
342
 
343
343
  assert os.path.exists(worktree_path)
344
344
 
345
- with pytest.raises(git_project.GitProjectError, match="Will not prune"):
345
+ with pytest.raises(
346
+ git_project.GitProjectError,
347
+ match="Will not prune existing worktree test-wt",
348
+ ):
346
349
  git.prune_worktree("test-wt")
347
350
 
348
351
  shutil.rmtree(worktree_checkout_path)
@@ -1053,7 +1056,10 @@ def test_git_worktree_subdir(reset_directory, local_repository):
1053
1056
  wtgit = git_project.Git()
1054
1057
  assert wtgit.get_current_branch() == "user/test-wt"
1055
1058
 
1056
- with pytest.raises(git_project.GitProjectError, match="Will not prune"):
1059
+ with pytest.raises(
1060
+ git_project.GitProjectError,
1061
+ match="Will not prune existing worktree test-wt",
1062
+ ):
1057
1063
  git.prune_worktree("test-wt")
1058
1064
 
1059
1065
  shutil.rmtree(worktree_checkout_path)
@@ -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
@@ -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
+ from git_project.test_support import ParserManagerMock
25
+
24
26
 
25
27
  def test_get_or_add_parser_name_and_key(reset_directory, parser_manager):
26
28
  command = parser_manager.find_subparser("command")
@@ -37,3 +39,14 @@ def test_get_or_add_parser_name_and_key(reset_directory, parser_manager):
37
39
  # The name is what the user types.
38
40
  clargs = parser_manager.parse_args(["visible"])
39
41
  assert clargs.command == "visible"
42
+
43
+
44
+ def test_parser_mock_equality():
45
+ def make(help_text):
46
+ parser = ParserManagerMock.ParserMock("thekey")
47
+ parser.add_argument("name", help=help_text)
48
+ parser.set_defaults(func="handler")
49
+ return parser
50
+
51
+ assert make("same") == make("same")
52
+ assert make("same") != make("different")
@@ -208,3 +208,54 @@ 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
+ assert (
224
+ "warning: cannot reach remote origin to check or delete pushed"
225
+ in capsys.readouterr().err
226
+ )
227
+
228
+
229
+ def test_project_prune_branch_remote_refuses_delete(
230
+ reset_directory, remote_repository, tmp_path_factory, capsys, monkeypatch
231
+ ):
232
+ 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,
245
+ )
246
+
247
+ project.prune_branch("pushed")
248
+
249
+ assert not project._git.committish_exists("pushed")
250
+ assert "warning: origin: Could not prune remote branch" in (
251
+ capsys.readouterr().err
252
+ )
253
+
254
+
255
+ def test_project_get_without_defaults(git):
256
+ project = git_project.Project.get(git, "project", set_defaults=False)
257
+
258
+ assert not project.has_item("remote")
259
+ assert not project.has_item("branch")
260
+ assert not git.config.has_item("project", "remote")
261
+ assert not git.config.has_item("project", "branch")
@@ -436,7 +436,9 @@ def test_substitutable_substitute_command_rebase_worktree(
436
436
  )
437
437
 
438
438
 
439
- def test_substitutable_substitute_fstring(reset_directory, git):
439
+ def test_substitutable_substitute_expression_stays_literal(
440
+ reset_directory, git
441
+ ):
440
442
  class MyProject(git_project.ScopedConfigObject):
441
443
  def __init__(self):
442
444
  super().__init__(
@@ -457,10 +459,15 @@ def test_substitutable_substitute_fstring(reset_directory, git):
457
459
  git._repo.branches.create("imerge/user/test-fstr", commit)
458
460
 
459
461
  git.checkout("imerge/user/test-fstr")
460
- current_branch = git.get_current_branch()
461
462
 
462
463
  git_project.run_command_with_shell("git rebase --exec false origin/master")
463
464
 
465
+ command = substitutable.substitute_value(
466
+ git, project, "cd {builddir}/{branch}"
467
+ )
468
+
469
+ assert command == "cd /path/to/build/imerge/user/test-fstr"
470
+
464
471
  substitutable.command = (
465
472
  'cd {builddir}/{branch.replace("imerge/", "", 1)} && make {target}'
466
473
  )
@@ -469,9 +476,8 @@ def test_substitutable_substitute_fstring(reset_directory, git):
469
476
  git, project, substitutable.command
470
477
  )
471
478
 
472
- assert (
473
- command
474
- == f'cd {project.builddir}/{current_branch.replace("imerge/", "", 1)} && make {project.target}'
479
+ assert command == (
480
+ 'cd /path/to/build/{branch.replace("imerge/", "", 1)} && make debug'
475
481
  )
476
482
 
477
483
 
@@ -704,3 +710,104 @@ def test_substitutable_substitute_formats_not_shared(reset_directory, git):
704
710
  # The second object has no leaked item, so it cannot see the first's.
705
711
  with pytest.raises(NameError):
706
712
  second.substitute_value(git, project, "{leaked}")
713
+
714
+
715
+ class MyTargetProject(git_project.ScopedConfigObject):
716
+ def __init__(self, git):
717
+ super().__init__(
718
+ git,
719
+ "project",
720
+ None,
721
+ "myproject",
722
+ builddir="/path/to/build",
723
+ target="debug",
724
+ )
725
+
726
+
727
+ def substitute(git, string):
728
+ substitutable = MySubstitutable.get(git, "project", "test")
729
+ project = MyTargetProject(git)
730
+ return substitutable.substitute_value(git, project, string)
731
+
732
+
733
+ def test_substitutable_substitute_no_code_execution(
734
+ reset_directory, git, tmp_path
735
+ ):
736
+ pwned = tmp_path / "pwned"
737
+ value = f'{{__import__("os").system("touch {pwned}")}}'
738
+
739
+ assert substitute(git, value) == value
740
+ assert not pwned.exists()
741
+
742
+
743
+ def test_substitutable_substitute_single_quote(reset_directory, git):
744
+ assert substitute(git, "echo '{target}'") == "echo 'debug'"
745
+
746
+
747
+ @pytest.mark.parametrize(
748
+ "value",
749
+ [
750
+ "{target.upper()}",
751
+ "{target[0]}",
752
+ "{target.__class__}",
753
+ "{target!r}",
754
+ "{target:>8}",
755
+ "{1+1}",
756
+ "{ target }",
757
+ ],
758
+ # The fixtures put the test id in a repo path, so keep it plain.
759
+ ids=["call", "index", "attribute", "conversion", "spec", "sum", "spaces"],
760
+ )
761
+ def test_substitutable_substitute_attribute_index_spec_literal(
762
+ reset_directory, git, value
763
+ ):
764
+ assert substitute(git, value) == value
765
+
766
+
767
+ @pytest.mark.parametrize(
768
+ "value, expected",
769
+ [
770
+ ("awk '{print $1}' {target}", "awk '{print $1}' debug"),
771
+ (r"find . -exec echo {} \;", r"find . -exec echo {} \;"),
772
+ ("a { b", "a { b"),
773
+ ("a } b", "a } b"),
774
+ ],
775
+ # The fixtures put the test id in a repo path, so keep it plain.
776
+ ids=["awk", "empty", "open", "close"],
777
+ )
778
+ def test_substitutable_substitute_stray_braces_literal(
779
+ reset_directory, git, value, expected
780
+ ):
781
+ assert substitute(git, value) == expected
782
+
783
+
784
+ def test_substitutable_substitute_escaped_name_not_substituted(
785
+ reset_directory, git
786
+ ):
787
+ assert substitute(git, "{{}target{}}") == "{target}"
788
+
789
+
790
+ def test_substitutable_substitute_doubled_braces(reset_directory, git):
791
+ assert substitute(git, "{{target}}") == "debug"
792
+
793
+
794
+ def test_substitutable_substitute_sentinel_text_literal(reset_directory, git):
795
+ assert substitute(git, "[[[x]]] {{}y{}}") == "[[[x]]] {y}"
796
+
797
+
798
+ def test_substitutable_substitute_two_scopes_one_pass(reset_directory, git):
799
+ class MyScope(git_project.ScopedConfigObject):
800
+ def __init__(self, subsection, ident):
801
+ super().__init__(git, "project", subsection, ident)
802
+
803
+ substitutable = MySubstitutable.get(git, "project", "test")
804
+
805
+ project = MyTargetProject(git)
806
+ project.push_scope(MyScope("worktree", "myworktree"))
807
+ project.push_scope(MyScope("build", "mybuild"))
808
+
809
+ command = substitutable.substitute_value(
810
+ git, project, "{worktree}/{build}"
811
+ )
812
+
813
+ assert command == "myworktree/mybuild"
@@ -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