Skip to main content

Options

Struct Options 

Source
pub struct Options {
    pub sources: Vec<Source>,
    pub formats: Vec<FormatSpec>,
    pub recursive: bool,
    pub flat: bool,
    pub dot_key: bool,
    pub case_sensitive: bool,
    pub order: Order,
    pub tree: bool,
    pub auto_files: bool,
    pub ignore_unknown_ext: bool,
    pub ignore_sheet_prefix: bool,
    pub ignore_hidden_sheets: bool,
}
Expand description

All loader options.

Plain data on purpose: set the fields you care about and take the rest from ..Options::default().

Fields§

§sources: Vec<Source>

The ordered config sources; later sources override earlier ones. Default: the config folder under the current working directory. Every element converts with .into() — see Source for all the accepted shapes.

let value: c4::Value = c4::Loader::new(c4::Options {
        sources: vec![
            "./config".into(),              // a folder …
            "./local.yml".into(),           // … or a single file
            ("yaml", "debug: true").into(), // in-code text
            (std::collections::BTreeMap::from([("port", 8080)]),).into(),
        ],
        ..c4::Options::default()
    })
    .load()?;
§formats: Vec<FormatSpec>

Which formats to read and which extensions each one claims. The list carries no override-order semantics — it only builds the extension→format mapping (if several entries claim the same extension, the last entry wins the claim). Override order between files is decided by filename alone; see the merge rules in README.md. Entry forms are on FormatSpec.

let options = c4::Options {
    formats: vec![
        "jsonc".into(),                                     // default extensions
        (c4::Format::Yaml, ["yml", "yaml", "conf"]).into(), // custom extensions
        (c4::Format::Csv, ["csv"], "db").into(),            // + a table layout
    ],
    ..c4::Options::default()
};
assert_eq!(options.formats.len(), 3);
§recursive: bool

Merge mode only (tree: false); folder sources. Scan subdirectories too. Default false.

// config/base.json and config/prod/db.json both merge in
let value: c4::Value = c4::Loader::new(c4::Options {
        recursive: true,
        ..c4::Options::default()
    })
    .load()?;
§flat: bool

Merge mode only, and only meaningful with recursive: true. true (default): subfolder files merge as if they sat at the top level — folder names carry no meaning. false: each subfolder becomes a key and its files merge under it. (The filename never becomes a key in merge mode; for folder-and-filename keys use tree mode.)

// config/db/a.json = {"host": "x"} — with flat: false it merges
// under the subfolder's key instead of the top level
let value: c4::Value = c4::Loader::new(c4::Options {
        recursive: true,
        flat: false,
        ..c4::Options::default()
    })
    .load()?;
assert_eq!(value["db"]["host"].as_str(), Some("x"));
§dot_key: bool

All modes; env and table formats. Treat dotted keys as nested paths: a.b.c becomes { "a": { "b": { "c": … } } }. Default true.

In the table stage this applies to both layouts: the kv layout’s key column, and the db layout’s key row (a dotted column nests inside each record).

A key segment may also end in array suffixes — [] (append) and [<int>] (index) groups, chained for nested arrays (grid[0][1], one level per group); any other bracket shape (a[x], a[-1], a[]b, a bare []) keeps the whole segment a literal key:

  • name[] appends one new element per occurrence: per kv row / env line, and per record for a db column.
  • name[<int>] addresses element <int>: the same index deep-merges into one element and indexes may arrive in any order. Skipped indexes leave Null gaps — a[1] + a[4] give a five-element array with nulls at 0, 2 and 3; deserialize such arrays as Vec<Option<T>>.

Suffixes also chain through the dotted path (a[0].b[].c) and work on keys without dots (ports[]). The expansion happens within one parse (one file/sheet/string source) — across sources arrays still replace like any array. The dot-key example tours all of it.

use std::path::Path;

use c4::{Options, TableLayout};

let options = Options::default(); // dot_key: true

// kv layout: the key column nests
let rows = vec![vec!["a.b".to_string(), "1".to_string()]];
let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
assert_eq!(value["a"]["b"].as_i64(), Some(1));

// db layout: dotted keys nest inside each record
let rows = vec![
    vec!["a.b".to_string(), "a.c".to_string()], // key row
    vec![String::new(), String::new()],         // type row (all auto)
    vec!["1".to_string(), "2".to_string()],     // one record
];
let value = c4::parse_table(rows, &TableLayout::Db, Path::new("doc"), &options)?;
assert_eq!(value[0]["a"]["b"].as_i64(), Some(1));
assert_eq!(value[0]["a"]["c"].as_i64(), Some(2));

// array suffixes: `[]` appends per row, `[<int>]` indexes
let rows = vec![
    vec!["tags[]".to_string(), "red".to_string()],
    vec!["tags[]".to_string(), "blue".to_string()],
    vec!["servers[1].host".to_string(), "beta".to_string()],
    vec!["servers[0].host".to_string(), "alpha".to_string()],
];
let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
assert_eq!(value["tags"][1].as_str(), Some("blue"));
assert_eq!(value["servers"][0]["host"].as_str(), Some("alpha"));

// chained suffixes nest; skipped indexes leave null gaps
let rows = vec![vec!["m[1][0]".to_string(), "9".to_string()]];
let value = c4::parse_table(rows, &TableLayout::Kv, Path::new("doc"), &options)?;
assert!(value["m"][0].is_null());
assert_eq!(value["m"][1][0].as_i64(), Some(9));
§case_sensitive: bool

All modes. Case-sensitive key merging. Default true; when false, keys are normalized to lowercase. (File-extension matching is always case-insensitive and unrelated to this option.)

use std::collections::BTreeMap;

let value: c4::Value = c4::Loader::new(c4::Options {
        sources: vec![
            (BTreeMap::from([("PORT", 1)]),).into(),
            (BTreeMap::from([("port", 8080)]),).into(),
        ],
        case_sensitive: false, // "PORT" and "port" are one key
        ..c4::Options::default()
    })
    .load()?;
assert_eq!(value["port"].as_i64(), Some(8080));
§order: Order

All modes; folder sources. Load order inside a folder. In merge mode it decides which file overrides which; in tree mode it decides key collisions (a.yml vs a folder a/).

let value: c4::Value = c4::Loader::new(c4::Options {
        order: "alphabetic".into(), // or c4::Order::Alphabetic
        ..c4::Options::default()
    })
    .load()?;
§tree: bool

Mode switch (requires the tree feature; true without it is Error::Unsupported). false (default): merge mode — a folder’s files deep-merge into one value. true: tree mode — the folder’s shape becomes the value: every subfolder is a key, and every file is a key named after the file (extension stripped) holding that file’s parsed content — a/b.json = {c:1} and d.json = {a:123} load as {a: {b: {c: 1}}, d: {a: 123}}.

The rules, in full:

  • Applies to folder path sources only; single-file and string sources merge into the root as always.
  • Always recursive — recursive and flat do not apply, but order does: entries load in order, and a key collision (a.yml next to a folder a/) deep-merges, so order decides the winner.
  • A dotfile whose whole name is its extension (.env) keeps the full name as its key.
  • Extension handling: a claimed extension parses normally; an extension-less file follows auto_files; any other unclaimed extension follows ignore_unknown_ext.
  • A spreadsheet workbook parses to an object keyed by sheet name, so its sheets become keys under the file’s key — a/b.xlsx with sheets c, d loads as {a: {b: {c: …, d: …}}}.
// config/a/b.json = {"c": 1}  ->  {a: {b: {c: 1}}}
let value: c4::Value = c4::Loader::new(c4::Options {
        tree: true,
        ..c4::Options::default()
    })
    .load()?;
assert_eq!(value["a"]["b"]["c"].as_i64(), Some(1));
§auto_files: bool

Tree mode only. What to do with a file that has no extension. true (default): read it and guess the type of its (trimmed) content with the table auto rules — a file containing 1.1.1.1 becomes an IPv4 value when the ipv4 feature is on, a string otherwise. false: treat it like a file with an unknown extension (see ignore_unknown_ext). (Named auto_files after the table auto type id it reuses.)

// tree mode: config/host is an extension-less file holding "1.1.1.1"
let value: c4::Value = c4::Loader::new(c4::Options {
        tree: true,
        auto_files: true,
        ..c4::Options::default()
    })
    .load()?;
assert!(!value["host"].is_null());
§ignore_unknown_ext: bool

Tree mode only. What to do with a file whose extension no active format claims: skip it (true, default) or fail the load with Error::Parse (false). Merge mode always skips such files.

let value: c4::Value = c4::Loader::new(c4::Options {
        tree: true,
        ignore_unknown_ext: false, // a config/*.xyz file now errors
        ..c4::Options::default()
    })
    .load()?;
§ignore_sheet_prefix: bool

Spreadsheet formats (excel/ods) only. Skip sheets whose name starts with #, . or _ — draft/scratch space next to live config. Default true. (A table source that names a sheet explicitly bypasses this filter, so a prefixed sheet stays loadable on purpose.)

// tree mode: game.xlsx has sheets "items" and "_draft"; by
// default "_draft" is skipped — false reads it as a key too
let value: c4::Value = c4::Loader::new(c4::Options {
        sources: vec!["./game.xlsx".into()],
        tree: true,
        ignore_sheet_prefix: false,
        ..c4::Options::default()
    })
    .load()?;
assert!(!value["_draft"].is_null());
§ignore_hidden_sheets: bool

Spreadsheet formats (excel/ods) only. Skip sheets marked hidden in the workbook (Excel hidden/veryHidden, OpenDocument table:display="false"). Default true. (A table source that names a sheet explicitly bypasses this filter.)

// the workbook's `config` sheet is marked hidden — read it anyway
let value: c4::Value = c4::Loader::new(c4::Options {
        sources: vec!["./game.xlsx".into()],
        ignore_hidden_sheets: false,
        ..c4::Options::default()
    })
    .load()?;

Trait Implementations§

Source§

impl Clone for Options

Source§

fn clone(&self) -> Options

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Options

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Options

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl PartialEq for Options

Source§

fn eq(&self, other: &Options) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Options

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.