Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand prompt logic for PR #199 #201

Open
bartdeboer opened this issue May 3, 2024 · 0 comments
Open

Expand prompt logic for PR #199 #201

bartdeboer opened this issue May 3, 2024 · 0 comments

Comments

@bartdeboer
Copy link
Contributor

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant