Sort dependency group keys when adding new group (#11591)

This change keeps dependency group keys sorted when adding new ones. 

If earlier dependency group keys were not sorted, we just append the new
group key to avoid churn in `pyproject.toml`. See discussion on #11447.
I've added a new snapshot test to capture this case.

Closes #11447.
This commit is contained in:
John Mumm 2025-02-18 19:12:50 +01:00 committed by GitHub
parent 555bf89b38
commit b086437bff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 256 additions and 21 deletions

View file

@ -450,6 +450,13 @@ impl PyProjectTomlMut {
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let was_sorted = dependency_groups
.get_values()
.iter()
.filter_map(|(dotted_ks, _)| dotted_ks.first())
.map(|k| k.get())
.is_sorted();
let group = dependency_groups
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new())))
@ -459,6 +466,12 @@ impl PyProjectTomlMut {
let name = req.name.clone();
let added = add_dependency(req, group, source.is_some())?;
// To avoid churn in pyproject.toml, we only sort new group keys if the
// existing keys were sorted.
if was_sorted {
dependency_groups.sort_values();
}
// If `dependency-groups` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments