Crates.io | cfg-lib |
lib.rs | cfg-lib |
version | 0.1.1 |
source | src |
created_at | 2020-03-25 16:20:25.746435 |
updated_at | 2021-09-13 09:16:30.79009 |
description | A Rust library for working with the CFG configuration format. |
homepage | https://docs.red-dove.com/cfg/rust.html |
repository | https://github.com/vsajip/rust-cfg-lib.git |
max_upload_size | |
id | 222699 |
size | 276,187 |
The CFG configuration format is a text format for configuration files which is similar to, and a superset of, the JSON format. It dates from before its first announcement in 2008 and has the following aims:
It overcomes a number of drawbacks of JSON when used as a configuration format:
With the following configuration file, test0.cfg
:
a: 'Hello, '
b: 'world!'
c: {
d: 'e'
}
'f.g': 'h'
christmas_morning: `2019-12-25 08:39:49`
home: `$HOME`
foo: `$FOO|bar`
You can load and query the above configuration using, for example, the evcxr REPL:
$ evcxr
>> :dep cfg-lib
>> use cfg_lib::*;
The configuration above can be loaded as shown below. In the REPL shell:
>> let cfg = Config::from_file("test0.cfg").unwrap();
The successful from_file()
call returns a Config
instance which can be used to query the configuration.
Accessing elements of the configuration with a simple key is not much harder than using a HashMap
:
>> cfg.get("a")
Ok(Base(String("Hello, ")))
>> cfg.get("b")
Ok(Base(String("world!")))
The values returned are of type Value.
As well as simple keys, elements can also be accessed using path strings:
>> cfg.get("c.d")
Ok(Base(String("e")))
Here, the desired value is obtained in a single step, by (under the hood) walking the path c.d
– first getting the mapping at key c
, and then the value at d
in the resulting mapping.
Note that you can have simple keys which look like paths:
>> cfg.get("f.g")
Ok(Base(String("h")))
If a key is given that exists in the configuration, it is used as such, and if it is not present in the configuration, an attempt is made to interpret it as a path. Thus, f.g
is present and accessed via key, whereas c.d
is not an existing key, so is interpreted as a path.
You can also get native Rust date/time objects from a configuration, by using an ISO date/time pattern in a backtick-string:
>> cfg.get("christmas_morning")
Ok(Base(DateTime(2019-12-25T08:39:49+00:00)))
You get either NaiveDate objects, if you specify the date part only, or else DateTime
To access an environment variable, use a backtick-string of the form $VARNAME
:
>> cfg.get("home")
Ok(Base(String("/home/vinay")))
You can specify a default value to be used if an environment variable isn’t present using the $VARNAME|default-value
form. Whatever string follows the pipe character (including the empty string) is returned if the VARNAME is not a variable in the environment.
>> cfg.get("foo")
Ok(Base(String("bar")))
For more information, see the CFG documentation.