use keycache::AuthLevel;
use std::env;
use std::io::{Error, ErrorKind};
use std::ops::Deref;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct Filename(PathBuf);
impl Filename {
const EXTENSION: &str = ".keycache";
}
impl Deref for Filename {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<String> for Filename {
fn from(filepath: String) -> Self {
let filepath = Path::new(&filepath);
let false = filepath.exists() else {
return Self(filepath.to_owned());
};
match filepath.extension() {
None => Self(filepath.with_extension(Self::EXTENSION)),
_ => Self(filepath.to_owned()),
}
}
}
#[derive(Debug, Clone)]
pub struct Environment {
pub cwd: Option<String>,
pub userauth: Option<String>,
}
impl Environment {
pub fn from_env() -> Self {
Self { cwd: env::var("KEYCACHE_CWD").ok(), userauth: env::var("KEYCACHE_USERAUTH").ok() }
}
}
#[derive(Debug, Clone)]
pub struct CliArgs {
pub flag_userauth: Option<String>,
pub flag_seal: Option<AuthLevel>,
pub name: Filename,
}
impl CliArgs {
pub fn from_env() -> Result<Self, Error> {
let mut flag_userauth = None;
let mut flag_create = None;
let mut name = None;
for arg in env::args().skip(1) {
match (arg.split_once('='), &flag_userauth, &flag_create, &name) {
(Some(("--userauth", value)), None, _, _) => flag_userauth = Some(String::from(value)),
(Some(("--seal", value)), _, None, _) => flag_create = Some(AuthLevel::try_from(value)?),
(None, _, _, None) => name = Some(Filename::from(arg)),
_ => return Err(Error::new(ErrorKind::InvalidInput, format!("Unexpected argument: {arg}"))),
}
}
let name = name.ok_or(Error::new(ErrorKind::InvalidInput, "Missing required argument: `name`"))?;
Ok(Self { flag_userauth, flag_seal: flag_create, name })
}
}