Add kv_ filters

This commit is contained in:
Félix Saparelli 2023-04-08 20:01:40 +12:00
parent b641773473
commit e82a7dbc14
No known key found for this signature in database
3 changed files with 54 additions and 3 deletions

View File

@ -28,6 +28,7 @@ clap_mangen = "0.2.15"
clearscreen = "2.0.1"
dirs = "5.0.0"
futures = "0.3.29"
dashmap = "5.4.0"
humantime = "2.1.0"
is-terminal = "0.4.4"
jaq-core = "1.2.1"

View File

@ -808,8 +808,8 @@ pub struct Args {
/// - 'string | hash', and 'path | hashfile' return the hash of the string or file at path.
/// No guarantee is made about the algorithm used: treat it as an opaque value.
///
/// - 'any | store(key)', 'fetch(key)', and 'clear' provide a simple persistent key-value
/// store. Data is kept in memory only, there is no persistence between invocations.
/// - 'any | kv_store(key)', 'kv_fetch(key)', and 'kv_clear' provide a simple key-value store.
/// Data is kept in memory only, there is no persistence. Consistency is not guaranteed.
///
/// - 'any | printout', 'any | printerr', and 'any | log(level)' will print or log any given
/// value to stdout, stderr, or the log (levels = error, warn, info, debug, trace), and

View File

@ -1,5 +1,6 @@
use std::iter::once;
use std::{iter::once, sync::Arc};
use dashmap::DashMap;
use jaq_core::{CustomFilter, Definitions, Error, Val};
use miette::miette;
use tracing::{debug, error, info, trace, warn};
@ -120,5 +121,54 @@ pub fn load_watchexec_defs(defs: &mut Definitions) -> miette::Result<()> {
),
);
let kv: Arc<DashMap<String, Val>> = Arc::new(DashMap::new());
trace!("jaq: add kv_clear filter");
defs.insert_custom(
"kv_clear",
CustomFilter::new(0, {
let kv = kv.clone();
move |_, (_, val)| {
kv.clear();
Box::new(once(Ok(val)))
}
}),
);
trace!("jaq: add kv_store filter");
defs.insert_custom(
"kv_store",
CustomFilter::new(1, {
let kv = kv.clone();
move |args, (ctx, val)| {
let key = match string_arg!(args, 0, ctx, val) {
Ok(v) => v,
Err(e) => return_err!(Err(e)),
};
kv.insert(key, val.clone());
Box::new(once(Ok(val)))
}
}),
);
trace!("jaq: add kv_fetch filter");
defs.insert_custom(
"kv_fetch",
CustomFilter::new(1, {
move |args, (ctx, val)| {
let key = match string_arg!(args, 0, ctx, val) {
Ok(v) => v,
Err(e) => return_err!(Err(e)),
};
Box::new(once(Ok(kv
.get(&key)
.map(|val| val.clone())
.unwrap_or(Val::Null))))
}
}),
);
Ok(())
}