fleetforge_common/
labels.rs

1use std::collections::HashMap;
2
3use serde_json::{Map, Value};
4
5/// Converts a string map into a JSON object for storage or API responses.
6pub fn labels_map_to_value(labels: &HashMap<String, String>) -> Value {
7    let mut map = Map::new();
8    for (key, value) in labels {
9        map.insert(key.clone(), Value::String(value.clone()));
10    }
11    Value::Object(map)
12}
13
14/// Parses a JSON object into a string map representation of labels.
15pub fn labels_value_to_map(value: &Value) -> HashMap<String, String> {
16    value
17        .as_object()
18        .map(|map| {
19            map.iter()
20                .filter_map(|(key, val)| val.as_str().map(|v| (key.clone(), v.to_string())))
21                .collect()
22        })
23        .unwrap_or_default()
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn round_trips_labels() {
32        let mut labels = HashMap::new();
33        labels.insert("team".to_string(), "core".to_string());
34        labels.insert("env".to_string(), "dev".to_string());
35
36        let value = labels_map_to_value(&labels);
37        let round_trip = labels_value_to_map(&value);
38
39        assert_eq!(labels, round_trip);
40    }
41}