Skip to content

Commit dfd4e21

Browse files
committed
feat(operator): Add LabelExt trait
This trait enables adding one or multiple labels to any Kubernetes resource (through kube's ResourceExt trait).
1 parent be42204 commit dfd4e21

File tree

1 file changed

+57
-0
lines changed
  • crates/stackable-operator/src/kvp/label

1 file changed

+57
-0
lines changed

crates/stackable-operator/src/kvp/label/mod.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,63 @@ pub type LabelsError = KeyValuePairsError;
4242
/// of labels fails.
4343
pub type LabelError = KeyValuePairError<LabelValueError>;
4444

45+
/// Add [`Label`]s to any Kubernetes resource.
46+
///
47+
/// It should be noted, that after the addition of labels to the resource, the validity of keys and
48+
/// values **can no longer be enforced** as they are both stored as plain [`String`]s. To update a
49+
/// label use [`LabelExt::add_label`] which will update the label in place if it is already present.
50+
pub trait LabelExt
51+
where
52+
Self: ResourceExt,
53+
{
54+
/// Adds a single label to `self`.
55+
fn add_label(&mut self, label: Label) -> &mut Self;
56+
57+
/// Adds multiple labels to `self`.
58+
fn add_labels(&mut self, label: Labels) -> &mut Self;
59+
}
60+
61+
impl<T> LabelExt for T
62+
where
63+
T: ResourceExt,
64+
{
65+
fn add_label(&mut self, label: Label) -> &mut Self {
66+
let meta = self.meta_mut();
67+
68+
match &mut meta.labels {
69+
Some(labels) => {
70+
// TODO (@Techassi): Add an API to consume key and value
71+
let KeyValuePair { key, value } = label.into_inner();
72+
labels.insert(key.to_string(), value.to_string());
73+
}
74+
None => {
75+
let mut labels = BTreeMap::new();
76+
77+
// TODO (@Techassi): Add an API to consume key and value
78+
let KeyValuePair { key, value } = label.into_inner();
79+
labels.insert(key.to_string(), value.to_string());
80+
81+
meta.labels = Some(labels);
82+
}
83+
}
84+
85+
self
86+
}
87+
88+
fn add_labels(&mut self, labels: Labels) -> &mut Self {
89+
let meta = self.meta_mut();
90+
91+
match &mut meta.labels {
92+
Some(existing_labels) => {
93+
existing_labels.extend::<BTreeMap<String, String>>(labels.into())
94+
}
95+
None => meta.labels = Some(labels.into()),
96+
}
97+
98+
self
99+
}
100+
}
101+
45102
/// A specialized implementation of a key/value pair representing Kubernetes
46103
/// labels.
47104
///

0 commit comments

Comments
 (0)