-
Notifications
You must be signed in to change notification settings - Fork 543
Expand file tree
/
Copy pathcut-release.py
More file actions
225 lines (184 loc) · 6.36 KB
/
Copy pathcut-release.py
File metadata and controls
225 lines (184 loc) · 6.36 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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#!/usr/bin/env python
import argparse
import os
import pathlib
import re
import sys
from datetime import datetime
import requests
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent.parent.parent
class ClassPropertyDescriptor:
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return ClassPropertyDescriptor(func)
class Session:
_instance = None
def __init__(self, endpoint=None):
if endpoint is None:
endpoint = "https://api.github.com"
self.endpoint = endpoint
self.session = requests.Session()
self.session.headers.update(
{
"Accept": "application/vnd.github+json",
"Authorization": f"token {os.environ['GITHUB_TOKEN']}",
}
)
@classproperty
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def get(self, path, **kwargs):
return self.session.get(f"{self.endpoint}/{path.lstrip('/')}", **kwargs)
def post(self, path, **kwargs):
return self.session.post(f"{self.endpoint}/{path.lstrip('/')}", **kwargs)
def __enter__(self):
self.session.__enter__()
return self
def __exit__(self, *args):
self.session.__exit__(*args)
def get_latest_release(options):
response = Session.instance.get(f"/repos/{options.repo}/releases/latest")
if response.status_code != 404:
return response.json()["tag_name"]
print(
f"Failed to get latest release. HTTP Response:\n{response.text}",
file=sys.stderr,
flush=True,
)
print("Searching tags...", file=sys.stderr, flush=True)
tags = []
page = 0
while True:
page += 1
response = Session.instance.get(
f"/repos/{options.repo}/tags", data={"pre_page": 100, "page": page}
)
repo_tags = response.json()
added_tags = False
for tag in repo_tags:
if tag["name"] not in tags:
tags.append(tag["name"])
added_tags = True
if added_tags is False:
break
return list(sorted(tags))[-1]
def get_generated_changelog(options):
response = Session.instance.post(
f"/repos/{options.repo}/releases/generate-notes",
json={
"tag_name": options.release_tag,
"previous_tag_name": options.previous_tag,
"target_commitish": "develop",
},
)
if response.status_code == 200:
return response.json()
return response.text
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--repo", required=True, help="The <user>/<repo> to use")
parser.add_argument("--release-tag", required=False, help="The tag of the release")
parser.add_argument(
"--previous-tag",
required=False,
help="The previous release tag. If not passed, the GH Api will be queried for it.",
)
changelog_file = REPO_ROOT / "CHANGELOG.md"
if not os.environ.get("GITHUB_TOKEN"):
parser.exit(status=1, message="GITHUB_TOKEN environment variable not set")
options = parser.parse_args()
if not options.release_tag:
options.release_tag = f"v{datetime.utcnow().strftime('%Y.%m.%d')}"
if not options.previous_tag:
options.previous_tag = get_latest_release(options)
print(
f"Creating changelog entries from {options.previous_tag} to {options.release_tag} ...",
file=sys.stderr,
flush=True,
)
changelog = get_generated_changelog(options)
if not isinstance(changelog, dict):
parser.exit(
status=1,
message=f"Unable to generate changelog. HTTP Response:\n{changelog}",
)
github_output = os.environ.get("GITHUB_OUTPUT")
cut_release_version = REPO_ROOT / ".cut_release_version"
print(
f"* Writing {cut_release_version.relative_to(REPO_ROOT)} ...",
file=sys.stderr,
flush=True,
)
cut_release_version.write_text(options.release_tag)
if github_output is not None:
with open(github_output, "a", encoding="utf-8") as wfh:
wfh.write(f"release-version={options.release_tag}\n")
cut_release_changes = REPO_ROOT / ".cut_release_changes"
print(
f"* Writing {cut_release_changes.relative_to(REPO_ROOT)} ...",
file=sys.stderr,
flush=True,
)
cut_release_changes.write_text(changelog["body"])
print(
f"* Updating {changelog_file.relative_to(REPO_ROOT)} ...",
file=sys.stderr,
flush=True,
)
changelog_file.write_text(
f"# {changelog['name']}\n\n"
+ changelog["body"]
+ "\n\n"
+ changelog_file.read_text()
)
# Update Script Version for the bash script
bootstrap_script_path = REPO_ROOT / "bootstrap-salt.sh"
print(
f"* Updating {bootstrap_script_path.relative_to(REPO_ROOT)} ...",
file=sys.stderr,
flush=True,
)
bootstrap_script_path.write_text(
re.sub(
r'__ScriptVersion="(.*)"',
f'__ScriptVersion="{options.release_tag.lstrip("v")}"',
bootstrap_script_path.read_text(),
)
)
# Update the Script Version for the powershell script
bootstrap_script_path = REPO_ROOT / "bootstrap-salt.ps1"
print(
f"* Updating {bootstrap_script_path.relative_to(REPO_ROOT)} ...",
file=sys.stderr,
flush=True,
)
bootstrap_script_path.write_text(
re.sub(
r'\$__ScriptVersion = "(.*)"',
f'$__ScriptVersion = "{options.release_tag.lstrip("v")}"',
bootstrap_script_path.read_text(),
)
)
parser.exit(status=0, message="CHANGELOG.md and bootstrap-salt.sh updated\n")
if __name__ == "__main__":
main()