Skip to content

Commit

Permalink
fix: Preserve dotted-key ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
mxndtaylor committed Nov 9, 2024
1 parent d9edae9 commit b2378f2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
3 changes: 2 additions & 1 deletion crates/toml_edit/src/inline_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::iter::FromIterator;

use crate::key::Key;
use crate::repr::Decor;
use crate::table::{Iter, IterMut, KeyValuePairs, TableLike};
use crate::table::{Iter, IterMut, KeyValuePairs, TableLike, sort_values_by_position};
use crate::{InternalString, Item, KeyMut, RawString, Table, Value};

/// Type representing a TOML inline table,
Expand Down Expand Up @@ -75,6 +75,7 @@ impl InlineTable {
_ => {}
}
}
sort_values_by_position(values);
}

/// Auto formats the table.
Expand Down
13 changes: 13 additions & 0 deletions crates/toml_edit/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ impl Table {
_ => {}
}
}
sort_values_by_position(values);
}

/// Auto formats the table.
Expand Down Expand Up @@ -518,6 +519,18 @@ fn decorate_table(table: &mut Table) {
}
}

pub(crate) fn sort_values_by_position<'s>(values: &mut Vec<(Vec<&'s Key>, &'s Value)>) {
values.sort_by(|(left_kp, _), (right_kp, _)| {
return match (left_kp.last().map(|x| x.position),
right_kp.last().map(|x| x.position)) {
// first if both have Some() position, its easy
(Some(Some(p1)), Some(Some(p2))) => p1.cmp(&p2),
// if one or more do not, preserve order
_ => std::cmp::Ordering::Equal
}
});
}

// `key1 = value1`
pub(crate) const DEFAULT_ROOT_DECOR: (&str, &str) = ("", "");
pub(crate) const DEFAULT_KEY_DECOR: (&str, &str) = ("", " ");
Expand Down

0 comments on commit b2378f2

Please sign in to comment.