Skip to content

Instantly share code, notes, and snippets.

@haojianzong
Last active May 26, 2024 02:21
Show Gist options
  • Save haojianzong/77d746a0466baa7e6543b1976e0ce8de to your computer and use it in GitHub Desktop.
Save haojianzong/77d746a0466baa7e6543b1976e0ce8de to your computer and use it in GitHub Desktop.
Git tag compare generator
"""
This script fetches the two most recent, distinct semantic version tags from a Git repository
and generates a comparison URL between them, suitable for GitHub repositories.
This can help developers to quickly check their changes before releasing a Prod version.
Output of the script:
Comparison URL: https://github.com/[your-github-name]/[your-repo]/compare/4.4.2-rc1...4.4.3-rc2
"""
import subprocess
from packaging import version
# Define your repository URL here (ensure to replace with your actual repo URL)
REPO_URL = "https://github.com/[your-github-name]/[your-repo]"
def get_semantic_git_tags():
try:
# Fetch all tags from Git, ordered by creatordate descending (most recent first)
tags_raw = subprocess.check_output(['git', 'for-each-ref', '--sort=-creatordate', '--format=%(refname:short)', 'refs/tags']).decode('utf-8').splitlines()
valid_tags = []
for tag in tags_raw:
try:
parsed_tag = version.parse(tag)
if isinstance(parsed_tag, version.Version):
valid_tags.append(tag)
except version.InvalidVersion:
# Ignore tags that don't represent valid semantic versions
continue
return valid_tags
except subprocess.CalledProcessError as e:
print(f"An error occurred while fetching tags from Git: {e}")
return []
def find_two_latest_distinct_versions(tags):
if not tags:
return None, None
# Start with the most recent tag as the first version
latest_version_tag = tags[0]
second_latest_version_tag = None
for tag in tags[1:]:
if version.parse(tag).base_version != version.parse(latest_version_tag).base_version:
second_latest_version_tag = tag
break
return latest_version_tag, second_latest_version_tag
def generate_compare_url(repo_url, tag1, tag2):
clean_url = repo_url.rstrip('.git') # Handle the .git suffix if present
return f"{clean_url}/compare/{tag1}...{tag2}"
def main():
tags = get_semantic_git_tags()
if len(tags) < 2:
print("Not enough valid version tags for a comparison. Need at least 2 versions.")
return
latest_tag, second_latest_tag = find_two_lates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment