Skip to content

Instantly share code, notes, and snippets.

@samuelcolvin
Last active October 15, 2020 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelcolvin/da2f521da5d2195fbfd65da3b8f58589 to your computer and use it in GitHub Desktop.
Save samuelcolvin/da2f521da5d2195fbfd65da3b8f58589 to your computer and use it in GitHub Desktop.
set version in python package in a github action using GITHUB_REF
#!/usr/bin/env python3
"""
see https://gist.github.com/samuelcolvin/da2f521da5d2195fbfd65da3b8f58589 for details
"""
import os
import re
import sys
from pathlib import Path
def main(version_path_env_var='VERSION_PATH', version_env_vars=('VERSION', 'GITHUB_REF')) -> int:
version_path = os.getenv(version_path_env_var)
if not version_path:
print(f'✖ "{version_path_env_var}" env variable not found')
return 1
version_path = Path(version_path)
if not version_path.parent.is_dir():
print(f'✖ path "{version_path.parent}" does not exist')
return 1
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:
print(f'✖ "{version_env_vars}" env variables not found')
return 1
print(f'writing version "{version}", to {version_path}')
version_path.write_text(f"""\
__all__ = ('VERSION',)
VERSION = '{version}'
""")
return 0
if __name__ == '__main__':
sys.exit(main())

To use simply run

VERSION_PATH='<your package dir>/version.py' python <(curl -Ls https://git.io/JT3rm)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment