use std::path::PathBuf;
use std::str::FromStr;
use clap::Args;
use crate::cli::ENV_PATH_SEP;
use crate::error::{Result, YageError};
use crate::{encrypt_yaml, get_yaml_recipients, load_recipients, read_yaml, write_yaml};
#[derive(Args, Debug)]
pub struct EncryptArgs {
#[clap(short, long)]
pub in_place: bool,
#[clap(
short,
long = "recipient",
value_name = "RECIPIENT",
env = "YAGE_RECIPIENT",
value_delimiter = ','
)]
pub recipients: Vec<String>,
#[clap(
short = 'R',
long = "recipient-file",
value_name = "FILE",
env = "YAGE_RECIPIENT_FILE",
value_delimiter = ENV_PATH_SEP,
)]
pub recipient_files: Vec<PathBuf>,
#[clap(short, long, default_value = "-", value_name = "FILE")]
pub output: PathBuf,
#[arg()]
pub files: Vec<PathBuf>,
}
pub fn encrypt(args: &EncryptArgs) -> Result<i32> {
if args.in_place && args.files.contains(&PathBuf::from_str("-").unwrap()) {
return Err(YageError::InPlaceStdin);
}
if !args.in_place && args.files.len() != 1 {
return Err(YageError::InvalidNumberOfInputFiles);
}
let recipients = load_recipients(&args.recipients, &args.recipient_files)?;
for file in &args.files {
let input_data = read_yaml(file)?;
let yaml_recipients = get_yaml_recipients(&input_data)?;
let recipients = if recipients.is_empty() {
&yaml_recipients
} else if yaml_recipients.is_empty() || recipients == yaml_recipients {
&recipients
} else {
return Err(YageError::InvalidRecipients);
};
let output_data = encrypt_yaml(&input_data, recipients)?;
write_yaml(if args.in_place { file } else { &args.output }, &output_data)?;
}
Ok(0)
}