git-project 0.0.43__tar.gz → 0.0.44__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 (52) hide show
  1. {git_project-0.0.43 → git_project-0.0.44}/PKG-INFO +30 -18
  2. {git_project-0.0.43 → git_project-0.0.44}/_version.py +2 -2
  3. git_project-0.0.44/changelog.d/README.rst +35 -0
  4. git_project-0.0.44/changelog.py +531 -0
  5. {git_project-0.0.43 → git_project-0.0.44}/docs/changelog.rst +31 -1
  6. {git_project-0.0.43 → git_project-0.0.44}/docs/contributing.rst +21 -7
  7. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/__init__.py +4 -1
  8. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/configobj.py +7 -11
  9. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/git.py +47 -14
  10. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/parsermanager.py +65 -10
  11. git_project-0.0.44/tests/test_changelog.py +792 -0
  12. {git_project-0.0.43 → git_project-0.0.44}/tests/test_confobj.py +75 -2
  13. git_project-0.0.44/tests/test_parsermanager.py +202 -0
  14. git_project-0.0.43/tests/test_parsermanager.py +0 -52
  15. {git_project-0.0.43 → git_project-0.0.44}/.gitignore +0 -0
  16. {git_project-0.0.43 → git_project-0.0.44}/CONTRIBUTORS +0 -0
  17. {git_project-0.0.43 → git_project-0.0.44}/COPYING +0 -0
  18. {git_project-0.0.43 → git_project-0.0.44}/MANIFEST.in +0 -0
  19. {git_project-0.0.43 → git_project-0.0.44}/docs/Makefile +0 -0
  20. {git_project-0.0.43 → git_project-0.0.44}/docs/api.rst +0 -0
  21. {git_project-0.0.43 → git_project-0.0.44}/docs/authors.rst +0 -0
  22. {git_project-0.0.43 → git_project-0.0.44}/docs/conf.py +0 -0
  23. {git_project-0.0.43 → git_project-0.0.44}/docs/index.rst +0 -0
  24. {git_project-0.0.43 → git_project-0.0.44}/docs/intro.rst +0 -0
  25. {git_project-0.0.43 → git_project-0.0.44}/docs/license.rst +0 -0
  26. {git_project-0.0.43 → git_project-0.0.44}/docs/make.bat +0 -0
  27. {git_project-0.0.43 → git_project-0.0.44}/docs/plugins.rst +0 -0
  28. {git_project-0.0.43 → git_project-0.0.44}/pyproject.toml +0 -0
  29. {git_project-0.0.43 → git_project-0.0.44}/requirements.txt +0 -0
  30. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/commandline.py +0 -0
  31. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/exception.py +0 -0
  32. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/gitproject.py +0 -0
  33. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/main.py +0 -0
  34. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/plugin.py +0 -0
  35. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/pluginmanager.py +0 -0
  36. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/project.py +0 -0
  37. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/py.typed +0 -0
  38. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/runnable.py +0 -0
  39. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/scopedobj.py +0 -0
  40. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/shell.py +0 -0
  41. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/substitutable.py +0 -0
  42. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/test_support/__init__.py +0 -0
  43. {git_project-0.0.43 → git_project-0.0.44}/src/git_project/test_support/common.py +0 -0
  44. {git_project-0.0.43 → git_project-0.0.44}/tests/conftest.py +0 -0
  45. {git_project-0.0.43 → git_project-0.0.44}/tests/test_git.py +0 -0
  46. {git_project-0.0.43 → git_project-0.0.44}/tests/test_gitproject.py +0 -0
  47. {git_project-0.0.43 → git_project-0.0.44}/tests/test_main.py +0 -0
  48. {git_project-0.0.43 → git_project-0.0.44}/tests/test_project.py +0 -0
  49. {git_project-0.0.43 → git_project-0.0.44}/tests/test_runnable.py +0 -0
  50. {git_project-0.0.43 → git_project-0.0.44}/tests/test_scopedobj.py +0 -0
  51. {git_project-0.0.43 → git_project-0.0.44}/tests/test_shell.py +0 -0
  52. {git_project-0.0.43 → git_project-0.0.44}/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.43
3
+ Version: 0.0.44
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
@@ -169,7 +169,10 @@ core plugins installed ``git <project> help <command>`` shows a command's
169
169
  full manual.
170
170
 
171
171
  ``--menu`` lists a command's subcommands, arguments and options in a form meant
172
- for tools.
172
+ for tools. ``--menu=json`` prints them as one JSON object and adds each
173
+ subcommand's aliases and each argument's ``nargs`` and ``choices``. The
174
+ ``version`` field changes only when a key is removed or changes meaning, so a
175
+ reader should ignore keys it does not know.
173
176
 
174
177
  License
175
178
  =======
@@ -214,28 +217,37 @@ Authors
214
217
  .. _David Greene: https://github.com/greened
215
218
 
216
219
 
217
- `0.0.43`_ - 2026-10-07
220
+ `0.0.44`_ - 2026-10-13
218
221
  ----------------------
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.
222
+ Added
223
+ .....
224
+ - ``--menu=json`` prints the menu as one JSON object with a ``version`` field.
225
+ Unlike the text form, it lists each subcommand's aliases and each argument's
226
+ ``nargs`` and ``choices``.
226
227
 
227
- Removed
228
+ Changed
228
229
  .......
229
- - ``Git.LsRemotesCallbacks`` and ``Git.RemoteBranchDeleteCallback`` are
230
- gone, because no git-project method uses them.
230
+ - ``--menu`` takes only ``text`` or ``json``. A command name after it is now an
231
+ error, where it used to be ignored. Put ``--menu`` after the command, as in
232
+ ``git <project> worktree --menu``.
231
233
 
232
234
  Fixed
233
235
  .....
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
236
+ - Loading a config object no longer writes the values it loaded into the
237
+ repository's local config. Every command loads the project this way, so a
238
+ single-valued key set in the project's section of the global or system config
239
+ was copied into the local config on each run, even by a command that changes
240
+ nothing. Removing a key that has no value in the local config no longer fails.
241
+ Any value it has in another config file, such as the global or system config,
242
+ stays in place.
243
+ - ``--menu`` now reports whether an option takes a value from the action
244
+ argparse builds for it. An option added with ``action="append"``,
245
+ ``action="extend"`` or a custom action class and no ``nargs`` was listed
246
+ as taking no value, and one with a custom action and ``nargs=0`` as taking
247
+ one.
248
+
249
+ .. _Unreleased: https://github.com/greened/git-project/compare/v0.0.44...HEAD
250
+ .. _0.0.44: https://github.com/greened/git-project/compare/v0.0.43...v0.0.44
239
251
  .. _0.0.43: https://github.com/greened/git-project/compare/v0.0.42...v0.0.43
240
252
  .. _0.0.42: https://github.com/greened/git-project/compare/v0.0.41...v0.0.42
241
253
  .. _0.0.41: https://github.com/greened/git-project/compare/v0.0.40...v0.0.41
@@ -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.43'
22
- __version_tuple__ = version_tuple = (0, 0, 43)
21
+ __version__ = version = '0.0.44'
22
+ __version_tuple__ = version_tuple = (0, 0, 44)
23
23
 
24
24
  __commit_id__ = commit_id = None
@@ -0,0 +1,35 @@
1
+ ..
2
+ SPDX-FileCopyrightText: 2026-present David A. Greene <dag@obbligato.org>
3
+
4
+ ..
5
+ SPDX-License-Identifier: AGPL-3.0-or-later
6
+
7
+ ..
8
+ Copyright 2026 David A. Greene
9
+
10
+ ..
11
+ This file is part of git-project
12
+
13
+ ..
14
+ git-project is free software: you can redistribute it and/or modify it under
15
+ the terms of the GNU Affero General Public License as published by the Free
16
+ Software Foundation, either version 3 of the License, or (at your option)
17
+ any later version.
18
+
19
+ ..
20
+ This program is distributed in the hope that it will be useful, but WITHOUT
21
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
22
+ FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
23
+ for more details.
24
+
25
+ ..
26
+ You should have received a copy of the GNU Affero General Public License
27
+ along with git-project. If not, see <https://www.gnu.org/licenses/>.
28
+
29
+ Each file here other than this one is one entry for the next release's
30
+ changelog, named ``<slug>.<category>.rst``, where the category is
31
+ ``added``, ``changed``, ``deprecated``, ``removed``, ``fixed`` or
32
+ ``security``. An entry is plain RST with no Sphinx roles, and a link
33
+ takes the anonymous inline form ```text <URL>`__``. At a release, ``changelog.py``
34
+ moves the entries into ``docs/changelog.rst`` and removes their files.
35
+ See the Changelog section of ``docs/contributing.rst``.
@@ -0,0 +1,531 @@
1
+ #!/usr/bin/env python3
2
+ #
3
+ # SPDX-FileCopyrightText: 2026-present David A. Greene <dag@obbligato.org>
4
+
5
+ # SPDX-License-Identifier: AGPL-3.0-or-later
6
+
7
+ # Copyright 2026 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
+ """Write the docs/changelog.rst section for a release from the fragments
25
+ in changelog.d.
26
+
27
+ Usage: ./changelog.py --version X.Y.Z [--stdout]
28
+
29
+ Each fragment is one entry, in a file named ``<slug>.<category>.rst``.
30
+ The slug is lower case letters, digits and hyphens, starting with a
31
+ letter or digit. The category is ``added``, ``changed``, ``deprecated``,
32
+ ``removed``, ``fixed`` or ``security``, and README.rst is not a
33
+ fragment. Each entry becomes one bullet. Its line breaks are kept, its
34
+ lines are indented under the bullet, and blank lines before and after it
35
+ are dropped.
36
+
37
+ A fragment is plain docutils RST, with no Sphinx roles, because
38
+ git-project's newest section becomes its PyPI description, which plain
39
+ docutils renders. A link takes the anonymous inline form ```text <URL>`__``.
40
+
41
+ The section goes below the empty ``Unreleased`` section, headed
42
+ ```X.Y.Z`_ - DATE``. DATE is today, or the UTC date of
43
+ ``SOURCE_DATE_EPOCH`` when that is set. Its subsections follow Keep a
44
+ Changelog order, and an empty one is left out. Within each, the bullets
45
+ are sorted by slug, comparing the numbers in a slug as numbers. The
46
+ ``X.Y.Z`` link target goes below the ``Unreleased`` one, which then
47
+ compares from ``vX.Y.Z``. Existing entries are not touched. It then runs
48
+ ``git rm`` on the fragments, so the changelog and their removal form one
49
+ change to review. Edit the result, land the change on the main branch
50
+ and tag that commit ``vX.Y.Z``.
51
+
52
+ When docutils is importable, it parses each bullet as a document of its
53
+ own, so an unknown role or a reference to a target the bullet does not
54
+ define is refused. It warns when docutils is not importable, so the
55
+ bullets go unchecked. It refuses, and changes nothing, when:
56
+
57
+ - the version is not ``X.Y.Z`` with no leading zeros, or its tag
58
+ ``vX.Y.Z`` exists
59
+ - ``SOURCE_DATE_EPOCH`` is set and is not only digits
60
+ - a ``vN.N.N`` tag is merged into HEAD and the version is not greater
61
+ than the highest one. Pre-release tags such as ``v1.2.0rc1`` do not
62
+ count.
63
+ - changelog.d holds no fragment
64
+ - a file in changelog.d other than README.rst is not a regular file,
65
+ does not match the name, or has an unknown category
66
+ - a fragment is empty or is not UTF-8, or its first line starts with a
67
+ ``-``, ``*`` or ``+`` bullet, which would nest a list
68
+ - docutils reports a warning or an error in a bullet
69
+ - a fragment is untracked or has uncommitted changes. ``git rm`` would
70
+ lose it, or the entry would not be what landed.
71
+ - the file does not exist, is untracked or has uncommitted changes
72
+ - the file has no ``Unreleased`` heading or more than one, or no
73
+ ``.. _Unreleased:`` compare target or more than one
74
+ - ``Unreleased`` has entries of its own. They would be lost or
75
+ duplicated.
76
+ - a link target comes before the end of the ``Unreleased`` section
77
+ - the file already has an ``X.Y.Z`` link target
78
+ - docutils reports a warning or an error in the updated file, as when
79
+ two entries define the same target name
80
+
81
+ A refusal about fragments lists every file at fault. With ``--stdout``
82
+ it prints the section, removes nothing, and skips the check that the
83
+ fragments are tracked and clean, and the checks on the file, the last
84
+ six above. The others still apply.
85
+
86
+ When ``git rm`` fails after the file is written, it prints the commands
87
+ that finish the release or undo it.
88
+ """
89
+
90
+ # The file has no per-repository constants, so git-project and
91
+ # git-project-core-plugins carry the same copy. The URL comes from the
92
+ # file's own Unreleased link target.
93
+
94
+ from __future__ import annotations
95
+
96
+ import argparse
97
+ import os
98
+ import re
99
+ import stat
100
+ import subprocess
101
+ import sys
102
+ import tempfile
103
+ import textwrap
104
+ import time
105
+ from collections.abc import Callable
106
+ from pathlib import Path
107
+
108
+ ROOT = Path(__file__).resolve().parent
109
+ FILE = Path("docs") / "changelog.rst"
110
+ FRAGMENTS = "changelog.d"
111
+ README = "README.rst"
112
+ # Keep a Changelog order, by the name a fragment's file uses.
113
+ CATEGORIES = {
114
+ "added": "Added",
115
+ "changed": "Changed",
116
+ "deprecated": "Deprecated",
117
+ "removed": "Removed",
118
+ "fixed": "Fixed",
119
+ "security": "Security",
120
+ }
121
+
122
+ FRAGMENT = re.compile(r"([a-z0-9][a-z0-9-]*)\.([^.]+)\.rst")
123
+ PART = "(0|[1-9][0-9]*)"
124
+ VERSION = re.compile(rf"{PART}\.{PART}\.{PART}")
125
+ TAG = re.compile(r"v([0-9]+)\.([0-9]+)\.([0-9]+)")
126
+ RELEASE = re.compile(r"^`[0-9]+\.[0-9]+\.[0-9]+`_ - ", re.MULTILINE)
127
+ UNRELEASED = re.compile(r"^`Unreleased`_\n([^\w\s])\1*\n", re.MULTILINE)
128
+ UNRELEASED_TARGET = re.compile(
129
+ r"^\.\. _Unreleased: (\S+)/compare/(\S+)\.\.\.HEAD\n", re.MULTILINE
130
+ )
131
+ ANY_UNRELEASED_TARGET = re.compile(r"^\.\. _Unreleased:", re.MULTILINE)
132
+ LINK_TARGET = re.compile(r"^\.\. _", re.MULTILINE)
133
+ SUBSECTION = re.compile(
134
+ r"^(?:Added|Changed|Deprecated|Removed|Fixed|Security)\n([^\w\s])\1*$",
135
+ re.MULTILINE,
136
+ )
137
+
138
+
139
+ class RefusalError(Exception):
140
+ def __init__(self, message: str, listing: str = "") -> None:
141
+ super().__init__(message)
142
+ self.listing = listing
143
+
144
+
145
+ def git(*args: str) -> str:
146
+ result = subprocess.run(
147
+ ["git", "-C", str(ROOT), *args],
148
+ capture_output=True,
149
+ text=True,
150
+ encoding="utf-8",
151
+ check=False,
152
+ )
153
+ if result.returncode != 0:
154
+ raise RefusalError(f"git {args[0]} failed: {result.stderr.strip()}")
155
+ return result.stdout
156
+
157
+
158
+ def succeeds(*args: str) -> bool:
159
+ result = subprocess.run(
160
+ ["git", "-C", str(ROOT), *args], capture_output=True, check=False
161
+ )
162
+ return result.returncode == 0
163
+
164
+
165
+ def warn(message: str) -> None:
166
+ print(f"changelog.py: warning: {message}", file=sys.stderr)
167
+
168
+
169
+ def numbers(match: re.Match[str]) -> tuple[int, ...]:
170
+ return tuple(int(n) for n in match.groups())
171
+
172
+
173
+ def newest_tag() -> re.Match[str] | None:
174
+ matches = [
175
+ TAG.fullmatch(t) for t in git("tag", "--merged", "HEAD").split()
176
+ ]
177
+ tags = [m for m in matches if m is not None]
178
+ if not tags:
179
+ return None
180
+ return max(tags, key=numbers)
181
+
182
+
183
+ def rst_checker() -> Callable[[str], list[str]] | None:
184
+ """Return a function that lists what docutils reports in an entry,
185
+ or None when docutils is not importable.
186
+
187
+ """
188
+ try:
189
+ from docutils import frontend
190
+ from docutils.parsers.rst import Parser
191
+ from docutils.readers.standalone import Reader
192
+ from docutils.utils import new_document
193
+ except ImportError:
194
+ return None
195
+
196
+ if hasattr(frontend, "get_default_settings"):
197
+ settings = frontend.get_default_settings(Parser, Reader)
198
+ else:
199
+ # Older docutils, as a distribution's python3 may carry.
200
+ option_parser = frontend.OptionParser(components=(Parser, Reader))
201
+ settings = option_parser.get_default_values()
202
+ # Collect the messages through the observer, not on stderr.
203
+ settings.report_level = 5
204
+ settings.halt_level = 5
205
+
206
+ def problems(text: str) -> list[str]:
207
+ document = new_document("<entry>", settings)
208
+ messages: list = []
209
+ document.reporter.attach_observer(messages.append)
210
+ parser = Parser()
211
+ parser.parse(text, document)
212
+ # The transforms report an unknown target, which the entry must
213
+ # define itself because the PyPI description is rendered alone.
214
+ document.transformer.populate_from_components(
215
+ (Reader(parser=parser), parser)
216
+ )
217
+ document.transformer.apply_transforms()
218
+ return [
219
+ (
220
+ f"line {m['line']}: {m.children[0].astext()}"
221
+ if m.get("line")
222
+ else m.children[0].astext()
223
+ )
224
+ for m in messages
225
+ if m["level"] >= 2
226
+ ]
227
+
228
+ return problems
229
+
230
+
231
+ def bullet(text: str) -> str:
232
+ """Return TEXT as one bullet, or "" when it has no text."""
233
+ lines = [line.rstrip() for line in textwrap.dedent(text).splitlines()]
234
+ while lines and not lines[0]:
235
+ lines.pop(0)
236
+ while lines and not lines[-1]:
237
+ lines.pop()
238
+ if not lines:
239
+ return ""
240
+ rest = [f" {line}" if line else "" for line in lines[1:]]
241
+ return "\n".join([f"- {lines[0]}", *rest])
242
+
243
+
244
+ def unclean() -> list[str]:
245
+ """Return a problem for each fragment that git does not have as it
246
+ is on disk, deleted ones included.
247
+
248
+ """
249
+ output = git(
250
+ "status",
251
+ "--porcelain",
252
+ "-z",
253
+ "--no-renames",
254
+ "--untracked-files=all",
255
+ "--ignored",
256
+ "--",
257
+ FRAGMENTS,
258
+ )
259
+ problems = []
260
+ for record in output.split("\0"):
261
+ code, path = record[:2], record[3:]
262
+ if not record or path == f"{FRAGMENTS}/{README}":
263
+ continue
264
+ if code in ("??", "!!"):
265
+ problems.append(f"{path}: it is untracked")
266
+ else:
267
+ problems.append(f"{path}: it has uncommitted changes")
268
+ return problems
269
+
270
+
271
+ def natural(path: Path) -> tuple[list[str | int], str]:
272
+ """Return a sort key for PATH's slug that compares its numbers as
273
+ numbers.
274
+
275
+ """
276
+ parts = re.split(r"([0-9]+)", path.name.split(".")[0])
277
+ return [int(p) if p.isdigit() else p for p in parts], path.name
278
+
279
+
280
+ def fragments(
281
+ clean: bool, check: Callable[[str], list[str]] | None
282
+ ) -> tuple[dict[str, list[str]], list[str]]:
283
+ """Return the bullets by subsection and the fragments' paths. CHECK
284
+ lists an entry's RST problems, and None skips it. With CLEAN, also
285
+ refuse a fragment that is untracked or changed.
286
+
287
+ """
288
+ directory = ROOT / FRAGMENTS
289
+ found: dict[str, list[str]] = {c: [] for c in CATEGORIES.values()}
290
+ paths: list[str] = []
291
+ problems: list[str] = []
292
+ # Within a subsection the files share a suffix, so the slug orders
293
+ # them, and "x-2" sorts before "x-10".
294
+ entries = sorted(
295
+ directory.iterdir() if directory.is_dir() else [], key=natural
296
+ )
297
+ for entry in entries:
298
+ if entry.name == README:
299
+ continue
300
+ path = f"{FRAGMENTS}/{entry.name}"
301
+ match = FRAGMENT.fullmatch(entry.name)
302
+ if match is None:
303
+ problems.append(f"{path}: the name is not <slug>.<category>.rst")
304
+ continue
305
+ name = CATEGORIES.get(match.group(2))
306
+ if name is None:
307
+ problems.append(
308
+ f"{path}: {match.group(2)} is not one of "
309
+ f"{', '.join(CATEGORIES)}"
310
+ )
311
+ continue
312
+ if entry.is_symlink() or not entry.is_file():
313
+ problems.append(f"{path}: it is not a regular file")
314
+ continue
315
+ try:
316
+ # An editor's byte order mark would land mid-file.
317
+ item = bullet(entry.read_text(encoding="utf-8-sig"))
318
+ except UnicodeDecodeError:
319
+ problems.append(f"{path}: it is not UTF-8")
320
+ continue
321
+ if not item:
322
+ problems.append(f"{path}: it is empty")
323
+ continue
324
+ if item.startswith(("- - ", "- * ", "- + ")):
325
+ problems.append(f"{path}: it starts with a bullet of its own")
326
+ continue
327
+ rst = check(item) if check else []
328
+ if rst:
329
+ problems.append(f"{path}: it is not valid RST: {' '.join(rst)}")
330
+ found[name].append(item)
331
+ paths.append(path)
332
+ if clean:
333
+ problems += unclean()
334
+ if problems:
335
+ raise RefusalError(
336
+ f"the files above in {FRAGMENTS} need fixing first",
337
+ "".join(f" {p}\n" for p in problems),
338
+ )
339
+ if not paths:
340
+ raise RefusalError(f"{FRAGMENTS} holds no fragment")
341
+ return found, paths
342
+
343
+
344
+ def release_date() -> str:
345
+ epoch = os.environ.get("SOURCE_DATE_EPOCH")
346
+ if epoch is None:
347
+ return time.strftime("%Y-%m-%d")
348
+ try:
349
+ # int() would also take a sign, spaces and underscores.
350
+ if not re.fullmatch("[0-9]+", epoch):
351
+ raise ValueError
352
+ return time.strftime("%Y-%m-%d", time.gmtime(int(epoch)))
353
+ except (ValueError, OverflowError, OSError):
354
+ raise RefusalError(
355
+ f"SOURCE_DATE_EPOCH is not a time in seconds: {epoch}"
356
+ ) from None
357
+
358
+
359
+ def section(
360
+ version: str,
361
+ found: dict[str, list[str]],
362
+ date: str,
363
+ heading: str,
364
+ sub: str,
365
+ ) -> str:
366
+ title = f"`{version}`_ - {date}"
367
+ parts = []
368
+ for name in CATEGORIES.values():
369
+ if found[name]:
370
+ bullets = "".join(b + "\n" for b in found[name])
371
+ parts.append(f"{name}\n{sub * len(name)}\n{bullets}")
372
+ return f"{title}\n{heading * len(title)}\n" + "\n".join(parts)
373
+
374
+
375
+ def underlines(text: str) -> tuple[str, str]:
376
+ heading = UNRELEASED.search(text)
377
+ sub = SUBSECTION.search(text)
378
+ return heading.group(1) if heading else "-", sub.group(1) if sub else "."
379
+
380
+
381
+ def insert(text: str, version: str, new: str) -> str:
382
+ headings = list(UNRELEASED.finditer(text))
383
+ if not headings:
384
+ raise RefusalError(f"{FILE} has no `Unreleased`_ heading")
385
+ if len(headings) > 1:
386
+ raise RefusalError(f"{FILE} has more than one `Unreleased`_ heading")
387
+ if len(ANY_UNRELEASED_TARGET.findall(text)) > 1:
388
+ raise RefusalError(
389
+ f"{FILE} has more than one `.. _Unreleased:` target"
390
+ )
391
+ target = UNRELEASED_TARGET.search(text)
392
+ if target is None:
393
+ raise RefusalError(f"{FILE} has no `.. _Unreleased:` compare target")
394
+
395
+ start = headings[0].end()
396
+ rest = RELEASE.search(text, start)
397
+ if rest is not None:
398
+ end = rest.start()
399
+ else:
400
+ after = LINK_TARGET.search(text, start)
401
+ end = after.start() if after else len(text)
402
+ first = LINK_TARGET.search(text)
403
+ if first is not None and first.start() < end:
404
+ # The splices below assume every target follows the section.
405
+ raise RefusalError(
406
+ f"{FILE} has a link target before the end of Unreleased, so "
407
+ "move it below the releases first"
408
+ )
409
+ if text[start:end].strip():
410
+ raise RefusalError(
411
+ f"Unreleased has entries of its own, so move them into "
412
+ f"{FRAGMENTS} first"
413
+ )
414
+ if re.search(rf"^\.\. _{re.escape(version)}:", text, re.MULTILINE):
415
+ raise RefusalError(f"{FILE} already has a {version} link target")
416
+
417
+ url, previous = target.groups()
418
+ links = (
419
+ f".. _Unreleased: {url}/compare/v{version}...HEAD\n"
420
+ f".. _{version}: {url}/compare/{previous}...v{version}\n"
421
+ )
422
+ text = text[: target.start()] + links + text[target.end() :]
423
+ # The link targets follow the section, so its offsets still hold.
424
+ return text[:start] + "\n" + new + "\n" + text[end:]
425
+
426
+
427
+ def write(path: Path, text: str) -> None:
428
+ mode = stat.S_IMODE(path.stat().st_mode)
429
+ # Next to the file, so the rename is atomic on its file system.
430
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
431
+ try:
432
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as out:
433
+ out.write(text)
434
+ # mkstemp makes the file private, and the changelog is not.
435
+ os.chmod(tmp, mode)
436
+ os.replace(tmp, path)
437
+ except BaseException:
438
+ os.unlink(tmp)
439
+ raise
440
+
441
+
442
+ def run(argv: list[str]) -> str:
443
+ parser = argparse.ArgumentParser(
444
+ prog="changelog.py",
445
+ description="Write the changelog section for a release.",
446
+ )
447
+ parser.add_argument(
448
+ "--version",
449
+ required=True,
450
+ metavar="X.Y.Z",
451
+ help="the version being released, whose tag must not exist yet",
452
+ )
453
+ parser.add_argument(
454
+ "--stdout",
455
+ action="store_true",
456
+ help="print the new section and change nothing",
457
+ )
458
+ args = parser.parse_args(argv)
459
+ version = args.version
460
+
461
+ wanted = VERSION.fullmatch(version)
462
+ if wanted is None:
463
+ raise RefusalError(f"not a version X.Y.Z: {version}")
464
+ if succeeds("rev-parse", "--verify", "--quiet", f"refs/tags/v{version}"):
465
+ raise RefusalError(f"tag v{version} already exists")
466
+ date = release_date()
467
+ tag = newest_tag()
468
+ if tag is not None and numbers(wanted) <= numbers(tag):
469
+ raise RefusalError(f"{version} is not greater than {tag.group(0)}")
470
+
471
+ path = ROOT / FILE
472
+ if not args.stdout:
473
+ if not path.exists():
474
+ raise RefusalError(f"{FILE} does not exist")
475
+ if not succeeds("ls-files", "--error-unmatch", "--", str(FILE)):
476
+ raise RefusalError(f"{FILE} is untracked, so commit it first")
477
+ if not succeeds("diff", "--quiet", "HEAD", "--", str(FILE)):
478
+ raise RefusalError(
479
+ f"{FILE} has uncommitted changes, so commit or drop them "
480
+ "first"
481
+ )
482
+
483
+ check = rst_checker()
484
+ if check is None:
485
+ warn("docutils is not importable, so the entries are not checked")
486
+ found, paths = fragments(not args.stdout, check)
487
+
488
+ text = path.read_text(encoding="utf-8") if path.exists() else ""
489
+ heading, sub = underlines(text)
490
+ new = section(version, found, date, heading, sub)
491
+ if args.stdout:
492
+ return new
493
+ updated = insert(text, version, new)
494
+ # Each entry parses alone, but two entries can still clash, as two
495
+ # that define the same target name do.
496
+ clashes = check(updated) if check is not None else []
497
+ if clashes:
498
+ raise RefusalError(
499
+ f"the updated {FILE} does not parse cleanly:\n "
500
+ + "\n ".join(clashes)
501
+ )
502
+ write(path, updated)
503
+ try:
504
+ git("rm", "-q", "--", *paths)
505
+ except RefusalError as error:
506
+ raise RefusalError(
507
+ f"wrote {FILE}, but {error}\n"
508
+ f"Finish the release with:\n"
509
+ f" git rm -q -- {' '.join(paths)}\n"
510
+ f"or undo it with:\n"
511
+ f" git checkout -- {FILE}"
512
+ ) from None
513
+ entries = "entry" if len(paths) == 1 else "entries"
514
+ return (
515
+ f"changelog.py: wrote {version} with {len(paths)} {entries} to "
516
+ f"{FILE} and removed their fragments\n"
517
+ )
518
+
519
+
520
+ def main() -> int:
521
+ try:
522
+ sys.stdout.write(run(sys.argv[1:]))
523
+ except RefusalError as refusal:
524
+ sys.stderr.write(refusal.listing)
525
+ print(f"changelog.py: {refusal}", file=sys.stderr)
526
+ return 1
527
+ return 0
528
+
529
+
530
+ if __name__ == "__main__":
531
+ sys.exit(main())