seaplane_cli/cli/cmds/metadata/
set.rs

1use clap::{ArgMatches, Command};
2use seaplane::api::metadata::v1::Value;
3
4use crate::{
5    api::MetadataReq,
6    cli::{cmds::metadata::common, CliCommand},
7    context::{Ctx, MetadataCtx},
8    error::Result,
9    printer::{Output, OutputFormat},
10};
11
12/// A newtype wrapper to enforce where the ArgMatches came from which reduces errors in checking if
13/// values of arguments were used or not. i.e. `seaplane formation create` may not have the same
14/// arguments as `seaplane account token` even though both produce an `ArgMatches`.
15#[allow(missing_debug_implementations)]
16pub struct SeaplaneMetadataSetArgMatches<'a>(pub &'a ArgMatches);
17
18#[derive(Copy, Clone, Debug)]
19pub struct SeaplaneMetadataSet;
20
21impl SeaplaneMetadataSet {
22    pub fn command() -> Command {
23        Command::new("set")
24            .visible_alias("put")
25            .about("Set a metadata key-value pair")
26            .arg(common::base64())
27            .arg(arg!(key =["KEY"] required ).help("The key to set"))
28            .arg(arg!(value =["VALUE"] required ).help("The value (@path will load the value from a path and @- will load the value from STDIN)"))
29    }
30}
31
32impl CliCommand for SeaplaneMetadataSet {
33    fn run(&self, ctx: &mut Ctx) -> Result<()> {
34        let mut req = MetadataReq::new(ctx)?;
35        let mdctx = ctx.md_ctx.get_mut_or_init();
36        for kv in mdctx.kvs.iter_mut() {
37            let key = kv.key.to_string();
38            let value = kv.value.to_string();
39            req.set_key(&key)?;
40            req.put_value(Value::from_encoded(value.clone()))?;
41            if ctx.args.out_format == OutputFormat::Table {
42                cli_println!("Success");
43            }
44        }
45
46        if ctx.args.out_format == OutputFormat::Json {
47            let kvs = ctx.md_ctx.get_or_init().kvs.clone();
48            kvs.print_json(ctx)?;
49        }
50
51        Ok(())
52    }
53
54    fn update_ctx(&self, matches: &ArgMatches, ctx: &mut Ctx) -> Result<()> {
55        // NOTE: MetadataCtx::from_md_set is impure and tries to read from STDIN if the value is
56        // `@-`
57        ctx.md_ctx
58            .init(MetadataCtx::from_md_set(&SeaplaneMetadataSetArgMatches(matches))?);
59        ctx.args.out_format = matches.get_one("format").copied().unwrap_or_default();
60        Ok(())
61    }
62}