Skip to content

Commit dff9b42

Browse files
committed
cmd/geth, cmd/utils: improve input handling
These changes make prompting behave consistently on all platforms: * The input buffer is now global. Buffering was previously set up for each prompt, which can cause weird behaviour, e.g. when running "geth account update <input.txt" where input.txt contains three lines. In this case, the first password prompt would fill up the buffer with all lines and then use only the first one. * Print the "unsupported terminal" warning only once. Now that stdin prompting has global state, we can use it to track the warning there. * Work around small liner issues, particularly on Windows. Prompting didn't work under most of the third-party terminal emulators on Windows because liner assumes line editing is always available.
1 parent 83877a0 commit dff9b42

7 files changed

Lines changed: 128 additions & 121 deletions

File tree

‎cmd/geth/chaincmd.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ func exportChain(ctx *cli.Context) {
116116
}
117117

118118
func removeDB(ctx *cli.Context) {
119-
confirm, err := utils.PromptConfirm("Remove local database?")
119+
confirm, err := utils.Stdin.ConfirmPrompt("Remove local database?")
120120
if err != nil {
121121
utils.Fatalf("%v", err)
122122
}

‎cmd/geth/js.go‎

Lines changed: 20 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
package main
1818

1919
import (
20-
"bufio"
2120
"fmt"
2221
"math/big"
2322
"os"
@@ -46,30 +45,6 @@ var (
4645
exit = regexp.MustCompile("^\\s*exit\\s*;*\\s*$")
4746
)
4847

49-
type prompter interface {
50-
AppendHistory(string)
51-
Prompt(p string) (string, error)
52-
PasswordPrompt(p string) (string, error)
53-
}
54-
55-
type dumbterm struct{ r *bufio.Reader }
56-
57-
func (r dumbterm) Prompt(p string) (string, error) {
58-
fmt.Print(p)
59-
line, err := r.r.ReadString('\n')
60-
return strings.TrimSuffix(line, "\n"), err
61-
}
62-
63-
func (r dumbterm) PasswordPrompt(p string) (string, error) {
64-
fmt.Println("!! Unsupported terminal, password will echo.")
65-
fmt.Print(p)
66-
input, err := bufio.NewReader(os.Stdin).ReadString('\n')
67-
fmt.Println()
68-
return input, err
69-
}
70-
71-
func (r dumbterm) AppendHistory(string) {}
72-
7348
type jsre struct {
7449
re *re.JSRE
7550
stack *node.Node
@@ -78,7 +53,6 @@ type jsre struct {
7853
atexit func()
7954
corsDomain string
8055
client rpc.Client
81-
prompter
8256
}
8357

8458
func makeCompleter(re *jsre) liner.WordCompleter {
@@ -106,27 +80,11 @@ func newLightweightJSRE(docRoot string, client rpc.Client, datadir string, inter
10680
js := &jsre{ps1: "> "}
10781
js.wait = make(chan *big.Int)
10882
js.client = client
109-
11083
js.re = re.New(docRoot)
11184
if err := js.apiBindings(); err != nil {
11285
utils.Fatalf("Unable to initialize console - %v", err)
11386
}
114-
115-
if !liner.TerminalSupported() || !interactive {
116-
js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
117-
} else {
118-
lr := liner.NewLiner()
119-
js.withHistory(datadir, func(hist *os.File) { lr.ReadHistory(hist) })
120-
lr.SetCtrlCAborts(true)
121-
lr.SetWordCompleter(makeCompleter(js))
122-
lr.SetTabCompletionStyle(liner.TabPrints)
123-
js.prompter = lr
124-
js.atexit = func() {
125-
js.withHistory(datadir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
126-
lr.Close()
127-
close(js.wait)
128-
}
129-
}
87+
js.setupInput(datadir)
13088
return js
13189
}
13290

@@ -136,28 +94,27 @@ func newJSRE(stack *node.Node, docRoot, corsDomain string, client rpc.Client, in
13694
js.corsDomain = corsDomain
13795
js.wait = make(chan *big.Int)
13896
js.client = client
139-
14097
js.re = re.New(docRoot)
14198
if err := js.apiBindings(); err != nil {
14299
utils.Fatalf("Unable to connect - %v", err)
143100
}
101+
js.setupInput(stack.DataDir())
102+
return js
103+
}
144104

145-
if !liner.TerminalSupported() || !interactive {
146-
js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
147-
} else {
148-
lr := liner.NewLiner()
149-
js.withHistory(stack.DataDir(), func(hist *os.File) { lr.ReadHistory(hist) })
150-
lr.SetCtrlCAborts(true)
151-
lr.SetWordCompleter(makeCompleter(js))
152-
lr.SetTabCompletionStyle(liner.TabPrints)
153-
js.prompter = lr
154-
js.atexit = func() {
155-
js.withHistory(stack.DataDir(), func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
156-
lr.Close()
157-
close(js.wait)
158-
}
105+
func (self *jsre) setupInput(datadir string) {
106+
self.withHistory(datadir, func(hist *os.File) { utils.Stdin.ReadHistory(hist) })
107+
utils.Stdin.SetCtrlCAborts(true)
108+
utils.Stdin.SetWordCompleter(makeCompleter(self))
109+
utils.Stdin.SetTabCompletionStyle(liner.TabPrints)
110+
self.atexit = func() {
111+
self.withHistory(datadir, func(hist *os.File) {
112+
hist.Truncate(0)
113+
utils.Stdin.WriteHistory(hist)
114+
})
115+
utils.Stdin.Close()
116+
close(self.wait)
159117
}
160-
return js
161118
}
162119

163120
func (self *jsre) batch(statement string) {
@@ -290,7 +247,7 @@ func (js *jsre) apiBindings() error {
290247
}
291248

292249
func (self *jsre) AskPassword() (string, bool) {
293-
pass, err := self.PasswordPrompt("Passphrase: ")
250+
pass, err := utils.Stdin.PasswordPrompt("Passphrase: ")
294251
if err != nil {
295252
return "", false
296253
}
@@ -315,7 +272,7 @@ func (self *jsre) ConfirmTransaction(tx string) bool {
315272

316273
func (self *jsre) UnlockAccount(addr []byte) bool {
317274
fmt.Printf("Please unlock account %x.\n", addr)
318-
pass, err := self.PasswordPrompt("Passphrase: ")
275+
pass, err := utils.Stdin.PasswordPrompt("Passphrase: ")
319276
if err != nil {
320277
return false
321278
}
@@ -365,7 +322,7 @@ func (self *jsre) interactive() {
365322
go func() {
366323
defer close(inputln)
367324
for {
368-
line, err := self.Prompt(<-prompt)
325+
line, err := utils.Stdin.Prompt(<-prompt)
369326
if err != nil {
370327
if err == liner.ErrPromptAborted { // ctrl-C
371328
self.resetPrompt()
@@ -404,7 +361,7 @@ func (self *jsre) interactive() {
404361
self.setIndent()
405362
if indentCount <= 0 {
406363
if mustLogInHistory(str) {
407-
self.AppendHistory(str[:len(str)-1])
364+
utils.Stdin.AppendHistory(str[:len(str)-1])
408365
}
409366
self.parseInput(str)
410367
str = ""

‎cmd/geth/js_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ func testREPL(t *testing.T, config func(*eth.Config)) (string, *testjethre, *nod
9494
t.Fatal(err)
9595
}
9696
// Create a networkless protocol stack
97-
stack, err := node.New(&node.Config{PrivateKey: testNodeKey, Name: "test", NoDiscovery: true})
97+
stack, err := node.New(&node.Config{DataDir: tmp, PrivateKey: testNodeKey, Name: "test", NoDiscovery: true})
9898
if err != nil {
9999
t.Fatalf("failed to create node: %v", err)
100100
}

‎cmd/geth/main.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
373373
app.After = func(ctx *cli.Context) error {
374374
logger.Flush()
375375
debug.Exit()
376+
utils.Stdin.Close() // Resets terminal mode.
376377
return nil
377378
}
378379
}
@@ -595,12 +596,12 @@ func getPassPhrase(prompt string, confirmation bool, i int, passwords []string)
595596
}
596597
// Otherwise prompt the user for the password
597598
fmt.Println(prompt)
598-
password, err := utils.PromptPassword("Passphrase: ", true)
599+
password, err := utils.Stdin.PasswordPrompt("Passphrase: ")
599600
if err != nil {
600601
utils.Fatalf("Failed to read passphrase: %v", err)
601602
}
602603
if confirmation {
603-
confirm, err := utils.PromptPassword("Repeat passphrase: ", false)
604+
confirm, err := utils.Stdin.PasswordPrompt("Repeat passphrase: ")
604605
if err != nil {
605606
utils.Fatalf("Failed to read passphrase confirmation: %v", err)
606607
}

‎cmd/utils/cmd.go‎

Lines changed: 0 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,11 @@
1818
package utils
1919

2020
import (
21-
"bufio"
2221
"fmt"
2322
"io"
2423
"os"
2524
"os/signal"
2625
"regexp"
27-
"strings"
2826

2927
"github.com/ethereum/go-ethereum/common"
3028
"github.com/ethereum/go-ethereum/core"
@@ -34,17 +32,12 @@ import (
3432
"github.com/ethereum/go-ethereum/logger/glog"
3533
"github.com/ethereum/go-ethereum/node"
3634
"github.com/ethereum/go-ethereum/rlp"
37-
"github.com/peterh/liner"
3835
)
3936

4037
const (
4138
importBatchSize = 2500
4239
)
4340

44-
var (
45-
interruptCallbacks = []func(os.Signal){}
46-
)
47-
4841
func openLogFile(Datadir string, filename string) *os.File {
4942
path := common.AbsolutePath(Datadir, filename)
5043
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
@@ -54,49 +47,6 @@ func openLogFile(Datadir string, filename string) *os.File {
5447
return file
5548
}
5649

57-
func PromptConfirm(prompt string) (bool, error) {
58-
var (
59-
input string
60-
err error
61-
)
62-
prompt = prompt + " [y/N] "
63-
64-
// if liner.TerminalSupported() {
65-
// fmt.Println("term")
66-
// lr := liner.NewLiner()
67-
// defer lr.Close()
68-
// input, err = lr.Prompt(prompt)
69-
// } else {
70-
fmt.Print(prompt)
71-
input, err = bufio.NewReader(os.Stdin).ReadString('\n')
72-
fmt.Println()
73-
// }
74-
75-
if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
76-
return true, nil
77-
} else {
78-
return false, nil
79-
}
80-
81-
return false, err
82-
}
83-
84-
func PromptPassword(prompt string, warnTerm bool) (string, error) {
85-
if liner.TerminalSupported() {
86-
lr := liner.NewLiner()
87-
defer lr.Close()
88-
return lr.PasswordPrompt(prompt)
89-
}
90-
if warnTerm {
91-
fmt.Println("!! Unsupported terminal, password will be echoed.")
92-
}
93-
fmt.Print(prompt)
94-
input, err := bufio.NewReader(os.Stdin).ReadString('\n')
95-
input = strings.TrimRight(input, "\r\n")
96-
fmt.Println()
97-
return input, err
98-
}
99-
10050
// Fatalf formats a message to standard error and exits the program.
10151
// The message is also printed to standard output if standard error
10252
// is redirected to a different file.

‎cmd/utils/input.go‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Copyright 2016 The go-ethereum Authors
2+
// This file is part of go-ethereum.
3+
//
4+
// go-ethereum is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU 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+
// go-ethereum 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 General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU General Public License
15+
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package utils
18+
19+
import (
20+
"fmt"
21+
"strings"
22+
23+
"github.com/peterh/liner"
24+
)
25+
26+
// Holds the stdin line reader.
27+
// Only this reader may be used for input because it keeps
28+
// an internal buffer.
29+
var Stdin = newUserInputReader()
30+
31+
type userInputReader struct {
32+
*liner.State
33+
warned bool
34+
supported bool
35+
normalMode liner.ModeApplier
36+
rawMode liner.ModeApplier
37+
}
38+
39+
func newUserInputReader() *userInputReader {
40+
r := new(userInputReader)
41+
// Get the original mode before calling NewLiner.
42+
// This is usually regular "cooked" mode where characters echo.
43+
normalMode, _ := liner.TerminalMode()
44+
// Turn on liner. It switches to raw mode.
45+
r.State = liner.NewLiner()
46+
rawMode, err := liner.TerminalMode()
47+
if err != nil || !liner.TerminalSupported() {
48+
r.supported = false
49+
} else {
50+
r.supported = true
51+
r.normalMode = normalMode
52+
r.rawMode = rawMode
53+
// Switch back to normal mode while we're not prompting.
54+
normalMode.ApplyMode()
55+
}
56+
return r
57+
}
58+
59+
func (r *userInputReader) Prompt(prompt string) (string, error) {
60+
if r.supported {
61+
r.rawMode.ApplyMode()
62+
defer r.normalMode.ApplyMode()
63+
} else {
64+
// liner tries to be smart about printing the prompt
65+
// and doesn't print anything if input is redirected.
66+
// Un-smart it by printing the prompt always.
67+
fmt.Print(prompt)
68+
prompt = ""
69+
defer fmt.Println()
70+
}
71+
return r.State.Prompt(prompt)
72+
}
73+
74+
func (r *userInputReader) PasswordPrompt(prompt string) (passwd string, err error) {
75+
if r.supported {
76+
r.rawMode.ApplyMode()
77+
defer r.normalMode.ApplyMode()
78+
return r.State.PasswordPrompt(prompt)
79+
}
80+
if !r.warned {
81+
fmt.Println("!! Unsupported terminal, password will be echoed.")
82+
r.warned = true
83+
}
84+
// Just as in Prompt, handle printing the prompt here instead of relying on liner.
85+
fmt.Print(prompt)
86+
passwd, err = r.State.Prompt("")
87+
fmt.Println()
88+
return passwd, err
89+
}
90+
91+
func (r *userInputReader) ConfirmPrompt(prompt string) (bool, error) {
92+
prompt = prompt + " [y/N] "
93+
input, err := r.Prompt(prompt)
94+
if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
95+
return true, nil
96+
}
97+
return false, err
98+
}

0 commit comments

Comments
 (0)