Skip to content

Commit

Permalink
marked-yaml: Support forcing lowercased mapping keys
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Silverstone <dsilvers@digital-scurf.org>
  • Loading branch information
kinnison committed Jun 21, 2024
1 parent 61291df commit ced07e6
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions marked-yaml/src/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub struct LoaderOptions {
error_on_duplicate_keys: bool,
prevent_coercion: bool,
toplevel_is_mapping: bool,
lowercase_keys: bool,
}

impl Default for LoaderOptions {
Expand All @@ -60,6 +61,7 @@ impl Default for LoaderOptions {
error_on_duplicate_keys: false,
prevent_coercion: false,
toplevel_is_mapping: true,
lowercase_keys: false,
}
}
}
Expand Down Expand Up @@ -106,6 +108,17 @@ impl LoaderOptions {
..self
}
}

/// Whether or not to force-lowercase mapping keys when loading
///
/// By default, the loader will leave key names alone, but in some
/// cases it can be preferable to normalise them to lowercase
pub fn lowercase_keys(self, force_lowercase: bool) -> Self {
Self {
lowercase_keys: force_lowercase,
..self
}
}
}

impl Display for LoadError {
Expand Down Expand Up @@ -335,6 +348,13 @@ impl MarkedEventReceiver for MarkedLoader {
Error(LoadError::UnexpectedTag(mark))
} else {
let span = Span::new_start(mark);
let val = if matches!(curstate, MappingWaitingOnKey(_, _))
&& self.options.lowercase_keys
{
val.to_lowercase()
} else {
val
};
let mut node = MarkedScalarNode::new(span, val);
if self.options.prevent_coercion {
node.set_coerce(matches!(kind, TScalarStyle::Plain));
Expand Down Expand Up @@ -636,4 +656,25 @@ mod test {
Err(LoadError::TopLevelMustBeSequence(Marker::new(0, 1, 1)))
);
}

#[test]
fn lowercase_keys() {
let node = parse_yaml_with_options(
0,
"KEY: VALUE",
LoaderOptions::default().lowercase_keys(false),
)
.unwrap();
assert!(node.as_mapping().unwrap().contains_key("KEY"));
assert!(!node.as_mapping().unwrap().contains_key("key"));

let node = parse_yaml_with_options(
0,
"KEY: VALUE",
LoaderOptions::default().lowercase_keys(true),
)
.unwrap();
assert!(!node.as_mapping().unwrap().contains_key("KEY"));
assert!(node.as_mapping().unwrap().contains_key("key"));
}
}

0 comments on commit ced07e6

Please sign in to comment.