| Abhay Kumar | a61c522 | 2025-11-10 07:32:50 +0000 | [diff] [blame] | 1 | package speakeasy |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io" |
| 6 | "os" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // Ask the user to enter a password with input hidden. prompt is a string to |
| 11 | // display before the user's input. Returns the provided password, or an error |
| 12 | // if the command failed. |
| 13 | func Ask(prompt string) (password string, err error) { |
| 14 | return FAsk(os.Stdout, prompt) |
| 15 | } |
| 16 | |
| 17 | // FAsk is the same as Ask, except it is possible to specify the file to write |
| 18 | // the prompt to. If 'nil' is passed as the writer, no prompt will be written. |
| 19 | func FAsk(wr io.Writer, prompt string) (password string, err error) { |
| 20 | if wr != nil && prompt != "" { |
| 21 | fmt.Fprint(wr, prompt) // Display the prompt. |
| 22 | } |
| 23 | password, err = getPassword() |
| 24 | |
| 25 | // Carriage return after the user input. |
| 26 | if wr != nil { |
| 27 | fmt.Fprintln(wr, "") |
| 28 | } |
| 29 | return |
| 30 | } |
| 31 | |
| 32 | func readline() (value string, err error) { |
| 33 | var valb []byte |
| 34 | var n int |
| 35 | b := make([]byte, 1) |
| 36 | for { |
| 37 | // read one byte at a time so we don't accidentally read extra bytes |
| 38 | n, err = os.Stdin.Read(b) |
| 39 | if err != nil && err != io.EOF { |
| 40 | return "", err |
| 41 | } |
| 42 | if n == 0 || b[0] == '\n' { |
| 43 | break |
| 44 | } |
| 45 | valb = append(valb, b[0]) |
| 46 | } |
| 47 | |
| 48 | return strings.TrimSuffix(string(valb), "\r"), nil |
| 49 | } |