seaplane_cli/cli/cmds/metadata/
delete.rs

1use clap::{ArgMatches, Command};
2use serde_json::json;
3
4use crate::{
5    api::MetadataReq,
6    cli::cmds::metadata::{common, common::SeaplaneMetadataCommonArgMatches, CliCommand},
7    context::{Ctx, MetadataCtx},
8    error::Result,
9    printer::OutputFormat,
10};
11
12#[derive(Copy, Clone, Debug)]
13pub struct SeaplaneMetadataDelete;
14
15impl SeaplaneMetadataDelete {
16    pub fn command() -> Command {
17        Command::new("delete")
18            .visible_aliases(["del", "remove", "rm"])
19            .about("Delete one or more metadata key-value pairs")
20            .args(common::args())
21    }
22}
23
24impl CliCommand for SeaplaneMetadataDelete {
25    fn run(&self, ctx: &mut Ctx) -> Result<()> {
26        let mut len = 0;
27        let mut req = MetadataReq::new(ctx)?;
28        for kv in ctx.md_ctx.get_mut().unwrap().kvs.iter_mut() {
29            let key = kv.key.to_string();
30            req.set_key(key.clone())?;
31            req.delete_value()?;
32            if ctx.args.out_format == OutputFormat::Table {
33                cli_println!("Removed {key}");
34            }
35            len += 1;
36        }
37
38        if ctx.args.out_format == OutputFormat::Table {
39            cli_println!("\nSuccessfully removed {len} item{}", if len > 1 { "s" } else { "" });
40        } else {
41            cli_println!(
42                "{}",
43                json!({"removed": ctx.md_ctx.get_or_init().kvs.keys().map(|k| k.to_string()).collect::<Vec<_>>() })
44            )
45        }
46
47        Ok(())
48    }
49
50    fn update_ctx(&self, matches: &ArgMatches, ctx: &mut Ctx) -> Result<()> {
51        ctx.md_ctx
52            .init(MetadataCtx::from_md_common(&SeaplaneMetadataCommonArgMatches(matches))?);
53        ctx.args.out_format = matches.get_one("format").copied().unwrap_or_default();
54        Ok(())
55    }
56}