-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-tag
More file actions
executable file
·147 lines (117 loc) · 4.11 KB
/
Copy pathgit-tag
File metadata and controls
executable file
·147 lines (117 loc) · 4.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env python3
"""Create an annotated release tag and push to origin (see --help)."""
from __future__ import annotations
import argparse
import re
import subprocess
import sys
_SEMVER_TAG = re.compile(r"^v(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)$")
def _run_git(args: list[str], **kwargs) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", *args],
check=True,
capture_output=True,
text=True,
**kwargs,
)
def _git_ok(args: list[str]) -> bool:
r = subprocess.run(["git", *args], capture_output=True)
return r.returncode == 0
def _latest_semver_tag() -> str | None:
r = subprocess.run(
["git", "tag", "-l", "v*", "--sort=-v:refname"],
capture_output=True,
text=True,
check=True,
)
for line in r.stdout.splitlines():
tag = line.strip()
if tag and _SEMVER_TAG.fullmatch(tag):
return tag
return None
def _parse_semver_tag(tag: str) -> tuple[int, int, int]:
m = _SEMVER_TAG.fullmatch(tag)
if not m:
raise ValueError(f"tag {tag!r} is not semver vMAJOR.MINOR.PATCH")
return int(m["major"]), int(m["minor"]), int(m["patch"])
def _format_semver_tag(major: int, minor: int, patch: int) -> str:
return f"v{major}.{minor}.{patch}"
def _bump_semver_tag(tag: str | None, level: str) -> str:
if tag is None:
if level == "patch":
return "v0.0.1"
if level == "minor":
return "v0.1.0"
return "v1.0.0"
major, minor, patch = _parse_semver_tag(tag)
if level == "patch":
return _format_semver_tag(major, minor, patch + 1)
if level == "minor":
return _format_semver_tag(major, minor + 1, 0)
return _format_semver_tag(major + 1, 0, 0)
def _resolve_tag(tag: str | None, bump: str | None) -> str:
if bump is not None:
latest = _latest_semver_tag()
new_tag = _bump_semver_tag(latest, bump)
if latest is None:
print(f"No existing semver tags; using {new_tag}")
else:
print(f"Bumping {latest} ({bump}) -> {new_tag}")
return new_tag
assert tag is not None
_parse_semver_tag(tag)
return tag
def main() -> int:
p = argparse.ArgumentParser(
description=(
"Create an annotated tag at HEAD with message 'Release TAG', "
"then push to origin. Refuses if the working tree is dirty or the tag exists. "
"If push fails after the tag was created, remove the local tag "
"(`git tag -d TAG`) or push again when the network is healthy."
)
)
g = p.add_mutually_exclusive_group(required=True)
g.add_argument("tag", nargs="?", help="explicit tag, e.g. v1.2.0")
g.add_argument(
"--bump",
choices=("patch", "minor", "major"),
help="compute next semver tag from the latest vMAJOR.MINOR.PATCH tag",
)
p.add_argument(
"--no-push",
action="store_true",
help="only create the tag locally",
)
args = p.parse_args()
if not _git_ok(["rev-parse", "--is-inside-work-tree"]):
print("Error: not inside a Git repository", file=sys.stderr)
return 1
try:
tag = _resolve_tag(args.tag, args.bump)
except ValueError as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
if _git_ok(["show-ref", "--verify", "--quiet", f"refs/tags/{tag}"]):
print(f"Error: tag {tag!r} already exists", file=sys.stderr)
return 1
st = subprocess.run(
["git", "status", "--porcelain"],
check=True,
capture_output=True,
text=True,
)
if st.stdout.strip():
print(
"Error: working tree is not clean; commit or stash before tagging",
file=sys.stderr,
)
return 1
_run_git(["tag", "-a", tag, "-m", f"Release {tag}"])
short = _run_git(["rev-parse", "--short", "HEAD"]).stdout.strip()
print(f"Created annotated tag {tag} at {short}")
if not args.no_push:
_run_git(["push", "origin", tag])
print(f"Pushed {tag} to origin")
return 0
if __name__ == "__main__":
sys.exit(main())