1 个不稳定版本

0.2.0 2021年3月9日
0.1.1 2021年3月6日
0.1.0 2021年2月18日

#53#how

MIT 许可证

11KB
241 代码行

CLInput

基本的 Rust 提示包。

使用方法

基本示例

最基本的示例是创建一个新的提示并提问

// This will display "How is it going? " and wait for input via stdin
use clinput::{Prompt, PromptError};
let res: Result<String, PromptError> = Prompt::new().ask("How is it going?");

深入

Prompt 结构还支持设置默认值、有效选择列表和自定义验证函数。

use clinput::{Prompt, PromptError};

// This will display "What is your favourite colour? [red]" and wait for input via stdin
// If the input is empty then "red" will be used
let with_default = Prompt::new().default("red").ask("What is your favourite colour?");

// This will display "Choose a direction [up, down, left, right] " and wait for input via stdin
// If the input does not match one of the choices "Valid options are: up, down, left , right" will be 
// displayed and the prompt will loop
let from_list = Prompt::new().choices(["up", "down", "left", "right"]).ask("Choose a direction");

// This will display "Enter a password at least 8 chars in length "
// If the input is less than 8 chars it will display "Too short" and loop
let custom = Prompt::new()
	.validate(|input: String| {
		if input.length() < 8 {
			return Err(PromptError::ValidateError(String::from("Too short")));
		}
		Ok(input)
	})
	.ask("Enter a password at least 8 chars in length");

// These can all be combined
let from_list_with_default = Prompt::new()
	.default("Zues")
	.choices(["Zeus", "Aphrodite", "Hades", "Cronus", "Gaia", "Heracles", "Athena"].to_vec())
	.ask("Who is your favourite Greek god? ");

常用用例助手

还有一些构造函数可以帮助处理常用用例

use clinput::{Prompt, PromptError};

// This will display "What is your name? " and wait for input
// If the input is whitespace only it will display "Cannot be blank" and loop
let not_empty = Prompt::not_blank().ask("What is your name?");

// This will display "Continue? " and wait for input
// If the input is not in the list: y, n (case insensitive) it will display "Valid options are: y, n" and loop
let yes_or_no = Prompt::yn().ask("Continue?");

依赖

~290–750KB
~18K SLoC