use serde_json::Value;
enum Req {
Eq(String, String),
Ne(String, String),
In(String, Vec<String>),
NotIn(String, Vec<String>),
Exists(String),
NotExists(String),
}
#[derive(Default)]
pub struct Selector(Vec<Req>);
fn split_top(s: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0;
let mut start = 0;
for (i, c) in s.char_indices() {
match c {
'(' => depth += 1,
')' => depth -= 1,
',' if depth == 0 => {
out.push(&s[start..i]);
start = i + 1;
}
_ => {}
}
}
out.push(&s[start..]);
out.into_iter()
.map(str::trim)
.filter(|x| !x.is_empty())
.collect()
}
fn set(s: &str) -> Vec<String> {
s.trim()
.trim_start_matches('(')
.trim_end_matches(')')
.split(',')
.map(|x| x.trim().to_string())
.collect()
}
impl Selector {
pub fn parse(s: &str) -> Selector {
let mut reqs = Vec::new();
for part in split_top(s) {
if let Some((k, v)) = part.split_once("!=") {
reqs.push(Req::Ne(k.trim().into(), v.trim().into()));
} else if let Some((k, v)) = part.split_once("==") {
reqs.push(Req::Eq(k.trim().into(), v.trim().into()));
} else if let Some((k, v)) = part.split_once('=') {
reqs.push(Req::Eq(k.trim().into(), v.trim().into()));
} else if let Some((k, v)) = part.split_once(" notin ") {
reqs.push(Req::NotIn(k.trim().into(), set(v)));
} else if let Some((k, v)) = part.split_once(" in ") {
reqs.push(Req::In(k.trim().into(), set(v)));
} else if let Some(k) = part.strip_prefix('!') {
reqs.push(Req::NotExists(k.trim().into()));
} else {
reqs.push(Req::Exists(part.into()));
}
}
Selector(reqs)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn matches_labels(&self, obj: &Value) -> bool {
let labels = obj.pointer("/metadata/labels");
let get = |k: &str| labels.and_then(|l| l.get(k)).and_then(Value::as_str);
self.0.iter().all(|r| match r {
Req::Eq(k, v) => get(k) == Some(v),
Req::Ne(k, v) => get(k) != Some(v.as_str()),
Req::In(k, vs) => get(k).is_some_and(|x| vs.iter().any(|v| v == x)),
Req::NotIn(k, vs) => get(k).is_none_or(|x| !vs.iter().any(|v| v == x)),
Req::Exists(k) => get(k).is_some(),
Req::NotExists(k) => get(k).is_none(),
})
}
pub fn matches_fields(&self, obj: &Value) -> bool {
let get = |path: &str| {
let mut cur = obj;
for seg in path.split('.') {
cur = cur.get(seg)?;
}
Some(match cur {
Value::String(s) => s.clone(),
other => other.to_string(),
})
};
self.0.iter().all(|r| match r {
Req::Eq(k, v) => get(k).unwrap_or_default() == *v,
Req::Ne(k, v) => get(k).unwrap_or_default() != *v,
_ => true,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn labels() {
let o = json!({"metadata":{"labels":{"app":"web","tier":"fe"}}});
assert!(Selector::parse("app=web,tier in (fe,be)").matches_labels(&o));
assert!(!Selector::parse("app!=web").matches_labels(&o));
assert!(Selector::parse("!x,app").matches_labels(&o));
assert!(Selector::parse("tier notin (be)").matches_labels(&o));
}
#[test]
fn fields() {
let o =
json!({"metadata":{"name":"a"},"status":{"phase":"Running"},"spec":{"nodeName":"n1"}});
assert!(Selector::parse("spec.nodeName=n1,status.phase!=Succeeded").matches_fields(&o));
assert!(!Selector::parse("metadata.name=b").matches_fields(&o));
}
}