From 6773dfce8d5326a4afed4bfdc97edb24713d24d1 Mon Sep 17 00:00:00 2001 From: Wind Date: Tue, 19 Nov 2024 07:14:12 +0800 Subject: [PATCH] add `--default` flag to input command (#14374) # Description Closes: #14248 # User-Facing Changes Added a `--default` flag to input command, and it also added an extra output to prompt: ``` > let x = input -d 18 "input your age" input your age (default: 18) > $x 18 > let x = input -d 18 > $x 18 ``` # Tests + Formatting I don't think it's easy to add a test for it :-( --- .../nu-command/src/platform/input/input_.rs | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/nu-command/src/platform/input/input_.rs b/crates/nu-command/src/platform/input/input_.rs index cf46b400c0..f792db992e 100644 --- a/crates/nu-command/src/platform/input/input_.rs +++ b/crates/nu-command/src/platform/input/input_.rs @@ -43,6 +43,12 @@ impl Command for Input { "number of characters to read; suppresses output", Some('n'), ) + .named( + "default", + SyntaxShape::String, + "default value if no input is provided", + Some('d'), + ) .switch("suppress-output", "don't print keystroke values", Some('s')) .category(Category::Platform) } @@ -72,8 +78,12 @@ impl Command for Input { }); } + let default_val: Option = call.get_flag(engine_state, stack, "default")?; if let Some(prompt) = &prompt { - print!("{prompt}"); + match &default_val { + None => print!("{prompt}"), + Some(val) => print!("{prompt} (default: {val})"), + } let _ = std::io::stdout().flush(); } @@ -149,7 +159,10 @@ impl Command for Input { if !suppress_output { std::io::stdout().write_all(b"\n")?; } - Ok(Value::string(buf, call.head).into_pipeline_data()) + match default_val { + Some(val) if buf.is_empty() => Ok(Value::string(val, call.head).into_pipeline_data()), + _ => Ok(Value::string(buf, call.head).into_pipeline_data()), + } } fn examples(&self) -> Vec { @@ -164,6 +177,11 @@ impl Command for Input { example: "let user_input = (input --numchar 2)", result: None, }, + Example { + description: "Get input from the user with default value, and assign to a variable", + example: "let user_input = (input --default 10)", + result: None, + }, ] } }