Last active
May 3, 2023 00:58
-
-
Save jessedufrene/314dc566d1893e89de4e4535c5cb91a6 to your computer and use it in GitHub Desktop.
Python Version - Decent way of auto incrementing the version of a Python script based on the tags in the Git repo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import subprocess | |
| # what to put if version cannot be determined | |
| _undefined_version = "undefined version" | |
| # first, try getting version from git | |
| _git_version = None | |
| try: | |
| _git_version = subprocess.check_output(["git", "describe", "--dirty"], stderr=subprocess.PIPE).strip().decode("utf-8") | |
| except (FileNotFoundError, subprocess.CalledProcessError) as e: | |
| pass # git is not installed, or can't get the version. | |
| # second, try getting version from the _version.py file | |
| _file_version = None | |
| try: | |
| from _version import version as _file_version | |
| except (ModuleNotFoundError, AttributeError): | |
| pass | |
| # third, see if we need to write the version file | |
| if _git_version and (not _file_version or _git_version != _file_version): | |
| # if the git version exists, and the file version either doesn't exist or doesn't match | |
| with open("_version.py", "w") as file: | |
| file.write(f'version = "{_git_version}"') | |
| # fourth, set the version | |
| version = _git_version or _file_version or _undefined_version | |
| if __name__ == "__main__": | |
| print(version, end="") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment