vars with Arc<str>
This commit is contained in:
134
src/vars.rs
134
src/vars.rs
@@ -3,38 +3,95 @@ 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;
|
||||
|
||||
use crate::common::{read_file_by_lines, AppConfig, VarsMap};
|
||||
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 VarsMap {
|
||||
pub(crate) fn filepath(&self) -> Option<&str> {
|
||||
self.get(&"__file__")
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn encoding(&self) -> Option<&str> {
|
||||
self.get(&"__encoding__")
|
||||
}
|
||||
}
|
||||
|
||||
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: PathBuf,
|
||||
pub(crate) vars: Option<VarsMap>,
|
||||
pub(crate) encoding: String,
|
||||
pub(crate) filepath: ArcStr,
|
||||
pub(crate) encoding: ArcStr,
|
||||
}
|
||||
|
||||
impl VarsFile {
|
||||
async fn from_file(filepath: &PathBuf, encoding: String) -> Result<Self> {
|
||||
let metadata = tokio::fs::metadata(&filepath).await.context(format!(
|
||||
"file not found {}",
|
||||
filepath.to_str().expect("str")
|
||||
))?;
|
||||
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!("{} is not a file", filepath.to_str().expect("str")))?
|
||||
Err(anyhow!("config is not a file {}", &filepath_str))?;
|
||||
}
|
||||
Ok(VarsFile {
|
||||
filepath: filepath.to_path_buf(),
|
||||
vars: None,
|
||||
filepath: ArcStr::from(filepath_str),
|
||||
encoding,
|
||||
})
|
||||
}
|
||||
|
||||
async fn from_dir(dir: PathBuf, encoding: String) -> Result<Self> {
|
||||
let filepath = dir.join("vars");
|
||||
let err_context = format!(
|
||||
"vars or vars.bat file not found in {}",
|
||||
dir.to_str().expect("str")
|
||||
);
|
||||
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),
|
||||
@@ -47,35 +104,38 @@ impl VarsFile {
|
||||
pub(crate) async fn from_config(config: &AppConfig) -> Result<Self> {
|
||||
Self::from_dir(
|
||||
PathBuf::from(&config.base_directory),
|
||||
config.encoding.clone(),
|
||||
ArcStr::from(config.encoding.as_str()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn parse(&mut self) -> Result<()> {
|
||||
let mut result = VarsMap::new();
|
||||
let lines = read_file_by_lines(&self.filepath, &self.encoding).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")?;
|
||||
let re_v3 = Regex::new(r"^set_var\s(?P<key1>[\w\d_]+)\s+(?P<value1>[^\#]+?)$")
|
||||
.context("regex v3")?;
|
||||
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 {
|
||||
if let Some(caps) = re_v2.captures(line.as_str()) {
|
||||
result.insert(caps["key"].to_string(), caps["value"].to_string());
|
||||
continue;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(caps) = re_v3.captures(line.as_str()) {
|
||||
result.insert(caps["key"].to_string(), caps["value"].to_string());
|
||||
};
|
||||
}
|
||||
|
||||
self.vars = Some(result);
|
||||
Ok(())
|
||||
Ok(VarsMap(result))
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user