Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement glob builtins #58

Merged
merged 1 commit into from
Sep 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions crates/burrego/src/opa/builtins/glob.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use anyhow::{anyhow, Result};

pub fn quote_meta(args: &[serde_json::Value]) -> Result<serde_json::Value> {
if args.len() != 1 {
return Err(anyhow!("glob.quote_meta: wrong number of arguments"));
}

let input = args[0]
.as_str()
.ok_or_else(|| anyhow!("glob.quote_meta: 1st parameter is not a string"))?;

serde_json::to_value(escape(input))
.map_err(|e| anyhow!("glob.quote_meta: cannot convert value into JSON: {:?}", e))
}

fn escape(s: &str) -> String {
let mut escaped = String::new();
for c in s.chars() {
match c {
'*' | '?' | '\\' | '[' | ']' | '{' | '}' => {
escaped.push('\\');
escaped.push(c);
}
c => {
escaped.push(c);
}
}
}
escaped
}

#[cfg(test)]
mod test {
#[test]
fn escape() {
assert_eq!(super::escape("*.domain.com"), r"\*.domain.com",);

assert_eq!(super::escape("*.domain-*.com"), r"\*.domain-\*.com",);

assert_eq!(super::escape("domain.com"), r"domain.com",);

assert_eq!(super::escape("domain-[ab].com"), r"domain-\[ab\].com",);

assert_eq!(super::escape("nie?ce"), r"nie\?ce",);
}
}
4 changes: 4 additions & 0 deletions crates/burrego/src/opa/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::collections::HashMap;

pub mod debugging;
pub mod encoding;
pub mod glob;
pub mod regex;
pub mod semver;
pub mod strings;
Expand Down Expand Up @@ -31,6 +32,9 @@ pub fn get_builtins() -> BuiltinFunctionsMap {
functions.insert("hex.encode", encoding::hex::encode);
functions.insert("hex.decode", encoding::hex::decode);

// glob
functions.insert("glob.quote_meta", glob::quote_meta);

// regex
functions.insert("regex.split", regex::split);
functions.insert("regex.template_match", regex::template_match);
Expand Down