use std::cell::RefCell;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use once_cell::sync::Lazy;
use serde::Serialize;
#[cfg(feature = "redactions")]
use crate::{
content::Content,
redaction::{dynamic_redaction, sorted_redaction, ContentPath, Redaction, Selector},
};
static DEFAULT_SETTINGS: Lazy<Arc<ActualSettings>> = Lazy::new(|| {
Arc::new(ActualSettings {
sort_maps: false,
snapshot_path: "snapshots".into(),
snapshot_suffix: "".into(),
input_file: None,
description: None,
info: None,
omit_expression: false,
prepend_module_to_snapshot: true,
#[cfg(feature = "redactions")]
redactions: Redactions::default(),
#[cfg(feature = "glob")]
allow_empty_glob: false,
})
});
thread_local!(static CURRENT_SETTINGS: RefCell<Settings> = RefCell::new(Settings::new()));
#[cfg(feature = "redactions")]
#[derive(Clone, Default)]
pub struct Redactions(Vec<(Selector<'static>, Arc<Redaction>)>);
#[cfg(feature = "redactions")]
impl<'a> From<Vec<(&'a str, Redaction)>> for Redactions {
fn from(value: Vec<(&'a str, Redaction)>) -> Redactions {
Redactions(
value
.into_iter()
.map(|x| (Selector::parse(x.0).unwrap().make_static(), Arc::new(x.1)))
.collect(),
)
}
}
#[derive(Clone)]
#[doc(hidden)]
pub struct ActualSettings {
pub sort_maps: bool,
pub snapshot_path: PathBuf,
pub snapshot_suffix: String,
pub input_file: Option<PathBuf>,
pub description: Option<String>,
pub info: Option<serde_yaml::Value>,
pub omit_expression: bool,
pub prepend_module_to_snapshot: bool,
#[cfg(feature = "redactions")]
pub redactions: Redactions,
#[cfg(feature = "glob")]
pub allow_empty_glob: bool,
}
impl ActualSettings {
pub fn sort_maps(&mut self, value: bool) {
self.sort_maps = value;
}
pub fn snapshot_path<P: AsRef<Path>>(&mut self, path: P) {
self.snapshot_path = path.as_ref().to_path_buf();
}
pub fn snapshot_suffix<I: Into<String>>(&mut self, suffix: I) {
self.snapshot_suffix = suffix.into();
}
pub fn input_file<P: AsRef<Path>>(&mut self, p: P) {
self.input_file = Some(p.as_ref().to_path_buf());
}
pub fn description<S: Into<String>>(&mut self, value: S) {
self.description = Some(value.into());
}
pub fn info<S: Serialize>(&mut self, value: &S) {
self.info = Some(serde_yaml::to_value(value).unwrap());
}
pub fn omit_expression(&mut self, value: bool) {
self.omit_expression = value;
}
pub fn prepend_module_to_snapshot(&mut self, value: bool) {
self.prepend_module_to_snapshot = value;
}
#[cfg(feature = "redactions")]
pub fn redactions<R: Into<Redactions>>(&mut self, r: R) {
self.redactions = r.into();
}
#[cfg(feature = "glob")]
pub fn allow_empty_glob(&mut self, value: bool) {
self.allow_empty_glob = value;
}
}
#[derive(Clone)]
pub struct Settings {
inner: Arc<ActualSettings>,
}
impl Default for Settings {
fn default() -> Settings {
Settings {
inner: DEFAULT_SETTINGS.clone(),
}
}
}
impl Settings {
pub fn new() -> Settings {
Settings::default()
}
pub fn clone_current() -> Settings {
Settings::with(|x| x.clone())
}
#[doc(hidden)]
pub fn _private_inner_mut(&mut self) -> &mut ActualSettings {
Arc::make_mut(&mut self.inner)
}
pub fn set_sort_maps(&mut self, value: bool) {
self._private_inner_mut().sort_maps = value;
}
pub fn sort_maps(&self) -> bool {
self.inner.sort_maps
}
pub fn set_prepend_module_to_snapshot(&mut self, value: bool) {
self._private_inner_mut().prepend_module_to_snapshot(value);
}
pub fn prepend_module_to_snapshot(&self) -> bool {
self.inner.prepend_module_to_snapshot
}
#[cfg(feature = "glob")]
pub fn set_allow_empty_glob(&mut self, value: bool) {
self._private_inner_mut().allow_empty_glob(value);
}
#[cfg(feature = "glob")]
pub fn allow_empty_glob(&self) -> bool {
self.inner.allow_empty_glob
}
pub fn set_snapshot_suffix<I: Into<String>>(&mut self, suffix: I) {
self._private_inner_mut().snapshot_suffix(suffix);
}
pub fn remove_snapshot_suffix(&mut self) {
self.set_snapshot_suffix("");
}
pub fn snapshot_suffix(&self) -> Option<&str> {
if self.inner.snapshot_suffix.is_empty() {
None
} else {
Some(&self.inner.snapshot_suffix)
}
}
pub fn set_input_file<P: AsRef<Path>>(&mut self, p: P) {
self._private_inner_mut().input_file(p);
}
pub fn remove_input_file(&mut self) {
self._private_inner_mut().input_file = None;
}
pub fn input_file(&self) -> Option<&Path> {
self.inner.input_file.as_deref()
}
pub fn set_description<S: Into<String>>(&mut self, value: S) {
self._private_inner_mut().description(value);
}
pub fn remove_description(&mut self) {
self._private_inner_mut().description = None;
}
pub fn description(&self) -> Option<&str> {
self.inner.description.as_deref()
}
pub fn set_info<S: Serialize>(&mut self, value: &S) {
self._private_inner_mut().info(value);
}
pub fn remove_info(&mut self) {
self._private_inner_mut().info = None;
}
pub(crate) fn info(&self) -> Option<serde_yaml::Value> {
self.inner.info.clone()
}
pub fn has_info(&self) -> bool {
self.inner.info.is_some()
}
pub fn set_omit_expression(&mut self, value: bool) {
self._private_inner_mut().omit_expression(value);
}
pub fn omit_expression(&self) -> bool {
self.inner.omit_expression
}
#[cfg(feature = "redactions")]
pub fn add_redaction<R: Into<Redaction>>(&mut self, selector: &str, replacement: R) {
self._private_inner_mut().redactions.0.push((
Selector::parse(selector).unwrap().make_static(),
Arc::new(replacement.into()),
));
}
#[cfg(feature = "redactions")]
pub fn add_dynamic_redaction<I, F>(&mut self, selector: &str, func: F)
where
I: Into<Content>,
F: Fn(Content, ContentPath<'_>) -> I + Send + Sync + 'static,
{
self.add_redaction(selector, dynamic_redaction(func));
}
#[cfg(feature = "redactions")]
pub fn sort_selector(&mut self, selector: &str) {
self.add_redaction(selector, sorted_redaction());
}
#[cfg(feature = "redactions")]
pub fn set_redactions<R: Into<Redactions>>(&mut self, redactions: R) {
self._private_inner_mut().redactions = redactions.into();
}
#[cfg(feature = "redactions")]
pub fn clear_redactions(&mut self) {
self._private_inner_mut().redactions.0.clear();
}
#[cfg(feature = "redactions")]
pub(crate) fn iter_redactions(&self) -> impl Iterator<Item = (&Selector, &Redaction)> {
self.inner
.redactions
.0
.iter()
.map(|&(ref a, ref b)| (a, &**b))
}
pub fn set_snapshot_path<P: AsRef<Path>>(&mut self, path: P) {
self._private_inner_mut().snapshot_path(path);
}
pub fn snapshot_path(&self) -> &Path {
&self.inner.snapshot_path
}
pub fn bind<F: FnOnce()>(&self, f: F) {
CURRENT_SETTINGS.with(|x| {
let old = {
let mut current = x.borrow_mut();
let old = current.inner.clone();
current.inner = self.inner.clone();
old
};
f();
let mut current = x.borrow_mut();
current.inner = old;
})
}
pub fn bind_async<F: Future<Output = T>, T>(&self, future: F) -> impl Future<Output = T> {
struct BindingFuture<F>(Arc<ActualSettings>, F);
impl<F: Future> Future for BindingFuture<F> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let inner = self.0.clone();
let future = unsafe { self.map_unchecked_mut(|s| &mut s.1) };
CURRENT_SETTINGS.with(|x| {
let old = {
let mut current = x.borrow_mut();
let old = current.inner.clone();
current.inner = inner;
old
};
let rv = future.poll(cx);
let mut current = x.borrow_mut();
current.inner = old;
rv
})
}
}
BindingFuture(self.inner.clone(), future)
}
pub fn bind_to_thread(&self) {
CURRENT_SETTINGS.with(|x| {
x.borrow_mut().inner = self.inner.clone();
})
}
pub(crate) fn with<R, F: FnOnce(&Settings) -> R>(f: F) -> R {
CURRENT_SETTINGS.with(|x| f(&*x.borrow()))
}
}