Skip to content

Instantly share code, notes, and snippets.

@StanGenchev
Last active November 25, 2020 17:12
Show Gist options
  • Save StanGenchev/d0a6fa0687ab795338633182e2961633 to your computer and use it in GitHub Desktop.
Save StanGenchev/d0a6fa0687ab795338633182e2961633 to your computer and use it in GitHub Desktop.
Python function to get stage name from git branch name.
# Note that this function assumes that you are in the parent directory of ".git"
from pathlib import Path
def get_active_stage(default: str = "dev") -> str:
"""
Gets active stage from the git branch name.
If name is unknown, it return "dev" or what you have passed as default.
"""
stages = {"master": "prod", "prod": "prod", "test": "test", "dev": "dev"}
stage = ""
with open(".git/HEAD", "r") as head:
content = head.read().splitlines()
for line in content:
if line[0:4] == "ref:":
stage = line.partition("refs/heads/")[2]
break
if stage in stages.keys():
return stages[stage]
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment