Skip to content

Commit

Permalink
fix(toml): Don't lose data when re-formatting
Browse files Browse the repository at this point in the history
The default formatter for `toml` was doing hijinks to the underlying
data, putting top-level items under values and these were just getting
dropped because `toml_edit` doesn't know what to do with them.

Fixes #605
  • Loading branch information
epage committed Sep 9, 2023
1 parent 5fb5318 commit b2879d6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 15 deletions.
32 changes: 19 additions & 13 deletions crates/toml/src/fmt.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#[derive(Copy, Clone, Default)]
pub(crate) struct DocumentFormatter {
pub(crate) multiline_array: bool,
is_value: bool,
}

impl toml_edit::visit_mut::VisitMut for DocumentFormatter {
Expand All @@ -9,21 +10,26 @@ impl toml_edit::visit_mut::VisitMut for DocumentFormatter {
}

fn visit_item_mut(&mut self, node: &mut toml_edit::Item) {
let other = std::mem::take(node);
let other = match other.into_table().map(toml_edit::Item::Table) {
Ok(i) => i,
Err(i) => i,
};
let other = match other
.into_array_of_tables()
.map(toml_edit::Item::ArrayOfTables)
{
Ok(i) => i,
Err(i) => i,
};
*node = other;
let is_parent_value = self.is_value;
if !is_parent_value {
let other = std::mem::take(node);
let other = match other.into_table().map(toml_edit::Item::Table) {
Ok(i) => i,
Err(i) => i,
};
let other = match other
.into_array_of_tables()
.map(toml_edit::Item::ArrayOfTables)
{
Ok(i) => i,
Err(i) => i,
};
self.is_value = other.is_value();
*node = other;
}

toml_edit::visit_mut::visit_item_mut(self, node);
self.is_value = is_parent_value;
}

fn visit_table_mut(&mut self, node: &mut toml_edit::Table) {
Expand Down
4 changes: 2 additions & 2 deletions crates/toml/tests/testsuite/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1202,7 +1202,7 @@ fn serialize_array_with_enum_of_optional_struct_field() {
Choice::Optional(OptionalField { x: 3, y: Some(7) }),
],
};
let expected = "values = [{}, \"Empty\", {}, {}]
let expected = "values = [{ Optional = { x = 0, y = 4 } }, \"Empty\", { Optional = { x = 2, y = 5 } }, { Optional = { x = 3, y = 7 } }]
";
let raw = toml::to_string(&input).unwrap();
snapbox::assert_eq(expected, raw);
Expand All @@ -1215,7 +1215,7 @@ fn serialize_array_with_enum_of_optional_struct_field() {
Choice::Optional(OptionalField { x: 3, y: Some(7) }),
],
};
let expected = "values = [{}, \"Empty\", {}, {}]
let expected = "values = [{ Optional = { x = 0, y = 4 } }, \"Empty\", { Optional = { x = 2 } }, { Optional = { x = 3, y = 7 } }]
";
let raw = toml::to_string(&input).unwrap();
snapbox::assert_eq(expected, raw);
Expand Down

0 comments on commit b2879d6

Please sign in to comment.