Skip to content

Instantly share code, notes, and snippets.

@flyck
Last active May 27, 2021 15:30
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 flyck/49293809f962dde171e0d79c05bad8fa to your computer and use it in GitHub Desktop.
Save flyck/49293809f962dde171e0d79c05bad8fa to your computer and use it in GitHub Desktop.
Shortcut for switch environments in IaC repositories
import sys
import os
import pathlib
PREFIX = os.getenv("CE_PREFIX", "environments/")
def main():
""" Find the next environment path to switch to in the current IaC project.
Example:
current directory: dev/infrastructure/container
result: ../../../prod/infrastructure/container
To be used in conjunction with this alias:
alias ce="python3 ~/switch.py && cd \$(python3 ~/switch.py)"
Usage: ce
"""
cwd = str(pathlib.Path.cwd())
envs = []
env = ""
# try to identify the environments level
if PREFIX not in cwd:
print(f"Prefix {PREFIX} not in cwd {cwd}. Dont know what to do. " +
"Hint: Overwrite with valid prefix by setting the environment variable CE_PREFIX.")
sys.exit(1)
# find the env base directory based on the prefix and collect all available environments
env_base_dir = cwd[:cwd.find(PREFIX) + len(PREFIX)]
for entity in pathlib.Path(env_base_dir).glob("*"):
if entity.is_dir():
envs.append(entity.name)
# split up cwd into useful components
sub_path = cwd.split(PREFIX)[1]
current_env = "".join(sub_path.split("/")[0])
sub_path_without_env = "/".join(sub_path.split("/")[1:])
# find next possible environment to switch to
found_next = False
i = 1
while not found_next and i < len(envs):
env = envs[(envs.index(current_env) + i) % len(envs)]
new_sub_path = pathlib.Path(env + "/" + sub_path_without_env)
new_path = pathlib.Path(env_base_dir + "/" + str(new_sub_path))
if new_path.exists():
found_next = True
i += 1
if not found_next:
print(f"Cloudnt find the same sub path {sub_path} in one of the other available environments: {envs}. "
"Dont know what to do.")
sys.exit(1)
# construct ../../ to get from current path to env_base_dir
dots = "".join(["../" for _ in str(new_sub_path).split("/")])
print(f"{dots + str(new_sub_path)}")
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment