Skip to content

Instantly share code, notes, and snippets.

@samuelcolvin
Last active Jan 26, 2022
Embed
What would you like to do?

Usage is simply

VERSION_PATH=<package name> python <(curl -Ls https://bit.ly/set__version__)

This will set the __version__ variable in <package name/__init__.py based on either the VERSION or GITHUB_REF environment variables.

#!/usr/bin/env python3
"""
see https://gist.github.com/samuelcolvin/e49096dc93396be60d2e972e8799410d for details
"""
import os
import re
import sys
from pathlib import Path
version_regex = re.compile(r'^(__version__ ?= ?).+$', flags=re.M)
def main(version_path_env_var='VERSION_PATH', version_env_vars=('VERSION', 'GITHUB_REF')) -> str:
version_path = os.getenv(version_path_env_var)
if not version_path:
return f'✖ "{version_path_env_var}" env variable not found'
version_path = Path(version_path)
if version_path.is_dir():
version_path = version_path / '__init__.py'
if not version_path.is_file():
return f'✖ "{version_path}" file does not exist'
version = None
for var in version_env_vars:
version_ref = os.getenv(var)
if version_ref:
version = re.sub('^refs/tags/v*', '', version_ref.lower())
break
if not version:
return f'✖ "{version_env_vars}" env variables not found'
content = version_path.read_text()
if not version_regex.search(content):
return f'✖ "{version_path}" does not contain a "__version__ = ..." line'
content = re.sub(version_regex, fr"\1'{version}'", content)
print(f'✔ writing version "{version}", to {version_path}')
version_path.write_text(content)
if __name__ == '__main__':
err = main()
if err:
print(err, file=sys.stderr)
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment