Last active
September 20, 2023 08:27
-
-
Save cbzehner/dede31dc0b4617fd4abaff9e03b15f9e to your computer and use it in GitHub Desktop.
Prompt for missing values in Clap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "clap_prompt_example" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
clap = { version = "3.1", features = ["derive"] } | |
dialoguer = "0.10" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{fmt::Debug, str::FromStr}; | |
use clap::Parser; | |
use dialoguer::{theme::ColorfulTheme, Input}; | |
/// Simple program to greet a person | |
#[derive(Parser, Debug)] | |
#[clap(author, version, about, long_about = None)] | |
struct InputArgs { | |
/// Name of the person to greet | |
#[clap(short, long)] | |
name: Option<String>, | |
/// Number of times to greet | |
#[clap(short, long)] | |
count: Option<u8>, | |
} | |
/// Internal representation matching the InputArgs without the nullable properties | |
struct Args { | |
name: String, | |
count: u8, | |
} | |
/// Transform input arguments into validated arguments by prompting for missing information | |
impl From<InputArgs> for Args { | |
fn from(input: InputArgs) -> Self { | |
let name = match input.name { | |
Some(name) => name, | |
None => prompt("Who would you like to greet", None), | |
}; | |
let count = match input.count { | |
Some(count) => count, | |
None => prompt("How many times", Some(1)), | |
}; | |
Self { name, count } | |
} | |
} | |
fn main() { | |
let input = InputArgs::parse(); | |
let args = Args::from(input); | |
for _ in 0..args.count { | |
println!("Hello {}!", args.name) | |
} | |
} | |
/// Prompt for user input with the ability to provide a default value | |
fn prompt<T>(prompt: &str, default: Option<T>) -> T | |
where | |
T: Clone + ToString + FromStr, | |
<T as FromStr>::Err: Debug + ToString, | |
{ | |
let theme = &ColorfulTheme::default(); | |
let mut builder = Input::<T>::with_theme(theme); | |
builder.with_prompt(prompt); | |
if let Some(default) = default { | |
builder.default(default); | |
} | |
builder.interact_text().unwrap() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment