Compare commits

..

5 Commits

Author SHA1 Message Date
67f925f160
remove unused code for vars
All checks were successful
Docker Image CI / test (push) Successful in 2m56s
Docker Image CI / push (push) Successful in 22m30s
2024-10-28 11:35:18 +03:00
7a22af7598
vars with Arc<str>
All checks were successful
Docker Image CI / test (push) Successful in 3m0s
Docker Image CI / push (push) Successful in 21m33s
2024-10-28 00:43:18 +03:00
73435ae70a
ignore /.idea
Some checks failed
Docker Image CI / test (push) Successful in 3m10s
Docker Image CI / push (push) Failing after 11m32s
2024-10-27 20:19:57 +03:00
9bf2103c47
app config refactor
All checks were successful
Docker Image CI / test (push) Successful in 3m26s
Docker Image CI / push (push) Successful in 22m31s
2024-10-25 12:02:53 +03:00
1179840114
arg --openssl to --with-openssl
All checks were successful
Docker Image CI / test (push) Successful in 3m3s
Docker Image CI / push (push) Successful in 22m24s
2024-10-25 10:43:07 +03:00
8 changed files with 267 additions and 172 deletions

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
/target /target
/.env.ps1 /.env.ps1
/.vscode /.vscode
/.idea

69
src/arcstr.rs Normal file
View File

@ -0,0 +1,69 @@
use std::ffi::OsStr;
use std::fmt::{Display, Formatter};
use std::ops::Deref;
use std::path::Path;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Ord, PartialOrd, Eq)]
pub(crate) struct ArcStr {
inner: Arc<str>,
}
impl Deref for ArcStr {
type Target = str;
fn deref(&self) -> &Self::Target {
self.inner.deref()
}
}
impl From<&str> for ArcStr {
fn from(value: &str) -> Self {
Self {
inner: Arc::from(value),
}
}
}
#[allow(suspicious_double_ref_op)]
impl From<&&str> for ArcStr {
fn from(value: &&str) -> Self {
Self {
inner: Arc::from(value.deref()),
}
}
}
impl AsRef<OsStr> for ArcStr {
fn as_ref(&self) -> &OsStr {
self.inner.as_ref().as_ref()
}
}
impl AsRef<Path> for ArcStr {
fn as_ref(&self) -> &Path {
self.inner.as_ref().as_ref()
}
}
impl AsRef<ArcStr> for ArcStr {
fn as_ref(&self) -> &ArcStr {
self
}
}
impl Display for ArcStr {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.deref())
}
}
impl ArcStr {
pub(crate) fn as_path(&self) -> &Path {
self.as_ref()
}
pub(crate) fn as_str(&self) -> &str {
self.inner.deref()
}
}

View File

@ -20,19 +20,12 @@ where
T: ICryptoProvider, T: ICryptoProvider,
{ {
pub(crate) fn new(cfg: &AppConfig, provider: T) -> Self { pub(crate) fn new(cfg: &AppConfig, provider: T) -> Self {
let base_dir = PathBuf::from(&cfg.base_directory);
let keys_dir = base_dir.clone().join(cfg.keys_subdir.clone());
let name = cfg.name.clone();
let ca_file = keys_dir.join(cfg.ca_filename.clone());
let key_file = keys_dir.join(format!("{}.key", &name));
let cert_file = keys_dir.join(format!("{}.crt", &name));
let provider = Arc::new(provider); let provider = Arc::new(provider);
Certs { Certs {
ca_file, ca_file: cfg.ca_filepath.clone(),
key_file, key_file: cfg.key_filepath.clone(),
cert_file, cert_file: cfg.cert_filepath.clone(),
provider, provider,
} }
} }

View File

@ -3,10 +3,8 @@ use async_stream::stream;
use clap::Parser; use clap::Parser;
use encoding::{label::encoding_from_whatwg_label, EncoderTrap}; use encoding::{label::encoding_from_whatwg_label, EncoderTrap};
use std::{ use std::{
collections::BTreeMap,
fmt::Display, fmt::Display,
path::{Path, PathBuf}, path::{Path, PathBuf},
str::FromStr,
}; };
use tokio::{ use tokio::{
fs::{self, File}, fs::{self, File},
@ -15,10 +13,8 @@ use tokio::{
use futures_core::stream::Stream; use futures_core::stream::Stream;
pub(crate) type VarsMap = BTreeMap<String, String>;
pub(crate) const UTF8_STR: &str = "utf8"; pub(crate) const UTF8_STR: &str = "utf8";
pub(crate) const DEFAULT_ENCODING: &str = "cp866"; // .bat pub(crate) const DEFAULT_ENCODING: &str = UTF8_STR;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum OpenSSLProviderArg { pub enum OpenSSLProviderArg {
@ -26,12 +22,11 @@ pub enum OpenSSLProviderArg {
ExternalBin(String), ExternalBin(String),
} }
impl FromStr for OpenSSLProviderArg { impl From<Option<&String>> for OpenSSLProviderArg {
type Err = anyhow::Error; fn from(value: Option<&String>) -> Self {
fn from_str(s: &str) -> Result<Self, Self::Err> { match value {
match s.to_ascii_lowercase().as_str() { Some(x) => OpenSSLProviderArg::ExternalBin(x.clone()),
"internal" => Ok(OpenSSLProviderArg::Internal), _ => OpenSSLProviderArg::Internal,
x => Ok(OpenSSLProviderArg::ExternalBin(x.to_string())),
} }
} }
} }
@ -75,9 +70,9 @@ pub(crate) struct Args {
#[arg(long, default_value = "3650")] #[arg(long, default_value = "3650")]
pub(crate) days: u32, pub(crate) days: u32,
/// openssl binary or (internal) /// use openssl binary
#[arg(long, short, default_value = "internal")] #[arg(long = "with-openssl", short)]
pub(crate) openssl: OpenSSLProviderArg, pub(crate) openssl: Option<String>,
/// template file /// template file
#[arg(long, default_value = "template.ovpn")] #[arg(long, default_value = "template.ovpn")]
@ -87,35 +82,54 @@ pub(crate) struct Args {
pub(crate) struct AppConfig { pub(crate) struct AppConfig {
pub(crate) encoding: String, pub(crate) encoding: String,
pub(crate) req_days: u32, pub(crate) req_days: u32,
pub(crate) keys_subdir: String, pub(crate) template_file: PathBuf,
pub(crate) config_subdir: String,
pub(crate) template_file: String,
pub(crate) openssl_default_cnf: String, pub(crate) openssl_default_cnf: String,
pub(crate) openssl_cnf_env: String, pub(crate) openssl_cnf_env: String,
pub(crate) ca_filename: String, pub(crate) ca_filepath: PathBuf,
pub(crate) ca_key_filepath: PathBuf,
pub(crate) default_email_domain: String, pub(crate) default_email_domain: String,
pub(crate) openssl: OpenSSLProviderArg, pub(crate) openssl: OpenSSLProviderArg,
pub(crate) base_directory: String, pub(crate) base_directory: PathBuf,
pub(crate) email: String, pub(crate) email: String,
pub(crate) name: String, pub(crate) name: String,
pub(crate) conf_filepath: PathBuf,
pub(crate) req_filepath: PathBuf,
pub(crate) key_filepath: PathBuf,
pub(crate) cert_filepath: PathBuf,
} }
impl Default for AppConfig { impl Default for AppConfig {
fn default() -> Self { fn default() -> Self {
let name = String::from("user");
let base_directory: PathBuf = ".".into();
let keys_directory = base_directory.join("keys");
let config_directory = base_directory.join("config");
let template_file = base_directory.join("template.ovpn");
let openssl_default_cnf = String::from("openssl-1.0.0.cnf");
let ca_filepath = keys_directory.join("ca.crt");
let ca_key_filepath = keys_directory.join("ca.key");
let req_filepath = keys_directory.join(format!("{}.csr", &name));
let key_filepath = keys_directory.join(format!("{}.key", &name));
let cert_filepath = keys_directory.join(format!("{}.crt", &name));
let conf_filepath = config_directory.join(format!("{}.ovpn", &name));
Self { Self {
encoding: DEFAULT_ENCODING.into(), encoding: DEFAULT_ENCODING.into(),
req_days: 30650, req_days: 30650,
keys_subdir: "keys".into(), template_file,
config_subdir: "config".into(), conf_filepath,
template_file: "template.ovpn".into(), req_filepath,
openssl_default_cnf: "openssl-1.0.0.cnf".into(), key_filepath,
cert_filepath,
openssl_default_cnf,
openssl_cnf_env: "KEY_CONFIG".into(), openssl_cnf_env: "KEY_CONFIG".into(),
ca_filename: "ca.crt".into(), ca_filepath,
ca_key_filepath,
default_email_domain: "example.com".into(), default_email_domain: "example.com".into(),
openssl: OpenSSLProviderArg::Internal, openssl: OpenSSLProviderArg::Internal,
base_directory: ".".into(), base_directory,
email: "name@example.com".into(), email: "name@example.com".into(),
name: "user".into(), name,
} }
} }
} }
@ -124,11 +138,25 @@ impl From<&Args> for AppConfig {
fn from(args: &Args) -> Self { fn from(args: &Args) -> Self {
let defaults = Self::default(); let defaults = Self::default();
let name = args.name.clone();
let base_directory = args let base_directory = args
.directory .directory
.as_ref() .as_ref()
.unwrap_or(&defaults.base_directory) .map(PathBuf::from)
.unwrap_or(defaults.base_directory)
.clone(); .clone();
let keys_directory = base_directory.join(&args.keys_dir);
let config_directory = base_directory.join(&args.config_dir);
let template_file = base_directory.join(&args.template_file);
let openssl_default_cnf = String::from("openssl-1.0.0.cnf");
let ca_filepath = keys_directory.join("ca.crt");
let ca_key_filepath = keys_directory.join("ca.key");
let req_filepath = keys_directory.join(format!("{}.csr", &name));
let key_filepath = keys_directory.join(format!("{}.key", &name));
let cert_filepath = keys_directory.join(format!("{}.crt", &name));
let conf_filepath = config_directory.join(format!("{}.ovpn", &name));
let email = args.email.clone().unwrap_or(format!( let email = args.email.clone().unwrap_or(format!(
"{}@{}", "{}@{}",
&args.name, &args.name,
@ -140,38 +168,34 @@ impl From<&Args> for AppConfig {
defaults.encoding.clone() defaults.encoding.clone()
}; };
let name = args.name.clone(); let name = args.name.clone();
let openssl = args.openssl.clone(); let openssl: OpenSSLProviderArg = args.openssl.as_ref().into();
let template_file = args.template_file.clone();
let req_days = args.days; let req_days = args.days;
let keys_subdir = args.keys_dir.clone();
let config_subdir = args.config_dir.clone();
Self { Self {
base_directory, base_directory,
template_file,
openssl_default_cnf,
ca_filepath,
ca_key_filepath,
req_filepath,
key_filepath,
cert_filepath,
conf_filepath,
email, email,
encoding, encoding,
name, name,
openssl, openssl,
template_file,
req_days, req_days,
keys_subdir,
config_subdir,
..defaults ..defaults
} }
} }
} }
pub(crate) async fn is_file_exist(filepath: &PathBuf) -> bool { pub(crate) async fn is_file_exist(filepath: &PathBuf) -> bool {
let metadata = tokio::fs::metadata(&filepath).await; match tokio::fs::metadata(&filepath).await {
if metadata.is_err() { Ok(x) => x.is_file(),
return false; _ => false,
} }
if !metadata.unwrap().is_file() {
return false;
}
true
} }
pub(crate) async fn read_file<P>(filepath: P, encoding: &str) -> Result<String> pub(crate) async fn read_file<P>(filepath: P, encoding: &str) -> Result<String>
@ -202,7 +226,7 @@ pub(crate) async fn write_file<P: AsRef<Path>>(
let enc = encoding_from_whatwg_label(encoding).ok_or(anyhow!("encoding not found"))?; let enc = encoding_from_whatwg_label(encoding).ok_or(anyhow!("encoding not found"))?;
let mut bytes = Vec::new(); let mut bytes = Vec::new();
enc.encode_to(text, EncoderTrap::Ignore, &mut bytes) enc.encode_to(text, EncoderTrap::Ignore, &mut bytes)
.map_err(|_| anyhow!("can't encode"))?; .map_err(|e| anyhow!("can't encode: {:?}", e))?;
fs::write(filepath, bytes).await.context("can't write file") fs::write(filepath, bytes).await.context("can't write file")
} }

View File

@ -1,10 +1,9 @@
use std::path::PathBuf; use anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, Ok, Result};
use clap::Parser; use clap::Parser;
use common::{is_file_exist, OpenSSLProviderArg, VarsMap}; use common::{is_file_exist, OpenSSLProviderArg};
use crypto_provider::ICryptoProvider; use crypto_provider::ICryptoProvider;
mod arcstr;
mod certs; mod certs;
mod common; mod common;
mod crypto_provider; mod crypto_provider;
@ -16,13 +15,10 @@ use crate::certs::Certs;
use crate::common::{AppConfig, Args}; use crate::common::{AppConfig, Args};
use crate::openssl::{external::OpenSSLExternalProvider, internal::OpenSSLInternalProvider}; use crate::openssl::{external::OpenSSLExternalProvider, internal::OpenSSLInternalProvider};
use crate::ovpn::OvpnConfig; use crate::ovpn::OvpnConfig;
use crate::vars::VarsFile; use crate::vars::{VarsFile, VarsMap};
async fn build_client_with<T: ICryptoProvider>(config: &AppConfig, provider: T) -> Result<String> { async fn build_client_with<T: ICryptoProvider>(config: &AppConfig, provider: T) -> Result<String> {
let name = config.name.clone(); let config_file = config.conf_filepath.clone();
let base_dir = PathBuf::from(&config.base_directory);
let config_dir = base_dir.join(&config.config_subdir);
let config_file = config_dir.join(format!("{}.ovpn", &name));
let config_file_str = config_file let config_file_str = config_file
.to_str() .to_str()
.ok_or(anyhow!("config file exist err"))? .ok_or(anyhow!("config file exist err"))?
@ -59,15 +55,16 @@ async fn build_client_config(config: &AppConfig, vars: VarsMap) -> Result<String
async fn main() -> Result<()> { async fn main() -> Result<()> {
let args = Args::parse(); let args = Args::parse();
let config = AppConfig::from(&args); let config = AppConfig::from(&args);
let mut vars = VarsFile::from_config(&config).await?; let vars = VarsFile::from_config(&config)
vars.parse().await?; .await
.context("vars from config")?
.parse()
.await
.context("parse vars")?;
println!("found vars: {}", vars.filepath.to_str().expect("fff")); println!("loaded: {:#?}", &vars);
println!("loaded: {:#?}", &vars.vars);
let vars = vars.vars.ok_or(anyhow!("no vars loaded"))?;
let config_file = build_client_config(&config, vars).await?; let config_file = build_client_config(&config, vars).await?;
println!("created: {}", &config_file); println!("created: {}", &config_file);
Ok(()) Ok(())

View File

@ -1,10 +1,12 @@
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use std::ops::Deref;
use std::path::PathBuf; use std::path::PathBuf;
use tokio::process::Command; use tokio::process::Command;
use crate::common::{is_file_exist, AppConfig, VarsMap}; use crate::common::{is_file_exist, AppConfig};
use crate::crypto_provider::ICryptoProvider; use crate::crypto_provider::ICryptoProvider;
use crate::vars::{IStrMap, VarsMap};
pub(crate) struct OpenSSLExternalProvider { pub(crate) struct OpenSSLExternalProvider {
vars: VarsMap, vars: VarsMap,
@ -33,18 +35,12 @@ impl OpenSSLExternalProvider {
pub(crate) fn from_cfg(cfg: &AppConfig, vars: VarsMap) -> Self { pub(crate) fn from_cfg(cfg: &AppConfig, vars: VarsMap) -> Self {
let base_dir = PathBuf::from(&cfg.base_directory); let base_dir = PathBuf::from(&cfg.base_directory);
let keys_dir = base_dir.join(&cfg.keys_subdir);
let name = cfg.name.clone();
let mut vars = vars; let mut vars = vars;
vars.insert("KEY_CN".into(), name.clone()); vars.insert("KEY_CN", &cfg.name);
vars.insert("KEY_NAME".into(), name.clone()); vars.insert("KEY_NAME", &cfg.name);
vars.insert("KEY_EMAIL".into(), cfg.email.clone()); vars.insert("KEY_EMAIL", &cfg.email);
let ca_file = keys_dir.join(&cfg.ca_filename);
let req_file = keys_dir.join(format!("{}.csr", &name));
let key_file = keys_dir.join(format!("{}.key", &name));
let cert_file = keys_dir.join(format!("{}.crt", &name));
let openssl_cnf = base_dir.join( let openssl_cnf = base_dir.join(
std::env::var(&cfg.openssl_cnf_env) std::env::var(&cfg.openssl_cnf_env)
.as_ref() .as_ref()
@ -56,10 +52,10 @@ impl OpenSSLExternalProvider {
base_dir, base_dir,
openssl_cnf, openssl_cnf,
openssl: cfg.openssl.to_string(), openssl: cfg.openssl.to_string(),
ca_file, ca_file: cfg.ca_filepath.clone(),
req_file, req_file: cfg.req_filepath.clone(),
key_file, key_file: cfg.key_filepath.clone(),
cert_file, cert_file: cfg.cert_filepath.clone(),
req_days: cfg.req_days, req_days: cfg.req_days,
} }
} }
@ -92,7 +88,7 @@ impl ICryptoProvider for OpenSSLExternalProvider {
"-batch", "-batch",
]) ])
.current_dir(&self.base_dir) .current_dir(&self.base_dir)
.envs(&self.vars) .envs(self.vars.deref())
.status() .status()
.await?; .await?;
@ -128,7 +124,7 @@ impl ICryptoProvider for OpenSSLExternalProvider {
"-batch", "-batch",
]) ])
.current_dir(&self.base_dir) .current_dir(&self.base_dir)
.envs(&self.vars) .envs(self.vars.deref())
.status() .status()
.await?; .await?;

View File

@ -1,4 +1,4 @@
use anyhow::{anyhow, Context, Ok, Result}; use anyhow::{anyhow, Context, Result};
use openssl::{ use openssl::{
asn1::Asn1Time, asn1::Asn1Time,
conf::{Conf, ConfMethod}, conf::{Conf, ConfMethod},
@ -16,13 +16,14 @@ use std::path::{Path, PathBuf};
use tokio::fs; use tokio::fs;
use crate::{ use crate::{
common::{is_file_exist, read_file, AppConfig, VarsMap}, common::{is_file_exist, read_file, AppConfig},
crypto_provider::ICryptoProvider, crypto_provider::ICryptoProvider,
}; };
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::collections::HashMap; use std::collections::HashMap;
use crate::vars::{IStrMap, VarsMap};
use chrono::{Datelike, Days, Timelike, Utc}; use chrono::{Datelike, Days, Timelike, Utc};
lazy_static! { lazy_static! {
@ -93,10 +94,6 @@ fn get_time_str_x509(days: u32) -> Result<String> {
pub(crate) struct OpenSSLInternalProvider { pub(crate) struct OpenSSLInternalProvider {
vars: VarsMap, vars: VarsMap,
#[allow(unused)]
base_dir: PathBuf,
#[allow(unused)]
openssl_cnf: PathBuf,
ca_file: PathBuf, ca_file: PathBuf,
ca_key_file: PathBuf, ca_key_file: PathBuf,
req_file: PathBuf, req_file: PathBuf,
@ -121,41 +118,24 @@ impl OpenSSLInternalProvider {
} }
pub(crate) fn try_from_cfg(cfg: &AppConfig, vars: VarsMap) -> Result<Self> { pub(crate) fn try_from_cfg(cfg: &AppConfig, vars: VarsMap) -> Result<Self> {
let base_dir = PathBuf::from(&cfg.base_directory);
let keys_dir = base_dir.join(&cfg.keys_subdir);
let name = cfg.name.clone();
let mut vars = vars; let mut vars = vars;
vars.insert("KEY_CN".into(), name.clone()); vars.insert("KEY_CN", &cfg.name);
vars.insert("KEY_NAME".into(), name.clone()); vars.insert("KEY_NAME", &cfg.name);
vars.insert("KEY_EMAIL".into(), cfg.email.clone()); vars.insert("KEY_EMAIL", &cfg.email);
let ca_file = keys_dir.join(&cfg.ca_filename); let key_size_s = vars.get(&"KEY_SIZE").unwrap_or("2048");
let ca_key_file = ca_file.with_extension("key");
let req_file = keys_dir.join(format!("{}.csr", &name));
let key_file = keys_dir.join(format!("{}.key", &name));
let cert_file = keys_dir.join(format!("{}.crt", &name));
let openssl_cnf = base_dir.join(
std::env::var(&cfg.openssl_cnf_env)
.as_ref()
.unwrap_or(&cfg.openssl_default_cnf),
);
let default_key_size = "2048".to_string();
let key_size_s = vars.get("KEY_SIZE").unwrap_or(&default_key_size);
let key_size: u32 = key_size_s.parse().context("parse key size error")?; let key_size: u32 = key_size_s.parse().context("parse key size error")?;
let encoding = cfg.encoding.clone(); let encoding = cfg.encoding.clone();
Ok(Self { Ok(Self {
vars, vars,
base_dir, ca_file: cfg.ca_filepath.clone(),
openssl_cnf, ca_key_file: cfg.ca_key_filepath.clone(),
ca_file, req_file: cfg.req_filepath.clone(),
ca_key_file, key_file: cfg.key_filepath.clone(),
req_file, cert_file: cfg.cert_filepath.clone(),
key_file,
cert_file,
req_days: cfg.req_days, req_days: cfg.req_days,
key_size, key_size,
encoding, encoding,
@ -209,9 +189,9 @@ impl OpenSSLInternalProvider {
for (&key, &var) in KEYMAP.iter() { for (&key, &var) in KEYMAP.iter() {
let value = self let value = self
.vars .vars
.get(var) .get(&var)
.ok_or(anyhow!("variable not set: {}", var))?; .ok_or(anyhow!("variable not set: {}", var))?;
name_builder.append_entry_by_text(key, value).unwrap(); name_builder.append_entry_by_text(key, value)?;
} }
Ok(name_builder.build()) Ok(name_builder.build())
} }
@ -227,10 +207,10 @@ impl OpenSSLInternalProvider {
let key_extended_ext = ExtendedKeyUsage::new().client_auth().build()?; let key_extended_ext = ExtendedKeyUsage::new().client_auth().build()?;
let mut san_extension = SubjectAlternativeName::new(); let mut san_extension = SubjectAlternativeName::new();
if let Some(name) = vars.get("KEY_NAME") { if let Some(name) = vars.get(&"KEY_NAME") {
san_extension.dns(name); san_extension.dns(name);
} }
if let Some(email) = vars.get("KEY_EMAIL") { if let Some(email) = vars.get(&"KEY_EMAIL") {
san_extension.email(email); san_extension.email(email);
} }
let san_ext = san_extension.build(context).context("build san")?; let san_ext = san_extension.build(context).context("build san")?;

View File

@ -3,38 +3,84 @@ use regex::Regex;
use std::{path::PathBuf, pin::Pin}; use std::{path::PathBuf, pin::Pin};
use tokio::pin; use tokio::pin;
use crate::arcstr::ArcStr;
use crate::common::{read_file_by_lines, AppConfig};
use futures_util::stream::StreamExt; 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 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) struct VarsFile {
pub(crate) filepath: PathBuf, pub(crate) filepath: ArcStr,
pub(crate) vars: Option<VarsMap>, pub(crate) encoding: ArcStr,
pub(crate) encoding: String,
} }
impl VarsFile { impl VarsFile {
async fn from_file(filepath: &PathBuf, encoding: String) -> Result<Self> { async fn from_file<P>(filepath: P, encoding: ArcStr) -> Result<Self>
let metadata = tokio::fs::metadata(&filepath).await.context(format!( where
"file not found {}", P: AsRef<Path>,
filepath.to_str().expect("str") {
))?; 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() { 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 { Ok(VarsFile {
filepath: filepath.to_path_buf(), filepath: ArcStr::from(filepath_str),
vars: None,
encoding, encoding,
}) })
} }
async fn from_dir(dir: PathBuf, encoding: String) -> Result<Self> { async fn from_dir<P>(dir: P, encoding: ArcStr) -> Result<Self>
let filepath = dir.join("vars"); where
let err_context = format!( P: AsRef<Path>,
"vars or vars.bat file not found in {}", {
dir.to_str().expect("str") 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 { match Self::from_file(&filepath, encoding.clone()).await {
Ok(res) => Ok(res), Ok(res) => Ok(res),
@ -47,50 +93,38 @@ impl VarsFile {
pub(crate) async fn from_config(config: &AppConfig) -> Result<Self> { pub(crate) async fn from_config(config: &AppConfig) -> Result<Self> {
Self::from_dir( Self::from_dir(
PathBuf::from(&config.base_directory), PathBuf::from(&config.base_directory),
config.encoding.clone(), ArcStr::from(config.encoding.as_str()),
) )
.await .await
} }
pub(crate) async fn parse(&mut self) -> Result<()> { pub(crate) async fn parse(&self) -> Result<VarsMap> {
let mut result = VarsMap::new(); let mut result = ArcVarsMap::new();
let lines = read_file_by_lines(&self.filepath, &self.encoding).await?; 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); let lines = Pin::from(lines);
pin!(lines); pin!(lines);
let re_v2 = let re_v2 = Regex::new(r#"^(export|set)\s\b(?P<key>[\w\d_]+)\b=\s?"?(?P<value>[^#]+?)"?$"#)
Regex::new(r#"^(export|set)\s\b(?P<key>[\w\d_]+)\b=\s?"?(?P<value>[^\#]+?)"?$"#) .context("regex v2")
.context("regex v2")?; .context("re_v2 error")?;
let re_v3 = Regex::new(r"^set_var\s(?P<key1>[\w\d_]+)\s+(?P<value1>[^\#]+?)$") let re_v3 = Regex::new(r"^set_var\s(?P<key1>[\w\d_]+)\s+(?P<value1>[^#]+?)$")
.context("regex v3")?; .context("regex v3")
.context("re_v3 error")?;
while let Some(line) = lines.next().await { while let Some(line) = lines.next().await {
if let Some(caps) = re_v2.captures(line.as_str()) { for re in [&re_v2, &re_v3].iter() {
result.insert(caps["key"].to_string(), caps["value"].to_string()); if let Some(caps) = re.captures(line.as_str()) {
let [key, value] = [&caps["key"], &caps["value"]].map(ArcStr::from);
result.insert(key, value);
continue; 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(())
}
#[allow(dead_code)]
fn apply(&self) -> Result<()> {
if let Some(vars) = self.vars.clone() {
for (key, value) in vars.iter() {
unsafe {
std::env::set_var(key, value);
} }
} }
} else { Ok(VarsMap(result))
Err(anyhow!("vars not parsed"))?
}
Ok(())
} }
} }