Skip to content

Commit

Permalink
feat: add ability to specify a default value for a an environment var…
Browse files Browse the repository at this point in the history
…iable in a .yaml config file
  • Loading branch information
efunneko committed Sep 24, 2024
1 parent c2d77a4 commit 156c744
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/solace_ai_connector/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import sys
import re
import yaml
from .solace_ai_connector import SolaceAiConnector

Expand All @@ -12,7 +13,7 @@ def load_config(file):
yaml_str = f.read()

# Substitute the environment variables using os.environ
yaml_str = os.path.expandvars(yaml_str)
yaml_str = expandvars_with_defaults(yaml_str)

# Load the YAML string using yaml.safe_load
return yaml.safe_load(yaml_str)
Expand All @@ -22,6 +23,19 @@ def load_config(file):
sys.exit(1)


def expandvars_with_defaults(text):
"""Expand environment variables with support for default values.
Supported syntax: ${VAR_NAME} or ${VAR_NAME, default_value}"""
pattern = re.compile(r"\$\{([^}:\s]+)(?:\s*,\s*([^}]*))?\}")

def replacer(match):
var_name = match.group(1)
default_value = match.group(2) if match.group(2) is not None else ""
return os.environ.get(var_name, default_value)

return pattern.sub(replacer, text)


def merge_config(dict1, dict2):
"""Merge a new configuration into an existing configuration."""
merged = {}
Expand Down

0 comments on commit 156c744

Please sign in to comment.