version-bumper 0.1.0__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,456 @@
1
+ # SPDX-FileCopyrightText: 2024 Roy Wright
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ import re
9
+ from collections.abc import Sequence
10
+ from typing import Self
11
+
12
+ """
13
+ A comparable Version object that fully conforms to the PYPA version specification in:
14
+ https://packaging.python.org/en/latest/specifications/version-specifiers/#version-specifiers
15
+
16
+ Usage example:
17
+
18
+ version = Version('1.2.2') # 1.2.2
19
+ version.bump(part=minor") # 1.2.3
20
+ version.bump(part="dev") # 1.2.3.dev1
21
+ version.bump(part="rc") # 1.2.3.rc1
22
+ version.bump(part="dev") # 1.2.3.rc1.dev1
23
+ version.set(part="local", "foo0100") # 1.2.3.rc1.dev1+foo0100
24
+ version.bump(part="local") # 1.2.3.rc1.dev1+foo0101
25
+ version.bump_release() # 1.2.3
26
+ """
27
+
28
+ # functools.total_ordering
29
+ # Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest.
30
+ # This simplifies the effort involved in specifying all the possible rich comparison operations:
31
+ #
32
+ # The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply
33
+ # an __eq__() method.
34
+
35
+
36
+ @functools.total_ordering
37
+ class Version:
38
+ # Constants
39
+ PARTS: Sequence[str] = ("epoch", "major", "minor", "patch", "a", "b", "rc", "post", "dev", "local")
40
+ PARSED_PARTS: Sequence[str] = ("epoch", "major", "minor", "patch", "pre", "post", "dev", "local")
41
+ PRE_PARTS: Sequence[str] = ("a", "b", "c", "rc", "alpha", "beta", "pre", "preview")
42
+ POST_PARTS: Sequence[str] = ("r", "rev", "post")
43
+ INT_PARTS: Sequence[str] = ("epoch", "major", "minor", "patch")
44
+
45
+ # This version parsing regex is from:
46
+ # https://packaging.python.org/en/latest/specifications/version-specifiers/#appendix-parsing-version-strings-with-regular-expressions
47
+ VERSION_PATTERN = r"""
48
+ v?
49
+ (?:
50
+ (?:(?P<epoch>[0-9]+)!)? # epoch
51
+ (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
52
+ (?P<pre> # pre-release
53
+ [-_\.]?
54
+ (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
55
+ [-_\.]?
56
+ (?P<pre_n>[0-9]+)?
57
+ )?
58
+ (?P<post> # post release
59
+ (?:-(?P<post_n1>[0-9]+))
60
+ |
61
+ (?:
62
+ [-_\.]?
63
+ (?P<post_l>post|rev|r)
64
+ [-_\.]?
65
+ (?P<post_n2>[0-9]+)?
66
+ )
67
+ )?
68
+ (?P<dev> # dev release
69
+ [-_\.]?
70
+ (?P<dev_l>dev)
71
+ [-_\.]?
72
+ (?P<dev_n>[0-9]+)?
73
+ )?
74
+ )
75
+ (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
76
+ """
77
+
78
+ def __init__(self, version_str: str) -> None:
79
+ """
80
+ Parse the version string into normalized parts in the Version instance.
81
+ """
82
+ # Case sensitivity
83
+ # All ascii letters should be interpreted case insensitively within a version and the normal
84
+ # form is lowercase. This allows versions such as 1.1RC1 which would be normalized to 1.1rc1.
85
+ #
86
+ # Leading and Trailing Whitespace
87
+ # Leading and trailing whitespace must be silently ignored and removed from all normalized forms of
88
+ # a version. This includes " ", \t, \n, \r, \f, and \v. This allows accidental whitespace to be
89
+ # handled sensibly, such as a version like 1.0\n which normalizes to 1.0.
90
+ #
91
+ # Preceding v character
92
+ # In order to support the common version notation of v1.0 versions may be preceded by a single
93
+ # literal v character. This character MUST be ignored for all purposes and should be omitted
94
+ # from all normalized forms of the version. The same version with and without the v is considered
95
+ # equivalent.
96
+ self.version_str = version_str.lower().strip("\t\n\r\f\v").lstrip("v")
97
+
98
+ # parse the version string using the PYPA regex
99
+ _regex = re.compile(
100
+ r"^\s*" + Version.VERSION_PATTERN + r"\s*$",
101
+ re.VERBOSE | re.IGNORECASE,
102
+ )
103
+ match = _regex.match(self.version_str)
104
+ if match is None:
105
+ msg = f"Invalid version string: {self.version_str}"
106
+ raise ValueError(msg)
107
+
108
+ # normalize the parts
109
+ self.epoch: int = int(match.group("epoch") or 0)
110
+ self.release: str = match.group("release")
111
+ release_parts: Sequence[int] = tuple(map(int, self.release.split(".")))
112
+ self.major: int = (
113
+ Version.__release_normalize(release_parts=release_parts, index=0, length=1, default_value=0) or 0
114
+ )
115
+ self.minor: int | None = Version.__release_normalize(
116
+ release_parts=release_parts, index=1, length=2, default_value=None
117
+ )
118
+ self.patch: int | None = Version.__release_normalize(
119
+ release_parts=release_parts, index=2, length=3, default_value=None
120
+ )
121
+ self.pre: str = Version.__pre_normalize(match.group("pre"))
122
+ self.post: str = Version.__post_normalize(match.group("post"))
123
+ self.dev: str = Version.__dev_normalize(match.group("dev"))
124
+ self.local: str = Version.__local_normalize(match.group("local"))
125
+
126
+ def __str__(self) -> str:
127
+ """
128
+ Convert from the version parts into a version string.
129
+ """
130
+ version_parts = []
131
+ if int(self.epoch) > 0:
132
+ version_parts.append(f"{self.epoch}!")
133
+ version_parts.append(str(self.major))
134
+ if self.minor is not None:
135
+ version_parts.append(f".{self.minor}")
136
+ if self.patch is not None:
137
+ version_parts.append(f".{self.patch}")
138
+ version_parts.append(self.pre)
139
+ version_parts.append(self.post)
140
+ version_parts.append(self.dev)
141
+ if self.local:
142
+ version_parts.append(f"+{self.local}")
143
+ return "".join([str(v) for v in version_parts])
144
+
145
+ def __lt__(self, other: Self) -> bool:
146
+ """test if self is less than other"""
147
+
148
+ # note, testing order is critical
149
+ if self.epoch < other.epoch:
150
+ return True
151
+ if self.major < other.major:
152
+ return True
153
+ if Version.__is_optional_value_less_than(self.minor, other.minor):
154
+ return True
155
+ if Version.__is_optional_value_less_than(self.patch, other.patch):
156
+ return True
157
+ if self.pre < other.pre:
158
+ return True
159
+ if self.post < other.post:
160
+ return True
161
+ if self.dev < other.dev:
162
+ return True
163
+ return self.local < other.local
164
+
165
+ def __eq__(self, other: object) -> bool:
166
+ """test if self is equal to other"""
167
+ return str(self) == str(other)
168
+
169
+ def bump(self, part: str) -> Self:
170
+ """Increment the given part of the version.
171
+ Valid part values are in PARTS sequence.
172
+ Bump the part if part is not None.
173
+ Set the value to new_version if it is not None.
174
+ return the Version instance.
175
+ """
176
+ if part not in Version.PARTS:
177
+ msg = f"Invalid part value: {part}"
178
+ raise ValueError(msg)
179
+
180
+ self.epoch = Version.__bump_int_part(part=part, prefix="epoch", value=self.epoch) or 0
181
+ self.major = Version.__bump_int_part(part=part, prefix="major", value=self.major) or 0
182
+ self.minor = Version.__bump_int_part(part=part, prefix="minor", value=self.minor)
183
+ if part == "patch":
184
+ self.minor = int(self.minor or 0)
185
+ self.patch = Version.__bump_int_part(part=part, prefix="patch", value=self.patch)
186
+ self.pre = Version.__bump_part(part=part, prefix="a", value=self.pre)
187
+ self.pre = Version.__bump_part(part=part, prefix="b", value=self.pre)
188
+ self.pre = Version.__bump_part(part=part, prefix="rc", value=self.pre)
189
+ self.post = Version.__bump_part(part=part, prefix=".post", value=self.post)
190
+ self.dev = Version.__bump_part(part=part, prefix=".dev", value=self.dev)
191
+ self.local = Version.__bump_local(part=part, value=self.local)
192
+
193
+ # clear parts to the right of the bumped part, except epoch
194
+ if part != "epoch":
195
+ part_index = Version.PARSED_PARTS.index(Version.__part_to_parsed_part(part))
196
+ self.__clear_parts(Version.PARSED_PARTS[part_index + 1 :])
197
+
198
+ return self
199
+
200
+ def bump_release(self) -> Self:
201
+ """
202
+ Remove any pre, post, dev, or local parts. Basically prepare the release version.
203
+ returns the Version instance.
204
+ """
205
+ self.__clear_parts(["pre", "post", "dev", "local"])
206
+ return self
207
+
208
+ def set(self, part: str, value: str, clear_right: bool = False) -> Self:
209
+ """
210
+ Normalize the value then replace the part's value with it.
211
+ returns the Version instance.
212
+ """
213
+ if part in Version.PARTS:
214
+ if part in Version.PRE_PARTS:
215
+ value = f"{part}{value}"
216
+ part = "pre"
217
+ setattr(self, part, Version.__pre_normalize(value))
218
+ elif part in Version.POST_PARTS:
219
+ part = "post"
220
+ setattr(self, part, Version.__post_normalize(value))
221
+ elif part == "local":
222
+ setattr(self, part, Version.__local_normalize(value))
223
+ elif part == "dev":
224
+ setattr(self, part, Version.__dev_normalize(value))
225
+ else: # all that's left are the integer parts: epoch, major, minor, and patch
226
+ setattr(self, part, int(value))
227
+ if clear_right:
228
+ parts_to_clear_slice = slice(Version.PARSED_PARTS.index(part) + 1, None)
229
+ self.__clear_parts(Version.PARSED_PARTS[parts_to_clear_slice])
230
+ return self
231
+
232
+ # The following static methods are just basically functions scoped within the class
233
+ # Having them as static methods allows private naming convention instead of protected.
234
+ # Also, I use the convention of Classname.__methodname instead of the allowable
235
+ # self.__methodname to visually indicate a static method.
236
+
237
+ @staticmethod
238
+ def __part_to_parsed_part(part: str) -> str:
239
+ """
240
+ The pre and post parts have aliases (a, b, rc, alpha,...). If the given part is an
241
+ alias, replace it with the base part (pre or post).
242
+ """
243
+ if part in Version.PRE_PARTS:
244
+ part = "pre"
245
+ elif part in Version.POST_PARTS:
246
+ part = "post"
247
+ return part
248
+
249
+ @staticmethod
250
+ def __implicit_release(release: str) -> str:
251
+ """
252
+ Implicit pre-release number
253
+ Pre releases allow omitting the numeral in which case it is implicitly assumed to be 0. The normal
254
+ form for this is to include the 0 explicitly. This allows versions such as 1.2a which is normalized
255
+ to 1.2a0.
256
+ """
257
+ match = re.match(r"(.*\D)(\d+)$", release)
258
+ if match:
259
+ prefix = match.group(1)
260
+ value = int(match.group(2))
261
+ release = f"{prefix}{value}"
262
+ else:
263
+ release = f"{release}0"
264
+ return release
265
+
266
+ @staticmethod
267
+ def __prefix_normalize(release: str, prefix: str) -> str:
268
+ """
269
+ Prefix (pre, post, and dev) parts need to be of the form "{prefix}N".
270
+ When release is N, make it "{prefix}N".
271
+ """
272
+ if all(characters.isdigit() for characters in release):
273
+ release = f"{prefix}{release}"
274
+ return release
275
+
276
+ @staticmethod
277
+ def __release_normalize(
278
+ release_parts: Sequence[int], index: int, length: int, default_value: int | None
279
+ ) -> int | None:
280
+ """
281
+ Release (major, minor, patch) parts are integers with the minor and patch parts being optional.
282
+ """
283
+ return release_parts[index] if len(release_parts) >= length else default_value
284
+
285
+ @staticmethod
286
+ def __pre_normalize(release: str) -> str:
287
+ """
288
+ Pre-release separators
289
+ Pre-releases should allow a ., -, or _ separator between the release segment and the pre-release
290
+ segment. The normal form for this is without a separator. This allows versions such as 1.1.a1
291
+ or 1.1-a1 which would be normalized to 1.1a1. It should also allow a separator to be used
292
+ between the pre-release signifier and the numeral. This allows versions such as 1.0a.1 which
293
+ would be normalized to 1.0a1.
294
+
295
+ Pre-release spelling
296
+ Pre-releases allow the additional spellings of alpha, beta, c, pre, and preview for a, b, rc, rc,
297
+ and rc respectively. This allows versions such as 1.1alpha1, 1.1beta2, or 1.1c3 which normalize
298
+ to 1.1a1, 1.1b2, and 1.1rc3. In every case the additional spelling should be considered
299
+ equivalent to their normal forms.
300
+
301
+ Implicit pre-release number
302
+ Pre releases allow omitting the numeral in which case it is implicitly assumed to be 0. The normal
303
+ form for this is to include the 0 explicitly. This allows versions such as 1.2a which is normalized to 1.2a0.
304
+ """
305
+ release = release or ""
306
+ if release:
307
+ release = release.replace(".", "")
308
+ release = release.replace("-", "")
309
+ release = release.replace("_", "")
310
+ release = release.replace("alpha", "a")
311
+ release = release.replace("beta", "b")
312
+ release = release.replace("c", "rc") if release.startswith("c") else release
313
+ release = release.replace("preview", "rc")
314
+ release = release.replace("pre", "rc")
315
+ release = Version.__prefix_normalize(release=release, prefix="pre")
316
+ release = Version.__implicit_release(release)
317
+ return release
318
+
319
+ @staticmethod
320
+ def __post_normalize(release: str) -> str:
321
+ """
322
+ Post release separators
323
+ Post releases allow a ., -, or _ separator as well as omitting the separator all together.
324
+ The normal form of this is with the . separator. This allows versions such as 1.2-post2 or
325
+ 1.2post2 which normalize to 1.2.post2. Like the pre-release separator this also allows an
326
+ optional separator between the post release signifier and the numeral. This allows versions
327
+ like 1.2.post-2 which would normalize to 1.2.post2.
328
+
329
+ Post release spelling
330
+ Post-releases allow the additional spellings of rev and r. This allows versions such as 1.0-r4
331
+ which normalizes to 1.0.post4. As with the pre-releases the additional spellings should be
332
+ considered equivalent to their normal forms.
333
+
334
+ Implicit post release number
335
+ Post releases allow omitting the numeral in which case it is implicitly assumed to be 0. The
336
+ normal form for this is to include the 0 explicitly. This allows versions such as 1.2.post
337
+ which is normalized to 1.2.post0.
338
+ """
339
+ release = release or ""
340
+ if release:
341
+ if re.match(r"^[.\-_]", release):
342
+ release = release[1:]
343
+ release = release.replace(".", "")
344
+ release = release.replace("-", "")
345
+ release = release.replace("_", "")
346
+ release = release.replace("rev", "post")
347
+ release = release.replace("r", "post")
348
+ release = Version.__prefix_normalize(release=release, prefix="post")
349
+ release = Version.__implicit_release(release)
350
+ release = f".{release}"
351
+ return release
352
+
353
+ @staticmethod
354
+ def __dev_normalize(release: str) -> str:
355
+ """
356
+ Development release separators
357
+ Development releases allow a ., -, or a _ separator as well as omitting the separator all together.
358
+ The normal form of this is with the . separator. This allows versions such as 1.2-dev2 or 1.2dev2
359
+ which normalize to 1.2.dev2.
360
+
361
+ Implicit development release number
362
+ Development releases allow omitting the numeral in which case it is implicitly assumed to be 0.
363
+ The normal form for this is to include the 0 explicitly. This allows versions such as 1.2.dev
364
+ which is normalized to 1.2.dev0.
365
+ """
366
+ release = release or ""
367
+ if release:
368
+ if re.match(r"^[.\-_]", release):
369
+ release = release[1:]
370
+ release = release.replace(".", "")
371
+ release = release.replace("-", "")
372
+ release = release.replace("_", "")
373
+ release = Version.__prefix_normalize(release=release, prefix="dev")
374
+ release = Version.__implicit_release(release)
375
+ release = f".{release}"
376
+ return release
377
+
378
+ @staticmethod
379
+ def __local_normalize(release: str) -> str:
380
+ """
381
+ Local version segments
382
+ With a local version, in addition to the use of . as a separator of segments, the use of - and _ is
383
+ also acceptable. The normal form is using the . character. This allows versions such as
384
+ 1.0+ubuntu-1 to be normalized to 1.0+ubuntu.1.
385
+ """
386
+ release = release or ""
387
+ if release:
388
+ release = release.replace("-", ".")
389
+ release = release.replace("_", ".")
390
+ return release
391
+
392
+ @staticmethod
393
+ def __is_optional_value_less_than(value1: int | None, value2: int | None) -> bool:
394
+ """
395
+ Integer compare for less than where any value may be None.
396
+ None is considered less than any integer, but equal to an empty string.
397
+ Both values None are considered not less than.
398
+ case value1 ? value2 < returns
399
+ a None == None False
400
+ b None < int True
401
+ c int > None False
402
+ d int ? int value1 < value2
403
+ """
404
+ if value1 is None and value2 is not None: # case b
405
+ return True
406
+ if value1 is not None and value2 is not None: # case d
407
+ return value1 < value2
408
+ return False # case a, c
409
+
410
+ @staticmethod
411
+ def __bump_part(part: str, prefix: str, value: str) -> str:
412
+ """
413
+ Increment the part version for prefixed parts (ex: "dev" -> "dev0", ".devN" -> ".devN+1").
414
+ For parts without a numerical value, set the numeric value to "0" (ex: "dev" -> "dev0")
415
+ """
416
+ if part and prefix and (prefix in {part, f".{part}"}):
417
+ if value.startswith(prefix):
418
+ return f"{prefix}{int(value[len(prefix):]) + 1}"
419
+ return f"{prefix}1"
420
+ return value
421
+
422
+ @staticmethod
423
+ def __bump_int_part(part: str, prefix: str, value: int | None) -> int | None:
424
+ """
425
+ Increment integer parts.
426
+ """
427
+ if part and prefix and part == prefix:
428
+ value = (value or 0) + 1
429
+ return value
430
+
431
+ @staticmethod
432
+ def __bump_local(part: str, value: str) -> str:
433
+ """
434
+ Increment trailing integer of the local part.
435
+ If the local part does not have a trailing integer, set it to "1".
436
+ """
437
+ if part == "local":
438
+ match = re.match(r"(.*)(\d+)$", value)
439
+ value = f"{value}1" if match is None else f"{match.group(1)}{int(match.group(2)) + 1}"
440
+ return value
441
+
442
+ def __clear_parts(self, parts: Sequence[str]) -> None:
443
+ """
444
+ Clear parts in the given sequence.
445
+ Parts must be in Version.PARSED_PARTS, raise ValueError if not.
446
+ Do not clear "major" part.
447
+ The clear value is "0" for integer parts and "" for non-integer parts.
448
+ """
449
+ for part in parts:
450
+ # do not clear major
451
+ if part in ["epoch", "minor", "patch"]:
452
+ # do not clear if part is unused in the version
453
+ if isinstance(getattr(self, part), int):
454
+ setattr(self, part, 0)
455
+ elif part != "major":
456
+ setattr(self, part, "")