Skip to content

Expand prompt logic for PR #199 #201

Open
@bartdeboer

Description

@bartdeboer

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions