semver-check 0.1.0__tar.gz

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,16 @@
1
+ Metadata-Version: 2.3
2
+ Name: semver-check
3
+ Version: 0.1.0
4
+ Summary: Add your description here
5
+ Author: Clemens Schwaighofer
6
+ Author-email: Clemens Schwaighofer <clemens.schwaighofer@omc.com>
7
+ Requires-Python: >=3.13
8
+ Description-Content-Type: text/markdown
9
+
10
+ # SemVer check
11
+
12
+ script to validate a SemVer
13
+
14
+ ```sh
15
+ uv run semver-check [--prefix] <version>
16
+ ```
@@ -0,0 +1,7 @@
1
+ # SemVer check
2
+
3
+ script to validate a SemVer
4
+
5
+ ```sh
6
+ uv run semver-check [--prefix] <version>
7
+ ```
@@ -0,0 +1,81 @@
1
+ [project]
2
+ name = "semver-check"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = []
8
+
9
+ [[project.authors]]
10
+ name = "Clemens Schwaighofer"
11
+ email = "clemens.schwaighofer@omc.com"
12
+
13
+ [project.scripts]
14
+ semver-check = "semver_check.cli:run"
15
+
16
+ [[tool.uv.index]]
17
+ name = "pypi"
18
+ url = "https://pypi.org/simple/"
19
+ publish-url = "https://upload.pypi.org/legacy/"
20
+
21
+ [tool.pyright]
22
+ typeCheckingMode = "strict"
23
+ reportMissingImports = "information"
24
+ reportMissingTypeStubs = "information"
25
+ reportUnknownMemberType = "information"
26
+
27
+ [tool.ty.rules]
28
+ all = "error"
29
+ import-not-found = "warn"
30
+
31
+ [tool.black]
32
+ line-length = 110
33
+ preview = true
34
+ enable-unstable-feature = [
35
+ "string_processing",
36
+ "hug_parens_with_braces_and_square_brackets",
37
+ ]
38
+
39
+ [tool.ruff]
40
+ line-length = 120
41
+
42
+ [tool.ruff.lint]
43
+ ignore = ["DTZ005"]
44
+
45
+ [tool.ruff.lint.isort]
46
+ combine-as-imports = true
47
+
48
+ [tool.ruff.format]
49
+ docstring-code-format = false
50
+
51
+ [tool.pylint.format]
52
+ max-line-length = 120
53
+
54
+ [tool.pylint.MASTER]
55
+ init-hook = 'import sys; sys.path.append("src/")'
56
+
57
+ [tool.pylint.miscellaneous]
58
+ notes = [
59
+ "FIXME",
60
+ "TODO",
61
+ ]
62
+ notes-rgx = '(FIXME|TODO)(\((TTD-|#)\[0-9]+\))'
63
+
64
+ [tool.flake8]
65
+ max-line-length = 120
66
+
67
+ [tool.pytest.ini_options]
68
+ testpaths = ["tests"]
69
+
70
+ [build-system]
71
+ requires = ["uv_build>=0.13.8,<2.0.0"]
72
+ build-backend = "uv_build"
73
+
74
+ [dependency-groups]
75
+ dev = [
76
+ "pyright>=1.1.414",
77
+ "pytest>=9.2.0",
78
+ "pytest-cov>=7.1.0",
79
+ "ruff>=0.17.5",
80
+ "ty>=0.0.104",
81
+ ]
@@ -0,0 +1,86 @@
1
+ [project]
2
+ name = "semver-check"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Clemens Schwaighofer", email = "clemens.schwaighofer@omc.com" }
8
+ ]
9
+ requires-python = ">=3.13"
10
+ dependencies = []
11
+
12
+ [project.scripts]
13
+ semver-check = "semver_check.cli:run"
14
+
15
+ # MARK: build target
16
+ [[tool.uv.index]]
17
+ name = "pypi"
18
+ url = "https://pypi.org/simple/"
19
+ publish-url = "https://upload.pypi.org/legacy/"
20
+
21
+ [build-system]
22
+ requires = ["uv_build>=0.13.8,<2.0.0"]
23
+ build-backend = "uv_build"
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "pyright>=1.1.414",
28
+ "pytest>=9.2.0",
29
+ "pytest-cov>=7.1.0",
30
+ "ruff>=0.17.5",
31
+ "ty>=0.0.104",
32
+ ]
33
+
34
+ # MARK: Linting
35
+ # Pyright
36
+ [tool.pyright]
37
+ typeCheckingMode = "strict"
38
+ reportMissingImports = "information"
39
+ reportMissingTypeStubs = "information"
40
+ reportUnknownMemberType = "information"
41
+ # Ty
42
+ [tool.ty.rules]
43
+ # ty has no strict mode; enabling all rules is the closest equivalent
44
+ all = "error"
45
+ import-not-found = "warn"
46
+ # Black (SUPERSEEDED BY RUFF format)
47
+ [tool.black]
48
+ # set 10 short for better formatting
49
+ line-length = 110
50
+ # to avoid " ... " " ... " string sets
51
+ # experimental-string-processing = true
52
+ preview = true
53
+ enable-unstable-feature = ["string_processing", "hug_parens_with_braces_and_square_brackets"]
54
+ # Ruff
55
+ [tool.ruff]
56
+ line-length = 120
57
+ [tool.ruff.lint]
58
+ ignore = ["DTZ005"]
59
+ [tool.ruff.lint.isort]
60
+ # https://docs.astral.sh/ruff/settings/#lint_isort_force-single-line
61
+ # force-single-line = true
62
+ combine-as-imports = true
63
+ [tool.ruff.format]
64
+ docstring-code-format = false
65
+ # set 10 short for better formatting
66
+ # line-length = 110
67
+ # Pylint
68
+ [tool.pylint.format]
69
+ max-line-length = 120
70
+ # [tool.pylint.TYPECHECK]
71
+ # generated-members="utils.*"
72
+ [tool.pylint.MASTER]
73
+ # this is for the tests/etc folders
74
+ init-hook='import sys; sys.path.append("src/")'
75
+ [tool.pylint.miscellaneous]
76
+ notes = ["FIXME", "TODO"]
77
+ notes-rgx = '(FIXME|TODO)(\((TTD-|#)\[0-9]+\))'
78
+
79
+ # [NOT USED] Flake8
80
+ [tool.flake8]
81
+ max-line-length = 120
82
+
83
+ [tool.pytest.ini_options]
84
+ testpaths = [
85
+ "tests",
86
+ ]
@@ -0,0 +1 @@
1
+ """SemVer 2.0.0 version string checker."""
@@ -0,0 +1,250 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Check if a version string is a valid SemVer 2.0.0 version.
4
+
5
+ Usage:
6
+ ./check_semver.py [--prefix] <version>
7
+
8
+ The version must start with 'v' (e.g. v1.2.3).
9
+ With --prefix, an optional prefix matching ^[A-Za-z]{1,10}- is allowed
10
+ in front of the 'v' (e.g. php-v1.2.3). Without --prefix, prefixed
11
+ versions are invalid.
12
+
13
+ Prints OK or INVALID (with the reason and position of the error).
14
+ Exit codes: 0 = valid, 1 = invalid, 2 = usage error.
15
+ Standalone, standard library only.
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import sys
21
+ from typing import TextIO
22
+
23
+ IDENT_CHARS = re.compile(r"^[0-9A-Za-z-]+$")
24
+ BAD_CHAR = re.compile(r"[^0-9A-Za-z-]")
25
+ PREFIX_RE = re.compile(r"^[A-Za-z]{1,10}-$")
26
+ # anything before the first '-' that does not look like the start of 'vX...'
27
+ PREFIX_CANDIDATE = re.compile(r"^([^.+\-]+-)")
28
+
29
+
30
+ def color(text: str, code: str, stream: TextIO) -> str:
31
+ """Wrap text in ANSI color if stream is a terminal and NO_COLOR is not set (or empty)."""
32
+ if stream.isatty() and os.environ.get("NO_COLOR", "") == "":
33
+ return f"\033[{code}m{text}\033[0m"
34
+ return text
35
+
36
+
37
+ def green(text: str, stream: TextIO = sys.stdout) -> str:
38
+ """Return text wrapped in bold green (if colors are enabled for stream)."""
39
+ return color(text, "1;32", stream)
40
+
41
+
42
+ def red(text: str, stream: TextIO = sys.stdout) -> str:
43
+ """Return text wrapped in bold red (if colors are enabled for stream)."""
44
+ return color(text, "1;31", stream)
45
+
46
+
47
+ class SemverError(Exception):
48
+ """Raised when a version string is not valid SemVer."""
49
+
50
+ def __init__(self, msg: str, pos: int, length: int = 1) -> None:
51
+ """
52
+ Create a SemVer validation error.
53
+
54
+ Args:
55
+ msg: Human readable reason for the error.
56
+ pos: Zero-based position in the version string where the error starts.
57
+ length: Number of characters to mark (at least 1).
58
+ """
59
+ super().__init__(msg)
60
+ self.msg = msg
61
+ self.pos = pos
62
+ self.length = max(1, length)
63
+
64
+
65
+ def check_numeric(part: str, offset: int, label: str) -> None:
66
+ """
67
+ Validate a core version part (MAJOR, MINOR or PATCH).
68
+
69
+ The part must be non-empty, ASCII digits only and have no leading zero.
70
+
71
+ Args:
72
+ part: The numeric part to check.
73
+ offset: Position of the part in the full version string.
74
+ label: Name of the part used in error messages.
75
+
76
+ Raises:
77
+ SemverError: If the part is invalid.
78
+ """
79
+ if part == "":
80
+ raise SemverError(f"{label} is empty", offset)
81
+ if not part.isascii() or not part.isdigit():
82
+ m = re.search(r"[^0-9]", part)
83
+ bad = m.start() if m is not None else 0
84
+ raise SemverError(
85
+ f"{label} '{part}' must be numeric (bad char '{part[bad]}')",
86
+ offset + bad,
87
+ )
88
+ if len(part) > 1 and part[0] == "0":
89
+ raise SemverError(f"{label} '{part}' has a leading zero", offset, len(part))
90
+
91
+
92
+ def check_identifiers(text: str, offset: int, label: str, numeric_no_leading_zero: bool) -> None:
93
+ """
94
+ Validate dot-separated pre-release or build metadata identifiers.
95
+
96
+ Each identifier must be non-empty and only contain [0-9A-Za-z-].
97
+
98
+ Args:
99
+ text: The identifiers string (without the leading '-' or '+').
100
+ offset: Position of text in the full version string.
101
+ label: Name of the section used in error messages.
102
+ numeric_no_leading_zero: If True, numeric identifiers must not have leading zeros
103
+ (required for pre-release, not for build metadata).
104
+
105
+ Raises:
106
+ SemverError: If an identifier is invalid.
107
+ """
108
+ if text == "":
109
+ raise SemverError(f"{label} is empty", offset)
110
+ pos = offset
111
+ for ident in text.split("."):
112
+ if ident == "":
113
+ raise SemverError(f"{label} contains an empty identifier", pos)
114
+ m = BAD_CHAR.search(ident)
115
+ if m:
116
+ raise SemverError(
117
+ f"{label} identifier '{ident}' has invalid char '{ident[m.start()]}' (allowed: 0-9 A-Z a-z -)",
118
+ pos + m.start(),
119
+ )
120
+ if numeric_no_leading_zero and ident.isdigit() and len(ident) > 1 and ident[0] == "0":
121
+ raise SemverError(
122
+ f"{label} numeric identifier '{ident}' has a leading zero",
123
+ pos,
124
+ len(ident),
125
+ )
126
+ pos += len(ident) + 1
127
+
128
+
129
+ def check_semver(version: str, allow_prefix: bool = False) -> None:
130
+ """
131
+ Validate a full version string against SemVer 2.0.0 with a mandatory 'v'.
132
+
133
+ Args:
134
+ version: The version string, e.g. 'v1.2.3' or 'php-v1.2.3-rc.1+build.5'.
135
+ allow_prefix: Allow an optional prefix matching ^[A-Za-z]{1,10}- before the 'v'.
136
+
137
+ Raises:
138
+ SemverError: On the first problem found, with its position in the string.
139
+ """
140
+ s = version
141
+ prefix = ""
142
+ m = PREFIX_CANDIDATE.match(s)
143
+ if m and not re.match(r"^v\d", s):
144
+ prefix = m.group(1)
145
+ if not allow_prefix:
146
+ raise SemverError(f"prefix '{prefix}' not allowed (use --prefix)", 0, len(prefix))
147
+ if not PREFIX_RE.match(prefix):
148
+ raise SemverError(
149
+ f"invalid prefix '{prefix}', must match ^[A-Za-z]{{1,10}}-",
150
+ 0,
151
+ len(prefix),
152
+ )
153
+ offset = len(prefix)
154
+ s = s[offset:]
155
+ if s[:1] != "v":
156
+ raise SemverError(f"missing 'v' before the version (expected {prefix}vX.Y.Z)", offset)
157
+ s = s[1:]
158
+ offset += 1
159
+
160
+ if s == "":
161
+ raise SemverError("version is empty", offset)
162
+
163
+ # build metadata: after first '+'
164
+ build = None
165
+ if "+" in s:
166
+ s, build = s.split("+", 1)
167
+ # pre-release: after first '-'
168
+ pre = None
169
+ if "-" in s:
170
+ s, pre = s.split("-", 1)
171
+
172
+ core = s.split(".")
173
+ names = ["MAJOR", "MINOR", "PATCH"]
174
+ pos = offset
175
+ for i, part in enumerate(core):
176
+ if i >= 3:
177
+ extra = ".".join(core[3:])
178
+ hint = ""
179
+ if re.match(r"^(post|dev|rc|a|b)\d*", extra):
180
+ hint = " (looks like PEP 440/Python versioning, not SemVer)"
181
+ raise SemverError(
182
+ f"too many core parts, expected MAJOR.MINOR.PATCH, got extra '.{extra}'" + hint,
183
+ pos - 1,
184
+ len(extra) + 1,
185
+ )
186
+ check_numeric(part, pos, names[i])
187
+ pos += len(part) + 1
188
+ if len(core) < 3:
189
+ raise SemverError(
190
+ f"missing {', '.join(names[len(core) :])} (expected MAJOR.MINOR.PATCH)",
191
+ offset + len(s),
192
+ )
193
+
194
+ pos = offset + len(s)
195
+ if pre is not None:
196
+ check_identifiers(pre, pos + 1, "pre-release", True)
197
+ pos += len(pre) + 1
198
+ if build is not None:
199
+ check_identifiers(build, pos + 1, "build metadata", False)
200
+
201
+
202
+ def main(argv: list[str]) -> int:
203
+ """
204
+ Parse command line arguments, check the version and print the result.
205
+
206
+ Args:
207
+ argv: Command line arguments including the program name.
208
+
209
+ Returns:
210
+ Exit code: 0 = valid, 1 = invalid, 2 = usage error.
211
+ """
212
+ usage = f"Usage: {os.path.basename(argv[0])} [--prefix] <version>"
213
+ allow_prefix = False
214
+ rest: list[str] = []
215
+ for a in argv[1:]:
216
+ if a in ("-h", "--help"):
217
+ print(usage, file=sys.stderr)
218
+ return 2
219
+ if a == "--prefix":
220
+ allow_prefix = True
221
+ elif a.startswith("--"):
222
+ print(f"{red('ERROR', sys.stderr)}: unknown option '{a}'", file=sys.stderr)
223
+ print(usage, file=sys.stderr)
224
+ return 2
225
+ else:
226
+ rest.append(a)
227
+ if len(rest) != 1:
228
+ print(usage, file=sys.stderr)
229
+ return 2
230
+ version = rest[0]
231
+ try:
232
+ check_semver(version, allow_prefix)
233
+ except SemverError as e:
234
+ print(f"{red('INVALID')}: {e.msg}")
235
+ print(f" {version}")
236
+ print(f" {' ' * e.pos}{'^' * e.length}")
237
+ return 1
238
+ print(green("OK"))
239
+ return 0
240
+
241
+
242
+ def run() -> None:
243
+ """Entry point for the semver-check console script."""
244
+ sys.exit(main(sys.argv))
245
+
246
+
247
+ if __name__ == "__main__":
248
+ run()
249
+
250
+ # __END__