Files
drawer/src/parsing.rs
T

181 lines
5.5 KiB
Rust
Raw Normal View History

2026-05-09 17:22:50 -05:00
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use clap::{Parser, Subcommand};
use crate::error::DrawerError;
use crate::parsing::KeyType::*;
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum OperationType {
Open,
Close,
}
#[derive(Debug, PartialEq)]
pub struct DrawerOperation {
pub operation_type: OperationType,
pub drawer_file: PathBuf,
pub key: KeyType,
pub target_path: PathBuf,
pub force: bool,
}
#[derive(Debug, PartialEq)]
pub enum KeyType {
EnvVar, Path(PathBuf)
}
#[derive(Parser)]
#[command(name = "drawer")]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Open {
drawer_file: PathBuf,
target_path: Option<PathBuf>,
#[arg(short = 'i')]
key: Option<PathBuf>,
#[arg(short = 'f')]
force: bool,
},
Close {
drawer_file: PathBuf,
target_path: Option<PathBuf>,
#[arg(short = 'i')]
key: Option<PathBuf>,
},
}
pub fn parse_args<I, T>(args: I) -> Result<DrawerOperation, DrawerError>
where
I: IntoIterator<Item = T>,
T: Into<OsString> + Clone,
{
let cli = Cli::try_parse_from(args)
.map_err(|e| DrawerError::ParseError(e.to_string()))?;
match cli.command {
Command::Open { drawer_file, target_path, key, force } => {
let key = resolve_key(key);
let target = target_path.unwrap_or_else(|| {
PathBuf::from(drawer_file.file_stem().unwrap_or_default())
});
Ok(DrawerOperation {
operation_type: OperationType::Open,
drawer_file,
key,
target_path: target,
force,
})
}
Command::Close { drawer_file, target_path, key } => {
let key = resolve_key(key);
let target = target_path.unwrap_or_else(|| PathBuf::from("."));
Ok(DrawerOperation {
operation_type: OperationType::Close,
drawer_file,
key,
target_path: target,
force: false,
})
}
}
}
fn resolve_key(key: Option<PathBuf>) -> KeyType {
if let Some(k) = key {
return Path(k);
}
EnvVar
}
impl DrawerOperation {
2026-05-09 18:07:24 -05:00
pub fn perform(&self) -> Result<(), DrawerError> {
self.validate()?;
match self.operation_type {
OperationType::Open => self.perform_open(),
OperationType::Close => self.perform_close(),
}
}
fn perform_open(&self) -> Result<(), DrawerError> {
todo!()
}
fn perform_close(&self) -> Result<(), DrawerError> {
let mut buf: Vec<u8> = Vec::new();
{
let mut archive = tar::Builder::new(&mut buf);
archive.append_dir_all(".", &self.target_path)
.map_err(|_| DrawerError::TarFailed)?;
archive.finish()
.map_err(|_| DrawerError::TarFailed)?;
}
std::fs::write(&self.drawer_file, &buf)
.map_err(|_| DrawerError::WriteFailed(self.drawer_file.clone()))
}
2026-05-09 17:22:50 -05:00
pub fn validate(&self) -> Result<(), DrawerError> {
if self.drawer_file.extension().and_then(|e| e.to_str()) != Some("drawer") {
return Err(DrawerError::DrawerFileInvalidExtension(self.drawer_file.clone()));
}
self.validate_key()?;
match self.operation_type {
OperationType::Open => self.validate_open(),
OperationType::Close => self.validate_close(),
}
}
fn validate_key(&self) -> Result<(), DrawerError> {
let key_path = match &self.key {
EnvVar => {
let val = std::env::var("DRAWER_KEY").map_err(|_| DrawerError::NoKeyPath)?;
PathBuf::from(val)
}
Path(p) => p.clone(),
};
match std::fs::File::open(&key_path) {
Ok(_) => Ok(()),
Err(_) => Err(DrawerError::KeyInvalid(key_path)),
}
}
fn validate_open(&self) -> Result<(), DrawerError> {
if !self.drawer_file.exists() {
return Err(DrawerError::DrawerFileNotFound(self.drawer_file.clone()));
}
if !self.force && self.target_path.exists() {
let mut entries = std::fs::read_dir(&self.target_path)
.map_err(|_| DrawerError::TargetInvalid(self.target_path.clone()))?;
if entries.next().is_some() {
return Err(DrawerError::TargetNotEmpty(self.target_path.clone()));
}
}
Ok(())
}
fn validate_close(&self) -> Result<(), DrawerError> {
let meta = std::fs::metadata(&self.target_path)
.map_err(|_| DrawerError::TargetInvalid(self.target_path.clone()))?;
if !meta.is_dir() {
return Err(DrawerError::TargetInvalid(self.target_path.clone()));
}
if std::fs::read_dir(&self.target_path).is_err() {
return Err(DrawerError::TargetInvalid(self.target_path.clone()));
}
let canon_target = self.target_path.canonicalize()
.unwrap_or_else(|_| self.target_path.clone());
let drawer_parent = self.drawer_file.parent().unwrap_or(Path::new("."));
let canon_drawer = drawer_parent.canonicalize()
.unwrap_or_else(|_| drawer_parent.to_path_buf())
.join(self.drawer_file.file_name().unwrap_or_default());
if canon_drawer.starts_with(&canon_target) {
return Err(DrawerError::DrawerInsideTarget);
}
Ok(())
}
}