punktf_lib/profile/
variables.rs

1//! User defined variables used by [profiles](`crate::profile::Profile`) and
2//! [dotfiles](`crate::profile::dotfile::Dotfile`).
3
4use std::collections::HashMap;
5use std::ops::Deref;
6
7use serde::{Deserialize, Serialize};
8
9/// Variables that replace values in templates
10pub trait Vars {
11	/// Get a variable by name
12	fn var<K: AsRef<str>>(&self, key: K) -> Option<&str>;
13}
14
15/// User defined variables
16#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17pub struct Variables {
18	/// User defined variables with a name and value.
19	#[serde(flatten)]
20	pub inner: HashMap<String, String>,
21}
22
23impl Vars for Variables {
24	fn var<K>(&self, key: K) -> Option<&str>
25	where
26		K: AsRef<str>,
27	{
28		self.inner.get(key.as_ref()).map(|value| value.deref())
29	}
30}
31
32impl Variables {
33	/// Creates a new instance from an iterator over key, value tuples.
34	pub fn from_items<K, V, I, II>(iter: II) -> Self
35	where
36		K: Into<String>,
37		V: Into<String>,
38		I: Iterator<Item = (K, V)>,
39		II: IntoIterator<IntoIter = I, Item = (K, V)>,
40	{
41		let inner = iter
42			.into_iter()
43			.map(|(k, v)| (k.into(), v.into()))
44			.collect();
45
46		Self { inner }
47	}
48}