algae_cli/cli/
encrypt.rs

1use std::{fmt::Debug, path::PathBuf};
2
3use clap::Parser;
4use miette::{IntoDiagnostic, Result, WrapErr};
5use tokio::fs::remove_file;
6
7use crate::{
8	files::{append_age_ext, encrypt_file},
9	keys::KeyArgs,
10};
11
12/// Encrypt a file using a public key or an identity.
13///
14/// Either of `--key-path` or `--key` must be provided.
15///
16/// For symmetric cryptography (using a passphrase), see `protect`/`reveal`.
17#[derive(Debug, Clone, Parser)]
18pub struct EncryptArgs {
19	/// File to be encrypted.
20	pub input: PathBuf,
21
22	/// Path or filename to write the encrypted file to.
23	///
24	/// By default this is the input file, with `.age` appended.
25	#[arg(short, long)]
26	pub output: Option<PathBuf>,
27
28	/// Delete input file after encrypting.
29	#[arg(long = "rm")]
30	pub remove: bool,
31
32	#[command(flatten)]
33	#[allow(missing_docs, reason = "don't interfere with clap")]
34	pub key: KeyArgs,
35}
36
37/// CLI command for the `encrypt` operation (public key encryption).
38pub async fn run(
39	EncryptArgs {
40		ref input,
41		output,
42		key,
43		remove,
44	}: EncryptArgs,
45) -> Result<()> {
46	let public_key = key.require_public_key().await?;
47	let output = output.unwrap_or_else(|| append_age_ext(input));
48
49	encrypt_file(input, output, public_key).await?;
50
51	if remove {
52		remove_file(input)
53			.await
54			.into_diagnostic()
55			.wrap_err("deleting input file")?;
56	}
57
58	Ok(())
59}