Variable Substitution¶
Background¶
The ‘app’ module supports variable substitution. Configuration items may include any of these constructs:
@VARIABLE@ - Another configuration variable. Configuration variables may be embedded within other configuration variables to any level.
$ENV_VARIABLE - An environment variable.
`shell command` - The output of a shell command.
Variables Processing¶
An Example¶
Imagine your application has loaded a configuration map from an INI file. Within the INI file some items refer to environment variables using $VAR notation, or they may cross-refer to other configuration items in the map. For example:
[Database]
HOST = $DB_HOST
NAME = accounting
CONNECT = host=@HOST@;instance=@NAME@
You may resolve the CONNECT item using this:
#include <c-craft/app.h>
APP_CONFIG cfg = cfg_load(mem, config_file, NULL);
const char *db = cfg_get_item(cfg, "Database", "CONNECT")
const char connect = var_transform(mem, cfg, db, FALSE);
Note that $DB_HOST is expected to be set in the environment.
Unresolved variables are passed through as their name, unchanged. This allows the system to chain variables for later resolution. It is also surprisingly descriptive when variables expected to be set are not found. For example, FATAL: Database host ‘$DB_HOST’ is not responding!
Environment Variables¶
To retrieve an environment variable directly, use this:
#include <c-craft/app.h>
char db_host = var_environment(mem, "DB_HOST");
You may specify a default value like so:
#include <c-craft/app.h>
char db_host = var_environment(mem, "DB_USER_NAME:Guest");
Shell Commands¶
Variables may also contain shell commands which will be called during processing to resolve to a value.
[General]
YEAR = `date +%Y`
#include <c-craft/app.h>
const char year = var_transform(mem, cfg, "@YEAR@", FALSE);
Note the last argument, no_exec, may be set to TRUE if you want to resolve variables and specifically exclude any commands in the configuration. You may require this if your local security policy prohibits commands in configuration files.
