pub fn load_and_validate_env_vars<P: AsRef<Path>>(
    config_paths: &[P],
    section: &str
) -> Result<(), EnvInventoryError>
Expand description

Loads environment variables from specified configuration files and validates their presence.

This function goes through the provided list of configuration file paths, merges the environment settings from each file, and ensures that all the registered environment variables are set. If an environment variable is not already present in the system’s environment, it will be set using the value from the merged settings.

Environment variables present in the system’s environment take precedence over those in the configuration files.

Parameters

  • config_paths: A slice containing paths to the configuration files that should be loaded. The files are expected to be in TOML format and have a dedicated section for environment variables.
  • section: The name of the section in the TOML files that contains the environment variables.

Returns

  • Ok(()): If all registered environment variables are present either in the system’s environment or in the merged settings.
  • Err(EnvInventoryError): If there’s an error reading or parsing the config files or if any registered environment variable is missing.

Behavior

The first file in the config_paths slice is mandatory and if it can’t be read or parsed, an error is immediately returned. Subsequent files are optional, and while they will generate a warning if they cannot be read or parsed, they won’t cause the function to return an error.

After merging the settings from all files and overlaying them on the system’s environment variables, the function checks for missing required environment variables and returns an error if any are found.

Examples

let paths = [Path::new("/path/to/shipped.conf"), Path::new("/path/to/system.conf")];
let result = load_and_validate_env_vars(&paths, "env");
if result.is_err() {
    eprintln!("Failed to load and validate environment variables: {:?}", result);
}

Errors

This function can return the following errors:

  • ReadFileError: If a provided config file cannot be read.
  • ParseFileError: If a provided config file cannot be parsed as TOML or lacks the expected structure.
  • MissingEnvVars: If one or more registered environment variables are missing.