ConfigurationManager
public class ConfigurationManager
A one-stop shop to aggregate configuration properties from different sources, including command-line arguments, environment variables, files, URLs and raw objects into a single configuration store. Once the store has been populated configuration data can be accessed and retrieved for an individual value, or multiple values, resources can also be removed.
Usage Example
import Configuration
let manager = ConfigurationManager()
manager.load(file: "config.json").load(.environmentVariables)
To get configuration values after they have been loaded, use:
manager["path:to:configuration:value"]
The configuration store is represented as a tree, where the path elements in keys are delimited
by colons (:
). The value returned is typed as Any?
, therefore it’s important to cast the value
to the type you want to use.
When aggregating configuration data from multiple sources, if the same configuration key
exists in multiple sources the one most recently loaded will override those loaded earlier.
In the example below the value for foo
is now baz
because ["foo": "baz"]
was more recently
loaded than ["foo": "bar"]
. The same behaviour applies to all other load
functions.
manager.load(["foo": "bar"]).load(["foo": "baz"])
-
Prefix used to denote a command line argument as a configuration path-value pair. Defaults to
--
For example:
./myApp --path.to.configuration=value
Note: This can be set to your preferred prefix when instantiating
ConfigurationManager
. See:init(commandLineArgumentKeyPrefix:commandLineArgumentPathSeparator:environmentVariablePathSeparator:parseStringToObject:)
Declaration
Swift
public var commandLineArgumentKeyPrefix: String
-
Path separator to specify the components of a path that is passed in as a command line argument. Defaults to
.
For example:
./myApp --path.to.configuration=value
Note: This can be set according to your preferences when instantiating
ConfigurationManager
. See:init(commandLineArgumentKeyPrefix:commandLineArgumentPathSeparator:environmentVariablePathSeparator:parseStringToObject:)
Declaration
Swift
public var commandLineArgumentPathSeparator: String
-
Path separator to specify the components of a path that is passed in as an environment variable. Defaults to
__
For example:
PATH__TO__CONFIGURATION=value
Note: This can be set according to your preferences when instantiating
ConfigurationManager
. See:init(commandLineArgumentKeyPrefix:commandLineArgumentPathSeparator:environmentVariablePathSeparator:parseStringToObject:)
Declaration
Swift
public var environmentVariablePathSeparator: String
-
Used to indicate if string values in command-line arguments and environment variables should be parsed to array or dictionary, if possible, using a known Deserializer. Defaults to
true
Note: This can be set according to your preferences when instantiating
ConfigurationManager
. See:init(commandLineArgumentKeyPrefix:commandLineArgumentPathSeparator:environmentVariablePathSeparator:parseStringToObject:)
Declaration
Swift
public var parseStringToObject: Bool
-
Enum to specify the configuration source. The supported options are to load configuration data from either command-line arguments or environment variables.
See moreDeclaration
Swift
public enum Source
-
Base paths for resolving relative paths.
See moreDeclaration
Swift
public enum BasePath
-
init(commandLineArgumentKeyPrefix:commandLineArgumentPathSeparator:environmentVariablePathSeparator:parseStringToObject:)
Create a customized instance of
ConfigurationManager
. Used to customize the default prefix, path separators and string parsing options.Usage Example
let customConfigMgr = ConfigurationManager.init(commandLineArgumentKeyPrefix: "---", commandLineArgumentPathSeparator: "_", environmentVariablePathSeparator: "___", parseStringToObject: false)
Declaration
Swift
public init(commandLineArgumentKeyPrefix: String = "--", commandLineArgumentPathSeparator: String = ".", environmentVariablePathSeparator: String = "__", parseStringToObject: Bool = true)
Parameters
commandLineArgumentKeyPrefix
Optional. Used to denote an argument as a configuration path-value pair. Defaults to
--
commandLineArgumentPathSeparator
Optional. Used to separate the components of a path. Defaults to
.
environmentVariablePathSeparator
Optional. Used to separate the components of a path. Defaults to
__
parseStringToObject
Optional. Used to indicate if string values in commandline arguments and environment variables should be parsed to array or dictionary, if possible, using a known
Deserializer
. Defaults totrue
. -
Load configurations from a raw object.
Usage Example
manager.load([ "hello": "world", "foo": [ "bar": "baz" ] ])
Declaration
Swift
public func load(_ object: Any) -> ConfigurationManager
Parameters
object
The configurations object.
-
Load configurations from command-line arguments or environment variables. For command line arguments, the configurations are parsed from arguments in this format:
<keyPrefix><path>=<value>
.Usage Example (for command-line arguments)
manager.load(.commandLineArguments)
To inject configurations via the command-line at runtime, set configuration values when launching the executable as follows:
./myApp --path.to.configuration=value
Usage Example (for environment variables)
manager.load(.environmentVariables)
Then, to use it in your application, set environment variables as follows:
PATH__TO__CONFIGURATION=value
Declaration
Swift
public func load(_ source: Source) -> ConfigurationManager
Parameters
source
Enum denoting which source to load from.
-
Load configurations from a Data object.
Usage Example
let data = Data(...) manager.load(data: data)
Declaration
Swift
public func load(data: Data, deserializerName: String? = nil) -> ConfigurationManager
Parameters
data
The Data object containing configurations.
deserializerName
Optional. Designated deserializer for the configuration resource. Defaults to
nil
. Pass a value to force the parser to deserialize according to the given format, i.e.JSONDeserializer.shared.name
; otherwise, the parser will go through a list of deserializers and attempt to deserialize using each one. -
Load configurations from a file.
Usage Example
manager.load(file: "/path/to/file")
By default, the
file
argument is a path relative to the location of the executable (.build/debug/myApp). Iffile
is an absolute path, then it will be treated as such. You can change the relative-from path using the optionalrelativeFrom
parameter as follows:// Resolve path against the current working directory manager.load(file: "../path/to/file", relativeFrom: .pwd) // Resolve path against a custom path manager.load(file: "../path/to/file", relativeFrom: .customPath("/path/to/somewhere/on/file/system"))
Note: The following
relativeFrom
options:.executable
(default) and.pwd
, will reference different file system locations if the application is run from inside Xcode than if it is run from the command-line. You can set a compiler flag, i.e.-DXCODE
, in your.xcodeproj
and use the flag to change your configuration file loading logic.Note:
BasePath.project
depends on the existence of aPackage.swift
file somewhere in a parent folder of the executable, therefore, changing its location usingswift build --build-path
is not supported.Declaration
Swift
public func load(file: String, relativeFrom: BasePath = .executable, deserializerName: String? = nil) -> ConfigurationManager
Parameters
file
Path to file.
relativeFrom
Optional. Defaults to the location of the executable.
deserializerName
Optional. Designated deserializer for the configuration resource. Defaults to
nil
. Pass a value to force the parser to deserialize according to the given format, i.e.JSONDeserializer.shared.name
; otherwise, the parser will go through a list of deserializers and attempt to deserialize using each one. -
Load configurations from a URL location.
Usage Example
let url = URL(...) manager.load(url: url)
Note: The
URL
MUST include a scheme, i.e.file://
,http://
, etc.Declaration
Swift
public func load(url: URL, deserializerName: String? = nil) -> ConfigurationManager
Parameters
url
The URL pointing to a configuration resource.
deserializerName
Optional. Designated deserializer for the configuration resource. Defaults to
nil
. Pass a value to force the parser to deserialize according to the given format, i.e.JSONDeserializer.shared.name
; otherwise, the parser will go through a list of deserializers and attempt to deserialize using each one. -
Add a deserializer to the list of deserializers that can be used to parse raw data.
Declaration
Swift
public func use(_ deserializer: Deserializer) -> ConfigurationManager
Parameters
deserializer
The deserializer to be added.
-
Get all configurations that have been merged into the
ConfigurationManager
as a raw object.Declaration
Swift
public func getConfigs() -> Any
-
Access configurations by path.
Declaration
Swift
public subscript(path: String) -> Any?
Parameters
path
The path to a configuration value.