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.
Python code
18 linesimport 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
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
- Use `datetime.now(timezone.utc).strftime(...)` if you need timezone-aware timestamps.
- 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
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a docker-compose.yml with mock services in Python easy
- How to Attach an SBOM to a Release in Python (Mock) easy
Keep learning
Related tutorials and quizzes for this topic.