prompter.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package prompt
  17. import (
  18. "fmt"
  19. "strings"
  20. "github.com/peterh/liner"
  21. )
  22. // Stdin holds the stdin line reader (also using stdout for printing prompts).
  23. // Only this reader may be used for input because it keeps an internal buffer.
  24. var Stdin = newTerminalPrompter()
  25. // UserPrompter defines the methods needed by the console to prompt the user for
  26. // various types of inputs.
  27. type UserPrompter interface {
  28. // PromptInput displays the given prompt to the user and requests some textual
  29. // data to be entered, returning the input of the user.
  30. PromptInput(prompt string) (string, error)
  31. // PromptPassword displays the given prompt to the user and requests some textual
  32. // data to be entered, but one which must not be echoed out into the terminal.
  33. // The method returns the input provided by the user.
  34. PromptPassword(prompt string) (string, error)
  35. // PromptConfirm displays the given prompt to the user and requests a boolean
  36. // choice to be made, returning that choice.
  37. PromptConfirm(prompt string) (bool, error)
  38. // SetHistory sets the input scrollback history that the prompter will allow
  39. // the user to scroll back to.
  40. SetHistory(history []string)
  41. // AppendHistory appends an entry to the scrollback history. It should be called
  42. // if and only if the prompt to append was a valid command.
  43. AppendHistory(command string)
  44. // ClearHistory clears the entire history
  45. ClearHistory()
  46. // SetWordCompleter sets the completion function that the prompter will call to
  47. // fetch completion candidates when the user presses tab.
  48. SetWordCompleter(completer WordCompleter)
  49. }
  50. // WordCompleter takes the currently edited line with the cursor position and
  51. // returns the completion candidates for the partial word to be completed. If
  52. // the line is "Hello, wo!!!" and the cursor is before the first '!', ("Hello,
  53. // wo!!!", 9) is passed to the completer which may returns ("Hello, ", {"world",
  54. // "Word"}, "!!!") to have "Hello, world!!!".
  55. type WordCompleter func(line string, pos int) (string, []string, string)
  56. // terminalPrompter is a UserPrompter backed by the liner package. It supports
  57. // prompting the user for various input, among others for non-echoing password
  58. // input.
  59. type terminalPrompter struct {
  60. *liner.State
  61. warned bool
  62. supported bool
  63. normalMode liner.ModeApplier
  64. rawMode liner.ModeApplier
  65. }
  66. // newTerminalPrompter creates a liner based user input prompter working off the
  67. // standard input and output streams.
  68. func newTerminalPrompter() *terminalPrompter {
  69. p := new(terminalPrompter)
  70. // Get the original mode before calling NewLiner.
  71. // This is usually regular "cooked" mode where characters echo.
  72. normalMode, _ := liner.TerminalMode()
  73. // Turn on liner. It switches to raw mode.
  74. p.State = liner.NewLiner()
  75. rawMode, err := liner.TerminalMode()
  76. if err != nil || !liner.TerminalSupported() {
  77. p.supported = false
  78. } else {
  79. p.supported = true
  80. p.normalMode = normalMode
  81. p.rawMode = rawMode
  82. // Switch back to normal mode while we're not prompting.
  83. normalMode.ApplyMode()
  84. }
  85. p.SetCtrlCAborts(true)
  86. p.SetTabCompletionStyle(liner.TabPrints)
  87. p.SetMultiLineMode(true)
  88. return p
  89. }
  90. // PromptInput displays the given prompt to the user and requests some textual
  91. // data to be entered, returning the input of the user.
  92. func (p *terminalPrompter) PromptInput(prompt string) (string, error) {
  93. if p.supported {
  94. p.rawMode.ApplyMode()
  95. defer p.normalMode.ApplyMode()
  96. } else {
  97. // liner tries to be smart about printing the prompt
  98. // and doesn't print anything if input is redirected.
  99. // Un-smart it by printing the prompt always.
  100. fmt.Print(prompt)
  101. prompt = ""
  102. defer fmt.Println()
  103. }
  104. return p.State.Prompt(prompt)
  105. }
  106. // PromptPassword displays the given prompt to the user and requests some textual
  107. // data to be entered, but one which must not be echoed out into the terminal.
  108. // The method returns the input provided by the user.
  109. func (p *terminalPrompter) PromptPassword(prompt string) (passwd string, err error) {
  110. if p.supported {
  111. p.rawMode.ApplyMode()
  112. defer p.normalMode.ApplyMode()
  113. return p.State.PasswordPrompt(prompt)
  114. }
  115. if !p.warned {
  116. fmt.Println("!! Unsupported terminal, password will be echoed.")
  117. p.warned = true
  118. }
  119. // Just as in Prompt, handle printing the prompt here instead of relying on liner.
  120. fmt.Print(prompt)
  121. passwd, err = p.State.Prompt("")
  122. fmt.Println()
  123. return passwd, err
  124. }
  125. // PromptConfirm displays the given prompt to the user and requests a boolean
  126. // choice to be made, returning that choice.
  127. func (p *terminalPrompter) PromptConfirm(prompt string) (bool, error) {
  128. input, err := p.Prompt(prompt + " [y/n] ")
  129. if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
  130. return true, nil
  131. }
  132. return false, err
  133. }
  134. // SetHistory sets the input scrollback history that the prompter will allow
  135. // the user to scroll back to.
  136. func (p *terminalPrompter) SetHistory(history []string) {
  137. p.State.ReadHistory(strings.NewReader(strings.Join(history, "\n")))
  138. }
  139. // AppendHistory appends an entry to the scrollback history.
  140. func (p *terminalPrompter) AppendHistory(command string) {
  141. p.State.AppendHistory(command)
  142. }
  143. // ClearHistory clears the entire history
  144. func (p *terminalPrompter) ClearHistory() {
  145. p.State.ClearHistory()
  146. }
  147. // SetWordCompleter sets the completion function that the prompter will call to
  148. // fetch completion candidates when the user presses tab.
  149. func (p *terminalPrompter) SetWordCompleter(completer WordCompleter) {
  150. p.State.SetWordCompleter(liner.WordCompleter(completer))
  151. }