Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow multiple environment variables to be substituted in config value #76

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class ConfigLookup {
public static final String DATA_DIRECTORY_SYSTEM_PROPERTY_NAME = "structurizr.dataDirectory";
private static final String DATA_DIRECTORY_ENVIRONMENT_VARIABLE_NAME = "STRUCTURIZR_DATA_DIRECTORY";
private static final String DEFAULT_DATA_DIRECTORY_PATH = "/usr/local/structurizr";
private static Pattern ENV_VAR_PATTERN = Pattern.compile("\\$\\{([\\w]*)\\}");

public static String getDataDirectoryLocation() {
return getConfigurationParameter(DATA_DIRECTORY_SYSTEM_PROPERTY_NAME, DATA_DIRECTORY_ENVIRONMENT_VARIABLE_NAME, null, DEFAULT_DATA_DIRECTORY_PATH);
Expand Down Expand Up @@ -70,13 +71,10 @@ public static String getConfigurationParameterFromStructurizrPropertiesFile(Stri
}
}

// translate ${...} into a value from the named environment variable
// (this mirrors what Spring does via the property placeholders)
// translate all ${...} within a string into a value, substituting any
// environment variables along the way
if (value != null) {
if (value.startsWith("${") && value.endsWith("}")) {
String environmentVariableName = value.substring(2, value.length()-1);
value = System.getenv(environmentVariableName);
}
value = getValueFromEnvironmentVariables(value);
}

if (value == null) {
Expand All @@ -86,4 +84,24 @@ public static String getConfigurationParameterFromStructurizrPropertiesFile(Stri
return value;
}

private static String getValueFromEnvironmentVariables(String original)
{
Matcher matcher = ENV_VAR_PATTERN.matcher(original);

int lastIndex = 0;
StringBuilder output = new StringBuilder();
while(matcher.find())
{
output.append(original, lastIndex, matcher.start())
.append(System.getenv(matcher.group(1)));

lastIndex = matcher.end();
}

if (lastIndex < original.length()) {
output.append(original, lastIndex, original.length());
}

return output.toString();
}
}