1
use std::fs;
2
use std::path::Path;
3

            
4
use clap::Args;
5

            
6
use crate::secrets::context::Context;
7

            
8
use super::KEY_LOCATION_HELP;
9

            
10
#[derive(Debug, Args)]
11
pub struct PurgeKey {
12
  /// The location to store the private key
13
  #[arg(short, long, help = KEY_LOCATION_HELP)]
14
  location: Option<String>,
15

            
16
  /// If not provided, the key will be named "default"
17
  #[arg(short, long, help = "The key name")]
18
  name: Option<String>,
19
}
20

            
21
impl PurgeKey {
22
  pub fn execute(&self, context: &Context) -> anyhow::Result<()> {
23
    let location: &str = &self.location.clone().unwrap_or_else(|| context.keys_location());
24
    let name: &str = &self.name.clone().unwrap_or_else(|| context.key_name());
25

            
26
    assert!(!location.is_empty(), "Location must be provided");
27
    assert!(!name.is_empty(), "Key name must be provided");
28

            
29
    let filename_with_ext: &str = &format!("{name}.key");
30
    let file_path = Path::new(location).join(filename_with_ext);
31
    if file_path.exists() {
32
      fs::remove_file(file_path)?;
33
      println!("Key {name} deleted successfully.");
34
    } else {
35
      println!("Key {name} does not exist.");
36
    }
37

            
38
    Ok(())
39
  }
40
}