Prompt asks the user for input.
(inv *serpent.Invocation, opts PromptOptions)
| 50 | |
| 51 | // Prompt asks the user for input. |
| 52 | func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) { |
| 53 | // If the cmd has a "yes" flag for skipping confirm prompts, honor it. |
| 54 | // If it's not a "Confirm" prompt, then don't skip. As the default value of |
| 55 | // "yes" makes no sense. |
| 56 | if opts.IsConfirm && inv.ParsedFlags().Lookup(skipPromptFlag) != nil { |
| 57 | if skip, _ := inv.ParsedFlags().GetBool(skipPromptFlag); skip { |
| 58 | return ConfirmYes, nil |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pretty.Fprintf(inv.Stdout, DefaultStyles.FocusedPrompt, "") |
| 63 | pretty.Fprintf(inv.Stdout, pretty.Nop, "%s ", opts.Text) |
| 64 | if opts.IsConfirm { |
| 65 | if len(opts.Default) == 0 { |
| 66 | opts.Default = ConfirmYes |
| 67 | } |
| 68 | var ( |
| 69 | renderedYes = pretty.Sprint(DefaultStyles.Placeholder, ConfirmYes) |
| 70 | renderedNo = pretty.Sprint(DefaultStyles.Placeholder, ConfirmNo) |
| 71 | ) |
| 72 | if opts.Default == ConfirmYes { |
| 73 | renderedYes = Bold(ConfirmYes) |
| 74 | } else { |
| 75 | renderedNo = Bold(ConfirmNo) |
| 76 | } |
| 77 | _, _ = fmt.Fprintf(inv.Stdout, "(%s/%s) ", renderedYes, renderedNo) |
| 78 | } else if opts.Default != "" { |
| 79 | _, _ = fmt.Fprintf(inv.Stdout, "(%s) ", pretty.Sprint(DefaultStyles.Placeholder, opts.Default)) |
| 80 | } |
| 81 | interrupt := make(chan os.Signal, 1) |
| 82 | |
| 83 | if inv.Stdin == nil { |
| 84 | panic("inv.Stdin is nil") |
| 85 | } |
| 86 | |
| 87 | errCh := make(chan error, 1) |
| 88 | lineCh := make(chan string) |
| 89 | |
| 90 | go func() { |
| 91 | var line string |
| 92 | var err error |
| 93 | |
| 94 | signal.Notify(interrupt, os.Interrupt) |
| 95 | defer signal.Stop(interrupt) |
| 96 | |
| 97 | inFile, isInputFile := inv.Stdin.(*os.File) |
| 98 | if opts.Secret && isInputFile && isatty.IsTerminal(inFile.Fd()) { |
| 99 | line, err = readSecretInput(inFile, inv.Stdout) |
| 100 | } else { |
| 101 | line, err = readUntil(inv.Stdin, '\n') |
| 102 | |
| 103 | // Check if the first line beings with JSON object or array chars. |
| 104 | // This enables multiline JSON to be pasted into an input, and have |
| 105 | // it parse properly. |
| 106 | if err == nil && (strings.HasPrefix(line, "{") || strings.HasPrefix(line, "[")) { |
| 107 | line, err = promptJSON(inv.Stdin, line) |
| 108 | } |
| 109 | } |