Open
Description
The Prompt function from PR #199 could be a bit expanded to support message formatting and default values:
// Prompt creates a pipe that reads user input from stdin after displaying the
// specified prompt.
func Prompt(prompt string) *Pipe {
return Promptf(prompt)
}
// Promptf displays a formatted prompt to the user and reads a line of input.
// Additional arguments can be provided for the format specifier like Printf.
// The last argument will be used as the default value.
func Promptf(format string, args ...any) *Pipe {
fmt.Printf(format, args...)
p := Stdin().First(1)
input, err := p.String()
if err != nil {
return p
}
input = strings.TrimSpace(input)
if input == "" && len(args) > 0 {
input = fmt.Sprint(args[len(args)-1])
}
return Echo(input)
}
Example:
input, _ := script.Prompt("Input: ").String()
fmt.Printf("Input was %s\n", input)
input, _ = script.Promptf("Input [%s]: ", "John").String()
fmt.Printf("Input was %s\n", input)
Output:
Input: Jane
Input was Jane
Input [John]:
Input was John
Metadata
Metadata
Assignees
Labels
No labels