Merge user and workspace settings (#3462)

## Summary

This PR follows Cargo's strategy for merging configuration, albeit in a
more limited way (we don't support as many configuration locations).
Specifically, we merge the user configuration with the workspace
configuration if both are present. The workspace configuration has
priority, such that we take values from the workspace configuration and
ignore those in the user configuration if both are specified for a given
setting -- with the exception of arrays and maps, which are
concatenated.

For now, if a user provides a configuration file with `--config-file`,
we _don't_ merge in the user settings.

See:
https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure.

Closes #3420.
This commit is contained in:
Charlie Marsh 2024-05-08 14:49:43 -04:00 committed by GitHub
parent 74f53729d8
commit 1aa8ff8268
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 170 additions and 8 deletions

View file

@ -112,6 +112,42 @@ impl ConfigSettings {
pub fn escape_for_python(&self) -> String {
serde_json::to_string(self).expect("Failed to serialize config settings")
}
/// Merge two sets of config settings, with the values in `self` taking precedence.
#[must_use]
pub fn merge(self, other: ConfigSettings) -> ConfigSettings {
let mut config = self.0;
for (key, value) in other.0 {
match config.entry(key) {
Entry::Vacant(vacant) => {
vacant.insert(value);
}
Entry::Occupied(mut occupied) => match occupied.get_mut() {
ConfigSettingValue::String(existing) => {
let existing = existing.clone();
match value {
ConfigSettingValue::String(value) => {
occupied.insert(ConfigSettingValue::List(vec![existing, value]));
}
ConfigSettingValue::List(mut values) => {
values.insert(0, existing);
occupied.insert(ConfigSettingValue::List(values));
}
}
}
ConfigSettingValue::List(existing) => match value {
ConfigSettingValue::String(value) => {
existing.push(value);
}
ConfigSettingValue::List(values) => {
existing.extend(values);
}
},
},
}
}
Self(config)
}
}
impl serde::Serialize for ConfigSettings {