prompter.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 console
  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 promt 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 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. // SetWordCompleter sets the completion function that the prompter will call to
  45. // fetch completion candidates when the user presses tab.
  46. SetWordCompleter(completer WordCompleter)
  47. }
  48. // WordCompleter takes the currently edited line with the cursor position and
  49. // returns the completion candidates for the partial word to be completed. If
  50. // the line is "Hello, wo!!!" and the cursor is before the first '!', ("Hello,
  51. // wo!!!", 9) is passed to the completer which may returns ("Hello, ", {"world",
  52. // "Word"}, "!!!") to have "Hello, world!!!".
  53. type WordCompleter func(line string, pos int) (string, []string, string)
  54. // terminalPrompter is a UserPrompter backed by the liner package. It supports
  55. // prompting the user for various input, among others for non-echoing password
  56. // input.
  57. type terminalPrompter struct {
  58. *liner.State
  59. warned bool
  60. supported bool
  61. normalMode liner.ModeApplier
  62. rawMode liner.ModeApplier
  63. }
  64. // newTerminalPrompter creates a liner based user input prompter working off the
  65. // standard input and output streams.
  66. func newTerminalPrompter() *terminalPrompter {
  67. p := new(terminalPrompter)
  68. // Get the original mode before calling NewLiner.
  69. // This is usually regular "cooked" mode where characters echo.
  70. normalMode, _ := liner.TerminalMode()
  71. // Turn on liner. It switches to raw mode.
  72. p.State = liner.NewLiner()
  73. rawMode, err := liner.TerminalMode()
  74. if err != nil || !liner.TerminalSupported() {
  75. p.supported = false
  76. } else {
  77. p.supported = true
  78. p.normalMode = normalMode
  79. p.rawMode = rawMode
  80. // Switch back to normal mode while we're not prompting.
  81. normalMode.ApplyMode()
  82. }
  83. p.SetCtrlCAborts(true)
  84. p.SetTabCompletionStyle(liner.TabPrints)
  85. p.SetMultiLineMode(true)
  86. return p
  87. }
  88. // PromptInput displays the given prompt to the user and requests some textual
  89. // data to be entered, returning the input of the user.
  90. func (p *terminalPrompter) PromptInput(prompt string) (string, error) {
  91. if p.supported {
  92. p.rawMode.ApplyMode()
  93. defer p.normalMode.ApplyMode()
  94. } else {
  95. // liner tries to be smart about printing the prompt
  96. // and doesn't print anything if input is redirected.
  97. // Un-smart it by printing the prompt always.
  98. fmt.Print(prompt)
  99. prompt = ""
  100. defer fmt.Println()
  101. }
  102. return p.State.Prompt(prompt)
  103. }
  104. // PromptPassword displays the given prompt to the user and requests some textual
  105. // data to be entered, but one which must not be echoed out into the terminal.
  106. // The method returns the input provided by the user.
  107. func (p *terminalPrompter) PromptPassword(prompt string) (passwd string, err error) {
  108. if p.supported {
  109. p.rawMode.ApplyMode()
  110. defer p.normalMode.ApplyMode()
  111. return p.State.PasswordPrompt(prompt)
  112. }
  113. if !p.warned {
  114. fmt.Println("!! Unsupported terminal, password will be echoed.")
  115. p.warned = true
  116. }
  117. // Just as in Prompt, handle printing the prompt here instead of relying on liner.
  118. fmt.Print(prompt)
  119. passwd, err = p.State.Prompt("")
  120. fmt.Println()
  121. return passwd, err
  122. }
  123. // PromptConfirm displays the given prompt to the user and requests a boolean
  124. // choice to be made, returning that choice.
  125. func (p *terminalPrompter) PromptConfirm(prompt string) (bool, error) {
  126. input, err := p.Prompt(prompt + " [y/N] ")
  127. if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
  128. return true, nil
  129. }
  130. return false, err
  131. }
  132. // SetHistory sets the the input scrollback history that the prompter will allow
  133. // the user to scroll back to.
  134. func (p *terminalPrompter) SetHistory(history []string) {
  135. p.State.ReadHistory(strings.NewReader(strings.Join(history, "\n")))
  136. }
  137. // AppendHistory appends an entry to the scrollback history. It should be called
  138. // if and only if the prompt to append was a valid command.
  139. func (p *terminalPrompter) AppendHistory(command string) {
  140. p.State.AppendHistory(command)
  141. }
  142. // SetWordCompleter sets the completion function that the prompter will call to
  143. // fetch completion candidates when the user presses tab.
  144. func (p *terminalPrompter) SetWordCompleter(completer WordCompleter) {
  145. p.State.SetWordCompleter(liner.WordCompleter(completer))
  146. }