Generate a Mock Artifact Version Tag in Python

Creates a mock build artifact version tag from a branch name and build number, with a date stamp.

Easy Python 3.9+ Aug 9, 2026 Production deployment patterns 13 views 0 copies

Python code

18 lines
Python 3.9+
import re
from datetime import datetime

def mock_version_tag(branch_name: str, build_number: int) -> str:
    """Generate a mock build artifact version tag from branch and build number."""
    branch_slug = re.sub(r'[^a-zA-Z0-9]+', '-', branch_name).strip('-').lower()
    date_part = datetime.utcnow().strftime('%Y%m%d')
    return f"{branch_slug}-{date_part}-{build_number:04d}"

if __name__ == "__main__":
    examples = [
        ("feature/user-login", 42),
        ("hotfix/1.2.3", 7),
        ("main", 1234),
        ("release/v2.0", 99),
    ]
    for branch, build in examples:
        print(f"{branch} -> {mock_version_tag(branch, build)}")

Output

stdout
feature/user-login -> feature-user-login-20250314-0042
hotfix/1.2.3 -> hotfix-1-2-3-20250314-0007
main -> main-20250314-1234
release/v2.0 -> release-v2-0-20250314-0099

How it works

Uses re.sub to replace non-alphanumeric characters with hyphens, then strips leading/trailing hyphens and lowercases the result. The UTC date is appended as %Y%m%d, and the build number is zero-padded to four digits with :04d. This yields a consistent, readable version tag for mocking build artifacts in local or CI testing. The format mimics common artifact versioning conventions: branch-slug-YYYYMMDD-build-number.

Common mistakes

  • Forgetting to call `strip('-')` leaves stray hyphens for branch names like '/feature/x'.
  • Using `datetime.now()` instead of `datetime.utcnow()` introduces timezone-dependent tags.
  • Assuming the build number is always four digits; without `:04d` the tag mismatches expected length.

Variations

  1. Use `datetime.now(timezone.utc).strftime(...)` if you need timezone-aware timestamps.
  2. Replace `re.sub` with a character whitelist like `''.join(c if c.isalnum() else '-' for c in branch_name)` for simpler cases.

Real-world use cases

  • Mocking artifact version tags in CI pipelines before a real release is built.
  • Generating unique snapshot version strings for local development or feature branch testing.
  • Automating version tagging in deployment scripts where the build server passes branch and build number.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.