# User guide
## Load a file, the environment and the command line
`cargo add configurant`, then:
```rust
use configurant::{Loader, Schema};
use std::collections::BTreeMap;
const SCHEMA: &str = r#"
[project]
name = "app"
version = "1.0.0"
summary = "demo"
schema_version = 1
env_prefix = "APP_"
[[value]]
key = "server.port"
type = "int"
default = 8080
min = 1
max = 65535
env = "APP_PORT"
flag = "--port"
description = "listen port"
"#;
/// `file` is the configuration file's name and text, if there is one.
fn load(
file: Option<(&str, &str)>,
env: BTreeMap<String, String>,
args: Vec<String>,
) -> Result<i64, Box<dyn std::error::Error>> {
let schema = Schema::parse(SCHEMA)?;
let mut loader = Loader::new(&schema).env(env).cli(args);
if let Some((name, text)) = file {
loader = loader.file(name, text);
}
let config = loader.build()?; // every error found, one per line
Ok(config.get("server.port")?)
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// The library reads nothing by itself: you hand it the file, the environment and the arguments.
let path = "app.toml";
let text = match std::fs::read_to_string(path) {
Ok(text) => Some(text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(e.into()),
};
// `vars` panics on a variable that is not Unicode; `vars_os` lets you skip those.
let env = std::env::vars_os()
.filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?)))
.collect();
let args = std::env::args().skip(1).collect();
let port = load(text.as_deref().map(|t| (path, t)), env, args)?;
println!("listening on {port}");
Ok(())
}
```
Later layers override earlier ones: **schema default < file < environment < command line**. A value marked `secret`
is refused from a file, a default and a flag; it comes from its environment variable, or from a `source`
([SECRET-SOURCES.md](SECRET-SOURCES.md)). In `app.toml` the port is written as `port = 9000` under `[server]`.
An unknown key is an error, with the nearest known name:
```text
unknown key `server.prot` from file `app.toml` (did you mean `server.port`?)
```
Only environment variables the schema names are read. If `env_prefix` is set, any other variable starting with it is
an unknown-key error, so a misspelt `APP_PROT` is reported. The command line you pass to `.cli` must hold only the
schema's flags; strip your program's own arguments first.
## What each load error means
`build` returns `Errors`, every `ConfigError` it found. A secret's value is shown as `<redacted>`.
| `UnknownKey` | A file key, prefixed variable or flag the schema does not declare. Fix the spelling or declare it. |
| `WrongType` | The text or TOML value is not the declared type. |
| `OutOfRange` | Outside `min`..`max`. |
| `NotAllowed` | Not one of the declared `choices`. |
| `SecretInForbiddenSource` | A secret was given in a file or flag. Remove it there (and change it if the file was shared); use its variable. |
| `MissingRequired` | A `required` value that no layer set. |
| `MissingCliValue` | A flag that takes a value was given none. |
| `UnexpectedArgument` | An argument that is not a `--flag`; only its position is shown. |
| `FileParse` | The file is not valid TOML (message and line), or is over 1 MiB. |
| `FileOutdated`, `MountFileOutdated` | The file is at an older config version. Run `configurant migrate`. |
| `FileNewer`, `MountFileNewer` | The file was written for a newer program. Upgrade the program, or migrate back with `--to`. |
| `EmptyMapKey` | A map has an entry whose key is empty. |
| `ModuleMissing` | A non-default value for a key whose `provider` module is not registered. |
| `ModuleRejected` | The module refused the value; its reason is given. |
`Config::get` and its relatives return these for a lookup:
| `UnknownKey` | The schema has no such key. `configurant keys` finds these in your sources. |
| `NotSet` | No default and no layer set it. Give a default, mark it `required`, or read it as optional. |
| `WrongType` | The Rust type asked for does not match the declared type. |
| `FileOnly` | An array of tables or a map: read it with `rows` or `map`. |
| `Deserialize` | The configuration does not fit your `serde` type. |
A bad schema is a `SchemaError`, whose message names the key and the rule; `configurant check` shows it.
## The command
`cargo install configurant`; `configurant <command> --help` lists each command's options.
| 0 | Done. |
| 1 | `keys` only: the sources ask for a key the schema does not define. |
| 2 | Refused: a usage error, an unreadable file, or an invalid schema or configuration. The reason is on standard error. |
What is trusted and what is not: [THREAT-MODEL.md](THREAT-MODEL.md).