-
Notifications
You must be signed in to change notification settings - Fork 2
/
add-new-versions.py
executable file
·242 lines (175 loc) · 6.38 KB
/
add-new-versions.py
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/env python
import argparse
import base64
import http
import json
import os
import re
import subprocess
import sys
from functools import lru_cache
from urllib.request import Request
from urllib.request import urlopen
from typing import Any
from typing import NamedTuple
from typing import Optional
import jinja2
VERSION_RE = re.compile("^v?(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<patch>[0-9]+)$")
OS = {"darwin", "linux", "windows"}
ARCH = {"x86_64", "arm64"}
TEMPLATES_DIR = "templates"
REPO = "hadolint/hadolint"
MIRROR_REPO = "AleksaC/hadolint-py"
MIN_VERSION = "v2.10.0"
class Version(NamedTuple):
major: int
minor: int
patch: int
@classmethod
def from_string(cls, version: str) -> "Version":
if match := re.match(VERSION_RE, version):
return cls(*map(int, match.groups()))
raise ValueError("Invalid version", version)
def __repr__(self):
return f"{self.major}.{self.minor}.{self.patch}"
def __lte__(self, other: "Version") -> bool:
if self.major != other.major:
return self.major < other.major
elif self.minor != other.minor:
return self.minor < other.minor
else:
return self.patch <= other.patch
class Template(NamedTuple):
src: str
dest: str
vars: dict[str, Any]
def _get(
url: str, headers: Optional[dict[str, str]] = None
) -> http.client.HTTPResponse:
if headers is None:
headers = {}
req = Request(url, headers=headers)
resp = urlopen(req, timeout=30)
return resp
def get_json(url: str, headers: Optional[dict[str, str]] = None) -> dict:
return json.loads(_get(url, headers).read())
def get_text(url: str, headers: Optional[dict[str, str]] = None) -> str:
return _get(url, headers).read().decode()
def git(*args: str) -> None:
subprocess.run(["git", *args], check=True)
@lru_cache
def get_gh_auth_headers():
gh_token = os.environ["GH_TOKEN"]
auth = base64.b64encode(f"AleksaC:{gh_token}".encode()).decode()
return {
"Accept": "application/vnd.github.v3+json",
"Authorization": f"Basic {auth}",
}
def get_versions(
repo: str, *, from_releases: bool = True, min_version: Optional[Version] = None
) -> list[Version]:
base_url = "https://api.github.com/repos/{}/{}?per_page=100&page={}"
versions: list[Version] = []
page = 1
while releases_page := get_json(
base_url.format(repo, "releases" if from_releases else "tags", page),
headers=get_gh_auth_headers(),
):
for release in releases_page:
if from_releases and (release["draft"] or release["prerelease"]):
continue
tag_name = release["tag_name"] if from_releases else release["name"]
try:
version = Version.from_string(tag_name)
except ValueError as e:
print(f"Could not parse version: {tag_name}")
print(e)
else:
if min_version and version < min_version:
return versions
versions.append(version)
page += 1
return versions
def get_missing_versions(
repo: str, mirror_repo: str, min_version: Optional[Version] = None
) -> list[Version]:
versions = get_versions(repo, min_version=min_version)
mirrored = get_versions(mirror_repo, from_releases=False, min_version=min_version)
missing = []
for new in reversed(versions):
for existing in mirrored:
if new == existing:
break
else:
missing.append(new)
return missing
def get_archives(repo: str, version: Version) -> dict[str, tuple[str, str]]:
release_url = f"https://api.github.com/repos/{repo}/releases/tags/v{version}"
release = get_json(release_url, headers=get_gh_auth_headers())
checksums, binaries = {}, {}
for file in release["assets"]:
file_name = file["name"]
if file["name"].endswith(".sha256"):
checksums[file_name] = file["browser_download_url"]
else:
binaries[file_name] = file["browser_download_url"]
archives = {}
for checksum_name, checksum_url in checksums.items():
sha, binary_name = (
get_text(checksum_url, headers=get_gh_auth_headers()).strip().split()
)
if binary_name.startswith("*"):
binary_name = binary_name[1:]
if not checksum_name.startswith(binary_name):
raise AssertionError
archive = (binaries[binary_name], sha)
_, os, arch = (
binary_name[:-4].split("-")
if binary_name.endswith(".exe")
else binary_name.split("-")
)
os_normalized, arch_normalized = os.lower(), arch.lower()
if os_normalized not in OS or arch_normalized not in ARCH:
raise ValueError("Unsupported plaform!", os, arch)
archives[f"{os_normalized}-{arch_normalized}"] = archive
return archives
def render_templates(templates: list[Template]) -> None:
for src, dest, vars in templates:
with open(os.path.join(TEMPLATES_DIR, src)) as f:
template_file = f.read()
template = jinja2.Template(template_file, keep_trailing_newline=True)
with open(dest, "w") as f:
f.write(template.render(**vars))
def tag_version(version: str) -> None:
git("add", "-u")
git("commit", "-m", f"Add version {version}")
git("tag", version)
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("--push", default=False, action="store_true")
args = parser.parse_args(argv)
versions = get_missing_versions(REPO, MIRROR_REPO, Version.from_string(MIN_VERSION))
for version in versions:
print(f"Adding new version: v{version}")
archives = get_archives(REPO, version)
render_templates(
[
Template(
src="setup.py.j2",
dest="setup.py",
vars={"hadolint_version": str(version), "archives": str(archives)},
),
Template(
src="README.md.j2",
dest="README.md",
vars={"hadolint_version": str(version)},
),
]
)
tag_version(f"v{version}")
if args.push:
git("push")
git("push", "--tags")
return 0
if __name__ == "__main__":
sys.exit(main())