Skip to content

Commit

Permalink
Make common args working after sub commands.
Browse files Browse the repository at this point in the history
Now common args like `--secret-name` can be specified after the
sub commands.

Common args like `--secret-name` are needed by every sub commands.
To avoid declaring them in every sub command, they are specified
outside sub commands. I think `ksher cmd --secret-name XX` means
better than `ksher --secret-name XX cmd`, hence they are set as
`global`.

But per clap-rs/clap#1546, an arg cannot
be global and required at the same time. So `--secret-name` is set
as `Option` and checked manually to throw a clap style error message.
  • Loading branch information
Magicloud committed Mar 27, 2024
1 parent 2bb1e9b commit 240685c
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
use anyhow::{anyhow, Result};
use clap::error::ErrorKind;
use clap::*;
use std::io::Write;
use std::process as p;

fn main() -> Result<()> {
let cli = Cli::parse();
if cli.secret_name.is_none() {
Cli::command().error(
ErrorKind::MissingRequiredArgument,
"the following required arguments were not provided:\n \x1b[32m--secret-name <SECRET_NAME>\x1b[0m"
).exit();
}
let secret_name = cli.secret_name.unwrap();

let pg = passwords::PasswordGenerator {
length: cli.secret_length.into(),
Expand Down Expand Up @@ -33,7 +41,7 @@ type: kubernetes.io/basic-auth
"#,
username,
pg.generate_one().map_err(|e| anyhow!("{e}"))?,
cli.secret_name,
secret_name,
cli.secret_namespace
)
}
Expand Down Expand Up @@ -63,11 +71,11 @@ enum SubCmd {

#[derive(Parser)]
struct Cli {
#[arg(short('s'), long)]
secret_name: String,
#[arg(short('n'), long, default_value = "default")]
#[arg(short('s'), long, global = true)]
secret_name: Option<String>,
#[arg(short('n'), long, global = true, default_value = "default")]
secret_namespace: String,
#[arg(short('l'), long, default_value = "16")]
#[arg(short('l'), long, global = true, default_value = "16")]
secret_length: u8,

#[command(subcommand)]
Expand Down

0 comments on commit 240685c

Please sign in to comment.