Files
peazyrsa/src/vars.rs
Dmitry 67f925f160
All checks were successful
Docker Image CI / test (push) Successful in 2m56s
Docker Image CI / push (push) Successful in 22m30s
remove unused code for vars
2024-10-28 11:35:18 +03:00

131 lines
4.0 KiB
Rust

use anyhow::{anyhow, Context, Result};
use regex::Regex;
use std::{path::PathBuf, pin::Pin};
use tokio::pin;
use crate::arcstr::ArcStr;
use crate::common::{read_file_by_lines, AppConfig};
use futures_util::stream::StreamExt;
use std::collections::BTreeMap;
use std::fmt::{Debug, Formatter};
use std::ops::Deref;
use std::path::Path;
pub(crate) type ArcVarsMap = BTreeMap<ArcStr, ArcStr>;
#[derive(Clone, PartialEq, Ord, PartialOrd, Eq)]
pub(crate) struct VarsMap(ArcVarsMap);
pub(crate) trait IStrMap {
fn get<S: AsRef<str> + Clone>(&self, key: &S) -> Option<&str>;
fn insert<S: AsRef<str> + Clone>(&mut self, key: S, value: S) -> Option<S>;
}
impl IStrMap for VarsMap {
fn get<S: AsRef<str> + Clone>(&self, key: &S) -> Option<&str> {
self.0.get(&ArcStr::from(key.as_ref())).map(|x| x.as_str())
}
fn insert<S: AsRef<str> + Clone>(&mut self, key: S, value: S) -> Option<S> {
let key = ArcStr::from(key.as_ref());
let value2 = ArcStr::from(value.clone().as_ref());
self.0.insert(key, value2).and(Some(value))
}
}
impl Deref for VarsMap {
type Target = BTreeMap<ArcStr, ArcStr>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Debug for VarsMap {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let debug_map: BTreeMap<_, _> =
self.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
debug_map.fmt(f)
}
}
pub(crate) struct VarsFile {
pub(crate) filepath: ArcStr,
pub(crate) encoding: ArcStr,
}
impl VarsFile {
async fn from_file<P>(filepath: P, encoding: ArcStr) -> Result<Self>
where
P: AsRef<Path>,
{
let filepath_str = filepath
.as_ref()
.to_str()
.ok_or(anyhow!("filepath to str"))?;
let metadata = tokio::fs::metadata(filepath_str)
.await
.context(format!("config file not found: {}", &filepath_str))?;
if !metadata.is_file() {
Err(anyhow!("config is not a file {}", &filepath_str))?;
}
Ok(VarsFile {
filepath: ArcStr::from(filepath_str),
encoding,
})
}
async fn from_dir<P>(dir: P, encoding: ArcStr) -> Result<Self>
where
P: AsRef<Path>,
{
let filepath = dir.as_ref().join("vars");
let err_context = "vars or vars.bat file not found";
match Self::from_file(&filepath, encoding.clone()).await {
Ok(res) => Ok(res),
Err(_) => Self::from_file(&filepath.with_extension("bat"), encoding.clone())
.await
.map_err(|e| e.context(err_context)),
}
}
pub(crate) async fn from_config(config: &AppConfig) -> Result<Self> {
Self::from_dir(
PathBuf::from(&config.base_directory),
ArcStr::from(config.encoding.as_str()),
)
.await
}
pub(crate) async fn parse(&self) -> Result<VarsMap> {
let mut result = ArcVarsMap::new();
result.insert("__file__".into(), self.filepath.clone());
result.insert("__encoding__".into(), self.encoding.clone());
let lines = read_file_by_lines(&self.filepath.as_path(), &self.encoding)
.await
.context("vars read error")?;
let lines = Pin::from(lines);
pin!(lines);
let re_v2 = Regex::new(r#"^(export|set)\s\b(?P<key>[\w\d_]+)\b=\s?"?(?P<value>[^#]+?)"?$"#)
.context("regex v2")
.context("re_v2 error")?;
let re_v3 = Regex::new(r"^set_var\s(?P<key1>[\w\d_]+)\s+(?P<value1>[^#]+?)$")
.context("regex v3")
.context("re_v3 error")?;
while let Some(line) = lines.next().await {
for re in [&re_v2, &re_v3].iter() {
if let Some(caps) = re.captures(line.as_str()) {
let [key, value] = [&caps["key"], &caps["value"]].map(ArcStr::from);
result.insert(key, value);
continue;
}
}
}
Ok(VarsMap(result))
}
}