Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/ops/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,17 +52,23 @@ pub fn set_value(
}
}

// insert will overwrite the decoration of the original key
// When the table is empty, only write the default decoration
// When the table has values, we need to read the existing decoration and apply it to the newly written value
// When the key to be written exists, only the value should be modified without changing the key's decoration
fn insert_tablelike<'a>(table: &mut (dyn TableLike + 'a), key: &str, value: Item) {
if table.is_empty() {
table.insert(key, value);
} else if table.contains_key(key) {
let pre_value = table.get(key).unwrap();
} else if let Some((mut pre_key, pre_value)) = table.get_key_value_mut(key) {
let (prefix, suffix) = get_item_decor(pre_value);
if let Item::Value(value) = value {
// insert function will auto foramt the key in table and inlinetable
table.insert(key, Item::Value(value.decorated(prefix, suffix)));
*pre_value = Item::Value(value.decorated(prefix, suffix));
} else if value.is_table() && !pre_value.is_table() {
// remove space before equal sign
pre_key.leaf_decor_mut().set_suffix("");
*pre_value = value;
} else {
table.insert(key, value);
*pre_value = value;
};
} else {
if let Item::Value(value) = value {
Expand Down
2 changes: 1 addition & 1 deletion tests/array_edit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ describe("array edit", () => {
expect(edit(aot, "foo.bar.[0].age", 20, opt)).toBe(dedent`
[foo]
bar = [
{ name = "tom", age = 20 }
{ name = "tom",age = 20 }
]
`)
})
Expand Down
36 changes: 36 additions & 0 deletions tests/edit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,29 @@ describe("edit", () => {
a = 1
b = 2
`)

const input1 = dedent`
[foo]
# comment
bar = 1
`
expect(edit(input1, "foo.bar", 2, opt)).toBe(dedent`
[foo]
# comment
bar = 2
`)
expect(edit(input1, "foo.bar", { baz: 3 }, opt)).toBe(dedent`
[foo]
# comment
bar = { baz = 3 }
`)
// TODO: This is a known bug: https://github.com/toml-rs/toml/issues/691
// expect(edit(input1, "foo.bar", { baz: 3 }, {...opt, inline: false})).toMatchInlineSnapshot(`
// "[foo]
// # comment
// [foo.bar]
// baz = 3"
// `)
})

it("set datetime", () => {
Expand Down Expand Up @@ -310,4 +333,17 @@ describe("issue", () => {
"
`)
})

it("issue#8", () => {
const toml = dedent`
[package]
# comment
rand = "1"
`
expect(edit(toml, "package.rand", "2", opt)).toBe(dedent`
[package]
# comment
rand = "2"
`)
})
})
Loading