git-tag-release 0.4.8__py3-none-any.whl

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.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-tag-release
3
+ Version: 0.4.8
4
+ Summary: Automate creation of semantic versioning tags
5
+ Author-email: Egor Tensin <egor@tensin.name>
6
+ License-Expression: MIT
7
+ Project-URL: homepage, https://github.com/egor-tensin/tag-release
8
+ Project-URL: issues, https://github.com/egor-tensin/tag-release/issues
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Requires-Python: >=3.8
12
+ License-File: LICENSE.txt
13
+ Dynamic: license-file
@@ -0,0 +1,7 @@
1
+ release.py,sha256=mKCnHKMWuixKemmWGoD26EWdALRSvo4DhcLdNY-Kbdc,12725
2
+ git_tag_release-0.4.8.dist-info/licenses/LICENSE.txt,sha256=4YpWKsGDOu9riW55uz0lXxEPGNI_u9oDtsHQ6BVdc0w,1087
3
+ git_tag_release-0.4.8.dist-info/METADATA,sha256=zHukaPfxYr1xPRFiy8oTvV1rtDufGX36o7n-51BGJzE,478
4
+ git_tag_release-0.4.8.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ git_tag_release-0.4.8.dist-info/entry_points.txt,sha256=RP_rxkzJy2zRVh_jYU5Mfuyqfu3KKmjsn2sCqAA6LcM,45
6
+ git_tag_release-0.4.8.dist-info/top_level.txt,sha256=OTPjJ0tj3AH9KG1tk5piaGfIOkYD_ENH4Pi4hW8bmP0,8
7
+ git_tag_release-0.4.8.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tag-release = release:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Egor Tensin <egor@tensin.name>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ release
release.py ADDED
@@ -0,0 +1,424 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) 2026 Egor Tensin <egor@tensin.name>
4
+ # This file is part of the "tag-release" project.
5
+ # For details, see https://github.com/egor-tensin/tag-release
6
+ # Distributed under the MIT License.
7
+
8
+ R"""
9
+ This script automates the creation of git tags in accordance with the semantic
10
+ versioning policy. It follows the convention of tags being in the MAJOR.MINOR.PATCH
11
+ format (with an optional prefix - "v" by default). You can then use it to bump
12
+ either of the major/minor/patch version numbers, and it will take care of
13
+ creating the proper tag for you.
14
+ """
15
+
16
+ import argparse
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass
19
+ from enum import Enum
20
+ import logging
21
+ import os
22
+ import re
23
+ import shlex
24
+ import subprocess
25
+ import sys
26
+
27
+
28
+ @contextmanager
29
+ def setup_logging(verbose=False):
30
+ level_names = {
31
+ logging.DEBUG: "DBG",
32
+ logging.INFO: "INFO",
33
+ logging.WARNING: "WARN",
34
+ logging.ERROR: "ERR",
35
+ logging.CRITICAL: "CRIT",
36
+ }
37
+ for lvl, name in level_names.items():
38
+ logging.addLevelName(lvl, name)
39
+
40
+ logging.basicConfig(
41
+ datefmt="%Y-%m-%d %H:%M:%S%z",
42
+ format="%(asctime)s | %(levelname)4s | %(message)s",
43
+ level=logging.DEBUG if verbose else logging.INFO,
44
+ stream=sys.stdout,
45
+ )
46
+ try:
47
+ yield
48
+ except Exception as e:
49
+ logging.exception(e)
50
+ sys.exit(1)
51
+
52
+
53
+ def _run_log_output(level, output):
54
+ if not output:
55
+ logging.log(level, "... No output")
56
+ return
57
+ logging.log(level, "Output (%d characters):", len(output))
58
+ for line in output.splitlines():
59
+ logging.log(level, " %s", line)
60
+
61
+
62
+ def run(*args, **kwargs):
63
+ stdout = subprocess.PIPE
64
+ stderr = subprocess.STDOUT
65
+
66
+ logging.info("Running: %s", shlex.join(args))
67
+ try:
68
+ result = subprocess.run(
69
+ args, check=True, stdout=stdout, stderr=stderr, encoding="utf-8", **kwargs
70
+ )
71
+ except subprocess.CalledProcessError as e:
72
+ logging.error("... Returned exit code %d", e.returncode)
73
+ _run_log_output(logging.ERROR, e.output)
74
+ raise
75
+
76
+ _run_log_output(logging.DEBUG, result.stdout)
77
+ return result.stdout
78
+
79
+
80
+ def go_to_repo(repo_dir=None):
81
+ if repo_dir is not None:
82
+ os.chdir(repo_dir)
83
+ try:
84
+ run(*["git", "rev-parse", "--is-inside-work-tree"])
85
+ except subprocess.CalledProcessError as e:
86
+ logging.error("%s doesn't seem to be a git working directory", os.getcwd())
87
+ raise
88
+
89
+
90
+ class ReleaseScope(Enum):
91
+ MAJOR = "major"
92
+ MINOR = "minor"
93
+ PATCH = "patch"
94
+
95
+ def __str__(self):
96
+ return self.value
97
+
98
+ def next_version(self, version):
99
+ version = version.extend(len(ReleaseScope))
100
+ version = version.upgrade(self._index)
101
+ return version
102
+
103
+ @property
104
+ def _index(self):
105
+ if self is ReleaseScope.MAJOR:
106
+ return 0
107
+ if self is ReleaseScope.MINOR:
108
+ return 1
109
+ if self is ReleaseScope.PATCH:
110
+ return 2
111
+ raise NotImplementedError(f"Unknown release scope: {self}")
112
+
113
+
114
+ class Version:
115
+ def __init__(self, nums):
116
+ nums = list(nums)
117
+ if len(nums) > len(ReleaseScope):
118
+ raise ValueError(f"Too many version components: {nums}")
119
+
120
+ while nums and nums[-1] is None:
121
+ nums.pop()
122
+ if not nums:
123
+ raise ValueError("Must provide at least the major version number")
124
+ if any((n is None for n in nums)):
125
+ raise ValueError(f"Some version components are invalid: {nums}")
126
+
127
+ self._nums = tuple(nums)
128
+
129
+ @staticmethod
130
+ def parse(src, strict=False):
131
+ invalid_msg = f"Invalid version: {src}"
132
+
133
+ match = re.fullmatch(r"(\d+)(?:\.(\d+)(?:\.(\d+))?)?", src)
134
+ if not match:
135
+ if strict:
136
+ raise ValueError(invalid_msg)
137
+ logging.warning("%s", invalid_msg)
138
+ return None
139
+ assert len(match.groups()) == 3
140
+
141
+ nums = [int(n) if n is not None else None for n in match.groups()]
142
+ return Version(nums)
143
+
144
+ def __str__(self):
145
+ return ".".join(map(str, self._nums))
146
+
147
+ def __eq__(self, other):
148
+ return self._nums == other._nums
149
+
150
+ def __lt__(self, other):
151
+ # Attempting to sort the way `sort -V` does it (so v1 < v1.0 for example).
152
+ for a, b in zip(self._nums, other._nums):
153
+ if a > b:
154
+ return False
155
+ if a < b:
156
+ return True
157
+ return len(self._nums) < len(other._nums)
158
+
159
+ def __hash__(self):
160
+ return hash(self._nums)
161
+
162
+ def extend(self, new_len):
163
+ if new_len < 1 or new_len > len(ReleaseScope):
164
+ raise ValueError(f"Invalid version length {new_len}")
165
+ if len(self._nums) >= new_len:
166
+ return Version(self._nums)
167
+ nums = list(self._nums)
168
+ nums.extend([0 for i in range(new_len - len(self._nums))])
169
+ return Version(nums)
170
+
171
+ def upgrade(self, idx):
172
+ assert idx < len(ReleaseScope)
173
+ if idx < 0 or len(self._nums) < idx + 1:
174
+ raise ValueError(
175
+ f"Can't increment version number at index {idx} for version {self}"
176
+ )
177
+ nums = list(self._nums[:idx])
178
+ nums.append(self._nums[idx] + 1)
179
+ nums.extend([0 for i in range(len(self._nums) - idx - 1)])
180
+ return Version(nums)
181
+
182
+ @property
183
+ def has_parent(self):
184
+ return len(self._nums) > 1
185
+
186
+ def get_parent(self):
187
+ return Version(self._nums[:-1])
188
+
189
+
190
+ @dataclass
191
+ class Tag:
192
+ name: str
193
+ version: Version
194
+ lightweight: bool
195
+
196
+ def git_cmd_create(self, message=None, target=None):
197
+ cmd = ["git", "tag"]
198
+ if self.lightweight:
199
+ return cmd + [self.name]
200
+ if message is None:
201
+ raise ValueError("Must provide a tag message for annotated tags")
202
+ cmd += ["-a", "-m", message, self.name]
203
+ if target is not None:
204
+ cmd.append(target.name + "^{}")
205
+ # ^^^ Avoid tags-to-tags, which is somehow bad, idk.
206
+ return cmd
207
+
208
+ def git_cmd_update(self, target):
209
+ cmd = ["git", "tag"]
210
+ if self.lightweight:
211
+ return cmd + ["-f", self.name, target.name]
212
+ cmd += ["-a", "-f", self.name]
213
+ cmd.append(target.name + "^{}")
214
+ # ^^^ Avoid tags-to-tags, which is somehow bad, idk.
215
+ return cmd
216
+
217
+
218
+ class TagManager:
219
+ DEFAULT_PREFIX = "v"
220
+ DEFAULT_VERSION = Version((0 for _ in range(len(ReleaseScope))))
221
+ DEFAULT_MESSAGE_FMT = "{}"
222
+
223
+ def __init__(self, prefix=None, strict=False, lightweight=False, message_fmt=None):
224
+ if prefix is None:
225
+ prefix = TagManager.DEFAULT_PREFIX
226
+ self._prefix = prefix
227
+ self._strict = strict
228
+ self._lightweight = lightweight
229
+ if message_fmt is None:
230
+ message_fmt = TagManager.DEFAULT_MESSAGE_FMT
231
+ self._message_fmt = message_fmt
232
+
233
+ tags = self._git_query_tags()
234
+ tags = self._git_filter_tags(tags)
235
+ tags = self._git_parse_tags(tags)
236
+ tags = list(tags)
237
+ if not tags:
238
+ version = TagManager.DEFAULT_VERSION
239
+ tags = [Tag(self._format_tag_name(version), version, lightweight)]
240
+
241
+ self._tag_lst = sorted(tags, key=lambda tag: tag.version)
242
+ self._tag_map = {tag.version: tag for tag in tags}
243
+
244
+ def _format_tag_name(self, version):
245
+ return f"{self._prefix}{version}"
246
+
247
+ @staticmethod
248
+ def _git_query_tags():
249
+ cmd = [
250
+ "git",
251
+ "for-each-ref",
252
+ "--format=%(refname:short) %(objecttype)",
253
+ "refs/tags/",
254
+ ]
255
+
256
+ output = run(*cmd)
257
+ lines = output.splitlines()
258
+
259
+ for line in lines:
260
+ line = line.split()
261
+ assert len(line) == 2
262
+ yield line
263
+
264
+ def _git_filter_tags(self, tags):
265
+ for refname, objecttype in tags:
266
+ if not refname.startswith(self._prefix):
267
+ msg = f"Unexpected tag name: {refname}"
268
+ if self._strict:
269
+ raise RuntimeError(msg)
270
+ logging.warning("%s", msg)
271
+ continue
272
+ yield refname.removeprefix(self._prefix), objecttype
273
+
274
+ @staticmethod
275
+ def _is_tag_lightweight(objecttype):
276
+ if objecttype == "commit":
277
+ return True
278
+ if objecttype == "tag":
279
+ return False
280
+ raise ValueError(f"Unexpected %(objecttype) value: {objecttype}")
281
+
282
+ def _git_parse_tags(self, tags):
283
+ for refname, objecttype in tags:
284
+ version = Version.parse(refname, strict=self._strict)
285
+ if version is None:
286
+ continue
287
+ lightweight = self._is_tag_lightweight(objecttype)
288
+ yield Tag(self._format_tag_name(version), version, lightweight)
289
+
290
+ def __len__(self):
291
+ return len(self._tag_lst)
292
+
293
+ @property
294
+ def latest(self):
295
+ if not self:
296
+ raise RuntimeError("No tags, can't get the latest")
297
+ return self._tag_lst[-1]
298
+
299
+ def create(self, tag, target=None):
300
+ if tag.version in self._tag_map:
301
+ raise RuntimeError(f"Tag {tag.name} already exists")
302
+
303
+ cmd = tag.git_cmd_create(
304
+ message=self._message_fmt.format(tag.name), target=target
305
+ )
306
+ run(*cmd)
307
+
308
+ self._tag_lst.append(tag)
309
+ self._tag_lst.sort(key=lambda tag: tag.version)
310
+ self._tag_map[tag.version] = tag
311
+
312
+ def update(self, parent, child):
313
+ if parent.version not in self._tag_map:
314
+ raise RuntimeError(f"Tag {parent.name} doesn't exist")
315
+ if child.version not in self._tag_map:
316
+ raise RuntimeError(f"Tag {child.name} doesn't exist")
317
+
318
+ cmd = parent.git_cmd_update(child)
319
+ env = os.environ.copy()
320
+ env["GIT_EDITOR"] = "true"
321
+ run(*cmd, env=env)
322
+
323
+ def release_next(self, scope):
324
+ version = scope.next_version(self.latest.version)
325
+ tag = Tag(f"{self._prefix}{version}", version, self._lightweight)
326
+ self.create(tag)
327
+ return tag
328
+
329
+ def retag_parents(self, child):
330
+ while child.version.has_parent:
331
+ parent_version = child.version.get_parent()
332
+ if parent_version in self._tag_map:
333
+ parent = self._tag_map[parent_version]
334
+ self.update(parent, child)
335
+ child = parent
336
+ continue
337
+ parent = Tag(
338
+ self._format_tag_name(parent_version),
339
+ parent_version,
340
+ self._lightweight,
341
+ )
342
+ self.create(parent, target=child)
343
+ child = parent
344
+
345
+
346
+ def parse_args(argv=None):
347
+ if argv is None:
348
+ argv = sys.argv[1:]
349
+
350
+ epilog = R"""
351
+ The tag message (--message) can include Python's str.format() placeholders.
352
+ It will be format()ted with a single argument: the full tag name (for example,
353
+ v1.2.3).
354
+ """
355
+
356
+ parser = argparse.ArgumentParser(description=__doc__, epilog=epilog)
357
+
358
+ parser.add_argument("-v", "--verbose", action="store_true", help="verbose output")
359
+ parser.add_argument(
360
+ "-p",
361
+ "--prefix",
362
+ default=TagManager.DEFAULT_PREFIX,
363
+ metavar="STR",
364
+ help=f"""tag prefix ("{TagManager.DEFAULT_PREFIX}" by default)""",
365
+ )
366
+ parser.add_argument(
367
+ "-s",
368
+ "--strict",
369
+ action="store_true",
370
+ help="error out on discovering malformed tags",
371
+ )
372
+ parser.add_argument(
373
+ "-l",
374
+ "--lightweight",
375
+ action="store_true",
376
+ help="create lightweight tags (annotated by default)",
377
+ )
378
+ parser.add_argument(
379
+ "-m",
380
+ "--message",
381
+ metavar="FMT",
382
+ dest="message_fmt",
383
+ default=TagManager.DEFAULT_MESSAGE_FMT,
384
+ help="tag message format string",
385
+ )
386
+ parser.add_argument(
387
+ "-r",
388
+ "--retag",
389
+ action="store_true",
390
+ help="update parent version tags (i.e. for tag v2.1.1, update tags v2 & v2.1 to point to it)",
391
+ )
392
+ parser.add_argument(
393
+ "release_scope",
394
+ choices=ReleaseScope,
395
+ type=ReleaseScope,
396
+ help="release scope",
397
+ )
398
+ parser.add_argument(
399
+ "repo_dir",
400
+ metavar="DIR",
401
+ nargs="?",
402
+ help="path to repository (working directory by default)",
403
+ )
404
+
405
+ return parser.parse_args(argv)
406
+
407
+
408
+ def main(argv=None):
409
+ args = parse_args(argv)
410
+ with setup_logging(args.verbose):
411
+ go_to_repo(args.repo_dir)
412
+ tags = TagManager(
413
+ prefix=args.prefix,
414
+ strict=args.strict,
415
+ lightweight=args.lightweight,
416
+ message_fmt=args.message_fmt,
417
+ )
418
+ new = tags.release_next(args.release_scope)
419
+ if args.retag:
420
+ tags.retag_parents(new)
421
+
422
+
423
+ if __name__ == "__main__":
424
+ main()