Skip to content

Instantly share code, notes, and snippets.

@j4c0bs
Created July 25, 2017 20:18
Show Gist options
  • Save j4c0bs/635631b38cdfcaaa21cfd2b1e2e0810f to your computer and use it in GitHub Desktop.
Save j4c0bs/635631b38cdfcaaa21cfd2b1e2e0810f to your computer and use it in GitHub Desktop.
Auto update version.py and git tag version id
#!/usr/bin/env python3
"""
--------------------------------------------------------------------------------
This script will:
- update git tag version id for last commit
- overwrite all contents in current version.py file
I strongly advise not using the code below and writing your own.
--------------------------------------------------------------------------------
Auto updates git tag version id and version.py file.
Run from same directory as version.py
version.py format:
VERSION="1.2.3"
Major version id numbers are not increased. Minor / sub only.
e.g. 1.2.9 -> 1.3.0
Requires git repo and existing version.py file.
"""
import os
import subprocess
def find_version_file():
version_file = ''
for filename in os.listdir():
if filename.casefold() == 'version.py':
version_file = filename
break
return version_file
def update_git_tag_version_id(version, last_commit_id):
tag_cmd = 'git tag {} {}'.format(version, last_commit_id)
subprocess.run(tag_cmd, shell=True)
print('>>>', tag_cmd)
def update_version_file(version_file, version_id):
with open(version_file, 'w') as ver:
txt = 'VERSION="{}"'.format(version_id)
ver.write(txt)
ver.write('\n')
def git_command_output(cmd):
return subprocess.check_output(cmd, shell=True).decode('utf-8').strip()
def get_last_commit_id():
output = git_command_output('git log --pretty=oneline')
return output[:10]
def get_current_version():
return git_command_output('git describe --abbrev=0 --tags')
def update_version_id(cur_ver):
major, minor, sub = map(int, cur_ver.split('.'))
sub += 1
minor += sub // 10
sub = sub % 10
return '{}.{}.{}'.format(major, minor, sub)
if __name__ == '__main__':
version_file = find_version_file()
if version_file:
current_version_id = get_current_version()
new_version_id = update_version_id(current_version_id)
last_commit_id = get_last_commit_id()
update_git_tag_version_id(new_version_id, last_commit_id)
if new_version_id == get_current_version():
update_version_file(version_file, new_version_id)
print('>>> version id {} --> {}'.format(current_version_id, new_version_id))
else:
print('>>> Unable to update git tag to version id:', new_version_id)
else:
print('\nNo version.py found in current directory\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment