Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve Toml File map Order #89

Open
Ziqi-Yang opened this issue Jan 12, 2024 · 3 comments
Open

Preserve Toml File map Order #89

Ziqi-Yang opened this issue Jan 12, 2024 · 3 comments

Comments

@Ziqi-Yang
Copy link

I want this library can preserve map order for toml configuration file. See this simple script (originally taken from toml-rs/toml#520):

use indexmap::IndexMap;
use serde::Deserialize;
use figment::{Figment, providers::{Format, Toml}};

#[allow(dead_code)]
#[derive(Deserialize, Debug, Clone)]
pub struct Cfg {
    pub(crate) id: f32,
    pub(crate) accounts: IndexMap<String, Account>,
}

#[allow(dead_code)]
#[derive(Deserialize, Debug, Clone)]
pub struct Account {
    pub(crate) id: i32,
    pub(crate) name: String,
}

fn main() {
    let toml = r#"

id=5

[accounts.c]
id=123
name="3a22e"

[accounts.a]
id=789
name="qawe"

[accounts.d]
id=456
name="3css"

[accounts.b]
id=1021
name="cfrt"

"#;

    // doens't preserve order
    let figment = Figment::new()
        .merge(Toml::string(toml));
    let cfg: Cfg = figment.extract().unwrap();
    
    // do preserve order, since we enable `indexmap` feature and use `IndexMap`
    // let cfg: Cfg = toml::from_str(&toml).unwrap();
    
    for (id, name) in cfg.accounts.iter() {
        println!("({}, {:?})", id, name);
    }
}

and Cargo.toml:

figment = { git = "https://github.com/SergioBenitez/Figment", rev="e8f1f13", features = ["env", "test", "toml"] }
toml = { version = "0.8.8", features = ["indexmap"] }

I wonder it there a simple way to enable indexmap or we need to impl a new Toml provider to use the indexmap feature?

@SergioBenitez
Copy link
Owner

See my comments in #90 (comment).

@mhovd
Copy link

mhovd commented May 25, 2024

We have a similar problem, in that TOML entry order is not preserved (or even consistent!). For example

[ranges]
a = [0, 10]
b = [20, 30]

We depend on the order, so between runs, settings.ranges.first() will sometimes give a, sometimes give b.
Is there a way to preserve entry order with Figment?

@SergioBenitez
Copy link
Owner

@mhovd Please see the comment above and feel free to submit a PR!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants