| 1 | #[derive (Copy, Clone, Default)] |
| 2 | pub(crate) struct DocumentFormatter { |
| 3 | pub(crate) multiline_array: bool, |
| 4 | is_value: bool, |
| 5 | } |
| 6 | |
| 7 | impl toml_edit::visit_mut::VisitMut for DocumentFormatter { |
| 8 | fn visit_document_mut(&mut self, node: &mut toml_edit::DocumentMut) { |
| 9 | toml_edit::visit_mut::visit_document_mut(self, node); |
| 10 | } |
| 11 | |
| 12 | fn visit_item_mut(&mut self, node: &mut toml_edit::Item) { |
| 13 | let is_parent_value = self.is_value; |
| 14 | if !is_parent_value { |
| 15 | let other = std::mem::take(node); |
| 16 | let other = match other.into_table().map(toml_edit::Item::Table) { |
| 17 | Ok(i) => i, |
| 18 | Err(i) => i, |
| 19 | }; |
| 20 | let other = match other |
| 21 | .into_array_of_tables() |
| 22 | .map(toml_edit::Item::ArrayOfTables) |
| 23 | { |
| 24 | Ok(i) => i, |
| 25 | Err(i) => i, |
| 26 | }; |
| 27 | self.is_value = other.is_value(); |
| 28 | *node = other; |
| 29 | } |
| 30 | |
| 31 | toml_edit::visit_mut::visit_item_mut(self, node); |
| 32 | self.is_value = is_parent_value; |
| 33 | } |
| 34 | |
| 35 | fn visit_table_mut(&mut self, node: &mut toml_edit::Table) { |
| 36 | node.decor_mut().clear(); |
| 37 | |
| 38 | // Empty tables could be semantically meaningful, so make sure they are not implicit |
| 39 | if !node.is_empty() { |
| 40 | node.set_implicit(true); |
| 41 | } |
| 42 | |
| 43 | toml_edit::visit_mut::visit_table_mut(self, node); |
| 44 | } |
| 45 | |
| 46 | fn visit_value_mut(&mut self, node: &mut toml_edit::Value) { |
| 47 | node.decor_mut().clear(); |
| 48 | |
| 49 | toml_edit::visit_mut::visit_value_mut(self, node); |
| 50 | } |
| 51 | |
| 52 | fn visit_array_mut(&mut self, node: &mut toml_edit::Array) { |
| 53 | toml_edit::visit_mut::visit_array_mut(self, node); |
| 54 | |
| 55 | if !self.multiline_array || (0..=1).contains(&node.len()) { |
| 56 | node.set_trailing("" ); |
| 57 | node.set_trailing_comma(false); |
| 58 | } else { |
| 59 | for item in node.iter_mut() { |
| 60 | item.decor_mut().set_prefix(" \n " ); |
| 61 | } |
| 62 | node.set_trailing(" \n" ); |
| 63 | node.set_trailing_comma(true); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |