toml icon indicating copy to clipboard operation
toml copied to clipboard

Missing output on `or_insert()`ing on a nested `Item::None` table

Open MarijnS95 opened this issue 8 months ago • 3 comments

Consider the following inexistant patch."ssh://foo.bar" table, that I'd like to fill with a my_crate entry:

fn main() {
    let mut x = toml_edit::DocumentMut::new();
    let patch = &mut x["patch"]["ssh://foo.bar"];
    assert!(patch.is_none());
    patch["my_crate"]["path"] = toml_edit::Item::Value("foo/baz/bar".into());
    println!("{}", x);
}

It seems the IndexMut access here causes all None tables to be added, with an implicit moniker, which is neat:

patch = { "ssh://foo.bar" = { my_crate = { path = "foo/baz/bar" } } }

However, I'd like the table to not be inline, to get [patch."ssh://foo.bar"]. It seems that toml_edit::table() returns such a table, so I assumed .or_insert()ing it would work:

fn main() {
    let mut x = toml_edit::DocumentMut::new();
    let patch = x["patch"]["ssh://foo.bar"].or_insert(toml_edit::table()); // This table is _not_ inline
    patch["my_crate"]["path"] = toml_edit::Item::Value("foo/baz/bar".into());
    println!("{}", x);
}

Somewhat surprisingly, this does not seem to recursively insert an implicit table for patch, and the output is:

patch = {}

The only way I've found around this thus far is to insert another table on ["patch"].or_insert(...). However, to prevent an empty [patch] from showing up, this has to be marked as implicit with this rather verbose syntax:

fn main() {
    let mut x = toml_edit::DocumentMut::new();
    let patch = &mut x["patch"].or_insert({
        let mut table = toml_edit::Table::new();
        table.set_implicit(true);
        toml_edit::Item::Table(table)
    })["ssh://foo.bar"]
        .or_insert(toml_edit::table());
    patch["my_crate"]["path"] = toml_edit::Item::Value("foo/baz/bar".into());
    println!("{}", x);
}

With the desired output:

[patch."ssh://foo.bar"]
my_crate = { path = "foo/baz/bar" }

Is it expected that no implicit table was created for patch? If so, how about having a toml_edit::implicit_table() helper or the like?

Thanks!

MarijnS95 avatar Jun 10 '24 14:06 MarijnS95