Module plugx_config::loader::fs
source · Expand description
File system configuration loader.
This is only usable if you enabled fs Cargo feature.
Example
use std::{fs, collections::HashMap};
use tempdir::TempDir;
use plugx_config::loader::{ConfigurationLoader, fs::{ConfigurationLoaderFs, SkippbaleErrorKind}};
use url::Url;
// Create a temporary directory containing `foo.json`, `bar.yaml`, and `baz.toml`:
let tmp_dir = TempDir::new("fs-example").unwrap();
let foo = tmp_dir.path().join("foo.json");
fs::write(&foo, "{\"hello\": \"world\"}").unwrap();
let bar = tmp_dir.path().join("bar.yaml");
fs::write(&bar, "hello: world").unwrap();
let baz = tmp_dir.path().join("baz.toml");
fs::write(&baz, "hello = \"world\"").unwrap();
let url = Url::try_from(format!("file://{}", tmp_dir.path().to_str().unwrap()).as_str()).unwrap();
let mut loader = ConfigurationLoaderFs::new();
// You could set some skippable errors here.
// For example if you're loading contents of one file that may potentially not exists:
// loader.add_skippable_error(SkippbaleErrorKind::NotFound)
let modifier = |url: &Url, loaded: &mut HashMap<String, _>| {
// Modify loaded configuration if needed
Ok(())
};
loader.set_modifier(Box::new(modifier)); // Note that setting a modifier is optional
// Load all configurations inside directory:
let loaded = loader.try_load(&url, None).unwrap();
assert!(loaded.contains_key("foo") && loaded.contains_key("bar") && loaded.contains_key("baz"));
let foo = loaded.get("foo").unwrap();
assert_eq!(foo.maybe_format(), Some(&"json".to_string()));
let bar = loaded.get("bar").unwrap();
assert_eq!(bar.maybe_contents(), Some(&"hello: world".to_string()));
// Only load `foo` and `bar`:
let whitelist = ["foo".into(), "bar".into()].to_vec();
let loaded = loader.try_load(&url, Some(&whitelist)).unwrap();
assert!(!loaded.contains_key("baz"));
// Load just one file:
let qux = tmp_dir.path().join("qux.env");
fs::write(&qux, "hello=\"world\"").unwrap();
let url = Url::try_from(format!("file://{}", qux.to_str().unwrap()).as_str()).unwrap();
let loaded = loader.try_load(&url, None).unwrap();
assert!(loaded.contains_key("qux"));See loader documentation to known how loaders work.
Structs
- Loads configurations from filesystem.
Enums
- Supported skippable errors when loading filesystem contents.