You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.8 KiB
87 lines
2.8 KiB
import os |
|
from arango import ArangoClient |
|
from dotenv import load_dotenv |
|
|
|
def get_env(): |
|
""" |
|
Load environment variables from ArangoDB 'enviroment' collection. |
|
|
|
Returns: |
|
dict: Key-value pairs from the 'enviroment' collection. |
|
""" |
|
try: |
|
load_dotenv(".env") |
|
pwd = os.environ['ARANGO_PWD_ENV_MANAGER'] |
|
except (FileNotFoundError, KeyError): |
|
from getpass import getpass |
|
import warnings |
|
warnings.warn("No .env file found or 'ARANGO_PWD_ENV_MANAGER' not set.", UserWarning) |
|
pwd = getpass("Enter the ArangoDB password for the user 'env_manager': ") |
|
with open(".env", "a+") as f: |
|
f.write(f"\nARANGO_PWD_ENV_MANAGER={pwd}") |
|
load_dotenv(".env") # Reload the .env file to set the new environment variable |
|
pwd = os.environ['ARANGO_PWD_ENV_MANAGER'] |
|
|
|
host = "https://arango.lasseedfast.se" |
|
username = "env_manager" |
|
db = 'div' |
|
|
|
# Initialize the database for ArangoDB. |
|
db = ArangoClient(hosts=host).db(db, username=username, password=pwd) |
|
env_doc = db.collection('enviroment').all().next() |
|
|
|
return env_doc |
|
|
|
|
|
def set_env(): |
|
""" |
|
Set environment variables in the current process from ArangoDB 'enviroment' collection. |
|
""" |
|
# Set the environment variables |
|
for key, value in get_env().items(): |
|
if isinstance(value, dict): |
|
continue |
|
os.environ[key] = str(value) |
|
|
|
def print_env(): |
|
""" |
|
Print all environment variables from ArangoDB 'enviroment' collection to the terminal. |
|
""" |
|
for key, value in get_env().items(): |
|
if isinstance(value, dict): |
|
continue |
|
print(f"{key}: {value}") |
|
|
|
def print_info(): |
|
""" |
|
Print the 'INFO' section from the ArangoDB 'enviroment' collection in a formatted way. |
|
""" |
|
env_info = get_env()['INFO'] |
|
for i, (k, v) in enumerate(env_info.items()): |
|
if i % 2 == 0: |
|
print(f"\033[90m{k}: {v}\033[0m") # Grey color for even indices |
|
else: |
|
print(f"{k}: {v}") # Default color for odd indices |
|
|
|
def write_to_env_file(): |
|
""" |
|
Append environment variables from ArangoDB 'enviroment' collection to the local .env file. |
|
Does not overwrite existing keys or write the 'INFO' key. |
|
""" |
|
env_doc = get_env() |
|
# Only append new keys, do not overwrite .env |
|
existing_keys = set() |
|
try: |
|
with open(".env", "r") as f: |
|
for line in f: |
|
if "=" in line: |
|
k = line.split("=", 1)[0].strip() |
|
existing_keys.add(k) |
|
except FileNotFoundError: |
|
pass # If .env doesn't exist, we'll just create it |
|
|
|
with open(".env", "a") as f: |
|
for key, value in env_doc.items(): |
|
if isinstance(value, dict) or key == "INFO" or key in existing_keys: |
|
continue |
|
f.write(f"{key}={value}\n") |