| 1 |
|
| 2 |
"""A simple script to validate that a git tag matches a SemVer pattern.""" |
| 3 |
|
| 4 |
import re |
| 5 |
import subprocess |
| 6 |
|
| 7 |
SEMVER_SIMPLE = re.compile(r"(\d+)\.(\d+)\.(\d+)((a|b|rc)(\d+))?") |
| 8 |
SEMVER_PATTERN = re.compile( |
| 9 |
r""" |
| 10 |
^ # Start of the string |
| 11 |
v? # Optional 'v' prefix (common in Git tags) |
| 12 |
(?P<major>0|[1-9]\d*)\. # Major version |
| 13 |
(?P<minor>0|[1-9]\d*)\. # Minor version |
| 14 |
(?P<patch>0|[1-9]\d*) # Patch version |
| 15 |
(?:-(?P<prerelease> # Optional pre-release section |
| 16 |
(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*) # Identifier |
| 17 |
(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))* |
| 18 |
))? |
| 19 |
(?:\+(?P<build> # Optional build metadata section |
| 20 |
[0-9a-zA-Z-]+ # Identifier |
| 21 |
(?:\.[0-9a-zA-Z-]+)* |
| 22 |
))? |
| 23 |
$ # End of the string |
| 24 |
""", |
| 25 |
re.VERBOSE, |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
def get_current_tag() -> str: |
| 30 |
"""Get current git tag.""" |
| 31 |
try: |
| 32 |
|
| 33 |
result = subprocess.run( |
| 34 |
["git", "describe", "--exact-match", "--tags", "--abbrev=0"], capture_output=True, text=True, check=True |
| 35 |
) |
| 36 |
return result.stdout.strip() |
| 37 |
except subprocess.CalledProcessError: |
| 38 |
print("Could not find a reachable tag.") |
| 39 |
return "" |
| 40 |
|
| 41 |
|
| 42 |
def is_semantic_version(tag_name: str) -> bool: |
| 43 |
"""Check if a given string complies with the semantic versioning 2.0.0 specification. |
| 44 |
|
| 45 |
Args: |
| 46 |
tag_name: The name of the Git tag to validate. |
| 47 |
|
| 48 |
Returns: |
| 49 |
bool: True if the tag is a valid semantic version, False otherwise. |
| 50 |
|
| 51 |
""" |
| 52 |
|
| 53 |
semver_pattern = re.compile( |
| 54 |
r""" |
| 55 |
^ # Start of the string |
| 56 |
v? # Optional 'v' prefix (common in Git tags) |
| 57 |
(?P<major>0|[1-9]\d*)\. # Major version |
| 58 |
(?P<minor>0|[1-9]\d*)\. # Minor version |
| 59 |
(?P<patch>0|[1-9]\d*) # Patch version |
| 60 |
(?:-(?P<prerelease> # Optional pre-release section |
| 61 |
(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*) # Identifier |
| 62 |
(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))* |
| 63 |
))? |
| 64 |
(?:\+(?P<build> # Optional build metadata section |
| 65 |
[0-9a-zA-Z-]+ # Identifier |
| 66 |
(?:\.[0-9a-zA-Z-]+)* |
| 67 |
))? |
| 68 |
$ # End of the string |
| 69 |
""", |
| 70 |
re.VERBOSE, |
| 71 |
) |
| 72 |
|
| 73 |
return bool(semver_pattern.match(tag_name)) |
| 74 |
|
| 75 |
|
| 76 |
if __name__ == "__main__": |
| 77 |
import sys |
| 78 |
|
| 79 |
git_tag = get_current_tag() |
| 80 |
if not git_tag: |
| 81 |
print("Git tag does not exist for current commit.") |
| 82 |
sys.exit(-1) |
| 83 |
|
| 84 |
if not is_semantic_version(git_tag): |
| 85 |
print(rf"Git tag '{git_tag}' is invalid according to SemVer.") |
| 86 |
sys.exit(-1) |
| 87 |
|
| 88 |
print(rf"Git tag '{git_tag}' is valid.") |