diff --git a/git-rev.py b/git-rev.py index 56ef106..4ee8a6e 100644 --- a/git-rev.py +++ b/git-rev.py @@ -1,20 +1,49 @@ import subprocess import time import os +import re -# get tag/base version -try: - tag = subprocess.check_output("git describe --tags --abbrev=0", shell=True).decode().strip() -except: - tag = "?" +branch = "?" +tag = "?" + +GITHUB_REF = os.environ.get('GITHUB_REF') -GITHUB_TAG = os.environ.get('GITHUB_TAG') +if GITHUB_REF is not None: + # Running in Github action + BRANCH_TAG_RE = re.compile(r'^refs\/([^\/]+)\/(.*)?$') + m = BRANCH_TAG_RE.match(GITHUB_REF) + if m.group(1) is not None: + if m.group(1) == "tags": + # tagged + tag = m.group(2) + try: + branch = subprocess.check_output("git branch -r --contains tags/" + tag, shell=True).decode().strip() + if branch.startswith("origin/"): + branch = branch[7:] + except: + branch = "unknown" + elif m.group(1) == "heads": + # branch + branch = m.group(2) + tag = "latest" -if GITHUB_TAG is not None: - tag = GITHUB_TAG +else: + # running locally + + # get tag/base version + try: + tag = subprocess.check_output("git describe --tags --abbrev=0", shell=True).decode().strip() + except: + tag = "?" + if tag.startswith('v'): + tag = tag[1:] + + # get branch name + try: + branch = subprocess.check_output("git rev-parse --abbrev-ref HEAD", shell=True).decode().strip() + except: + branch = "unknown" -if tag.startswith('v'): - tag = tag[1:] version = tag # get current revision hash @@ -23,22 +52,8 @@ except: commit = "?" -GITHUB_SHA = os.environ.get('GITHUB_SHA') - -if GITHUB_SHA is not None: - commit = GITHUB_SHA - -# get branch name -try: - branch = subprocess.check_output("git rev-parse --abbrev-ref HEAD", shell=True).decode().strip() -except: - branch = "unknown" - -if GITHUB_TAG is not None: - branch = "main" - # if not main branch append branch name -if branch != "main": +if branch != "main" and branch != "HEAD": version += "-[" + branch + "]" # check if clean