-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_version.py
308 lines (266 loc) · 10.9 KB
/
generate_version.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import sys
import os
import subprocess
from pathlib import Path
from typing import Any
from contextlib import suppress, closing
try:
from packaging.version import parse as parse_version
except ImportError:
from setuptools._vendor.packaging.version import parse as parse_version
here = Path(os.path.dirname(os.path.abspath(__file__)))
VERSION_FILE = os.path.join(here, "instruct/about.py")
current_sha = ""
if (here / ".git").exists():
with suppress(FileNotFoundError):
with open(here / ".git" / "HEAD") as fh:
head_reference = fh.read().strip()
if head_reference.startswith("ref: "):
ref_val = head_reference[len("ref: ") :]
with open(here / ".git" / ref_val) as fh:
current_sha = fh.read().strip()
else:
current_sha = head_reference
with suppress(FileNotFoundError):
via_git_rev_parse = subprocess.check_output(("git", "rev-parse", "HEAD")).strip().decode()
assert (
via_git_rev_parse == current_sha
), f"rev parse: {via_git_rev_parse!r} != {current_sha!r}"
def quote(s: Any) -> str:
if not isinstance(s, str):
return repr(s).replace("'", '"')
return f'"{s}"'
def write_about_and_emit_version(version="", filename_or_stream: str = VERSION_FILE):
if not version:
with open(os.path.join(here, "CURRENT_VERSION.txt")) as fh:
for line in fh:
if line.strip().startswith("#"):
continue
version = line.strip()
break
else:
fh.seek(0)
raise LookupError(f"Cannot find a version inside file! It has {fh.read()!r}")
full_version = version
if current_sha:
full_version = f"{version}+git.{current_sha}"
parsed_version = parse_version(full_version)
if filename_or_stream == "-":
stream = sys.stderr
elif isinstance(filename_or_stream, str):
stream = open(filename_or_stream, "w")
elif hasattr(filename_or_stream, "write"):
stream = filename_or_stream
else:
raise TypeError(filename_or_stream)
prerelease_version = repr(parsed_version.pre).replace("'", '"')
with closing(stream) as fh:
fh.write(
f"""# Autogenerated from `attr: generate_version.write_about_and_emit_version`
# it is run on setup.py/pip installs!
from __future__ import annotations
import typing
from contextlib import suppress
from functools import total_ordering
if typing.TYPE_CHECKING:
from typing import Optional, Tuple, Union, Type, Never, Any, Self
def _parse_local(local_version: Optional[str]) -> Tuple[Union[int, str], ...]:
if local_version:
if not local_version[0].isalnum():
raise ValueError("local versions must start with an ascii letter or digit")
if not local_version[-1].isalnum():
raise ValueError("local versions must end with an ascii letter or digit")
return tuple(
map((lambda val: int(val, 10) if val.isdigit() else val), local_version.split("."))
)
return ()
@total_ordering
class VersionInfo:
__slots__ = ("major", "minor", "micro", "pre", "post", "local", "_parsed_local")
major: int
minor: int
micro: int
pre: Optional[Tuple[str, int]]
post: Optional[int]
local: Optional[str]
_parsed_local: Union[Tuple[()], Tuple[Union[str, int], ...]]
def __new__(cls: Type[Self], major=0, minor=0, micro=0, pre=None, post=None, local=None):
if pre and post:
raise ValueError("pre and post may not be specified simultaneously!")
self = super().__new__(cls)
object.__setattr__(self, "major", major)
object.__setattr__(self, "minor", minor)
object.__setattr__(self, "micro", micro)
object.__setattr__(self, "pre", pre)
object.__setattr__(self, "post", post)
object.__setattr__(self, "local", local)
object.__setattr__(self, "_parsed_local", _parse_local(local))
return self
def keys(self: Self) -> Tuple[str, ...]:
return type(self).__slots__[:-1]
def __repr__(self: Self) -> str:
vals = ", ".join(
f"{{name}}={{val!r}}" for name, val in zip(type(self).__slots__[:-1], self._astuple())
)
return f"{{type(self).__name__}}({{vals}})"
def __setattr__(self, name: str, value: Any) -> Never:
raise AttributeError(name)
def __reduce__(self: Self):
return type(self), self._astuple()
def __getitem__(self: Self, key: Union[int, slice, str]):
if isinstance(key, (slice, int)):
return self._astuple().__getitem__(key)
return self._asdict().__getitem__(key)
def __iter__(self: Self):
return iter(self._astuple())
def _astuple(self: Self):
return (self.major, self.minor, self.micro, self.pre, self.post, self.local)
def _asdict(self: Self):
return {{attr: value for attr, value in zip(type(self).__slots__[:-1], self._astuple())}}
def __hash__(self: Self) -> int:
return hash((type(self), *self._astuple()))
@classmethod
def from_tuple(cls: Type[Self], version: tuple) -> Self:
defaults = (0, 0, 0, None, None, None)
diff = len(version) - len(defaults)
if diff < 0:
version = (*version, *defaults[diff:])
elif diff > 0:
raise ValueError(
f"{{cls.__name__}} expects at most {{len(cls.__slots__)}} "
f"elements (Encountered {{len(version)}} fields)"
) from None
for index, part in enumerate(version[:3]):
if not isinstance(part, int):
raise TypeError(f"Expected integer at index {{index}}")
pre, post, local = version[-3:]
pre = pre or None
local = local or None
if pre is not None:
if not isinstance(pre, tuple):
raise TypeError("pre must be a tuple!")
if len(pre) == 1:
pre = (*pre, 0)
try:
prerelease_phase, pre_ordinal = pre
except ValueError:
raise TypeError(f"pre may not exceed 2 elements (currently {{len(pre)}} elements)")
if not isinstance(prerelease_phase, str):
raise TypeError(
"prerelease phase is expected to be a string, "
f"not a {{type(prerelease_phase).__name__}}"
)
with suppress(KeyError):
prerelease_phase = {{"alpha": "a", "beta": "b", "c": "rc", "preview": "rc"}}[
prerelease_phase.lower()
]
if prerelease_phase not in ("a", "b", "rc"):
raise ValueError(f"Unknown prerelease phase: {{prerelease_phase!r}}")
if not isinstance(pre_ordinal, int):
raise TypeError("prerelease ordinal must be a non-negative integer")
elif pre_ordinal < 0:
raise ValueError("prerelease ordinal must be a non-negative integer")
elif post is not None:
if not isinstance(post, int):
raise TypeError("post release ordinal must be a non-negative integer")
elif post < 0:
raise ValueError("post release ordinal must be a non-negative integer")
if local is not None:
if not isinstance(local, str):
raise TypeError("local version segments must be a string")
local = local.lower().translate({{ord("-"): ord("."), ord("_"): ord(".")}})
return cls(*(*version[:3], pre, post, local))
def __lt__(self: Self, other: Any) -> bool:
cls = type(self)
with suppress(AttributeError, TypeError):
if isinstance(other, tuple) and not isinstance(other, cls):
other = cls.from_tuple(other)
try:
other_local = other._parsed_local
except AttributeError:
other_local = _parse_local(other.local)
return (
self.major,
self.minor,
self.micro,
self.pre if self.pre is not None else ("{{", 0),
self.post if self.post is not None else float("inf"),
self._parsed_local,
) < (
other.major,
other.minor,
other.micro,
other.pre if other.pre is not None else ("{{", 0),
other.post if other.post is not None else float("inf"),
other_local,
)
return NotImplemented
def __eq__(self: Self, other: Any) -> bool:
cls = type(self)
with suppress(AttributeError, TypeError):
if isinstance(other, tuple) and not isinstance(other, cls):
other = cls.from_tuple(other)
try:
other_local = other._parsed_local
except AttributeError:
other_local = _parse_local(other.local)
return (
self.major,
self.minor,
self.micro,
self.pre,
self.post,
self._parsed_local,
) == (
other.major,
other.minor,
other.micro,
other.pre,
other.post,
other_local,
)
return NotImplemented
@property
def release(self: Self) -> Tuple[int, int, int]:
return self[:3]
@property
def base_version(self: Self) -> str:
return f"{{self.major}}.{{self.minor}}.{{self.micro}}"
@property
def public(self: Self) -> str:
value = f"{{self.major}}.{{self.minor}}.{{self.micro}}"
if self.pre is not None:
value = f"{{value}}{{self.pre[0]}}{{self.pre[1]}}"
if self.post is not None:
value = f"{{value}}post{{self.post}}"
return value
def __str__(self: Self) -> str:
value = f"{{self.major}}.{{self.minor}}.{{self.micro}}"
if self.pre is not None:
value = f"{{value}}{{self.pre[0]}}{{self.pre[1]}}"
if self.post is not None:
value = f"{{value}}post{{self.post}}"
if self.local:
local_v = ".".join(str(part) for part in self._parsed_local)
value = f"{{value}}+{{local_v}}"
return value
__version__: str = "{full_version}"
__version_info__: VersionInfo = VersionInfo(
{parsed_version.major!r},
{parsed_version.minor!r},
{parsed_version.micro!r},
{quote(parsed_version.pre) if parsed_version.pre else None},
{parsed_version.post!r},
{quote(parsed_version.local) if parsed_version.local else None},
)
__commit__: Optional[str] = {quote(parsed_version.local) or None}
"""
)
return version
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filename", default="-", nargs="?")
parser.add_argument("version", default="", nargs="?")
args = parser.parse_args()
write_about_and_emit_version(args.version, args.filename)