aboutsummaryrefslogtreecommitdiff
path: root/pkg/cli/query.go
blob: 1f5d16c3147ae83ed4dd6898a5968c64f92243f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*******************************************************************************
*
* Copyright 2017 Stefan Majewsky <majewsky@gmx.net>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************/

package cli

import (
	"fmt"
	"io"
	"regexp"
	"strings"

	terminal "golang.org/x/crypto/ssh/terminal"
)

//cannot use `var errInterrupted = errors.New("Interrupted!")` because golint
//complains about the formatting of the error message
type errInterrupted struct{}

func (e errInterrupted) Error() string {
	return "Interrupted!"
}

type terminalTUI struct {
	i *Interface
}

func (t terminalTUI) ReadLine(prompt string) (string, error) {
	if prompt != "" {
		t.i.safeStdout().Write([]byte(strings.TrimSpace(prompt) + " "))
	}
	str, err := t.i.stdinBuf.ReadString('\n')
	return strings.TrimSpace(str), err
}

func (t terminalTUI) Confirm(question string) (bool, error) {
	out := t.i.safeStdout()
	out.Write([]byte(strings.TrimSpace(question) + " [y/n] "))

	buf := buffer{Input: t.i.stdin}
	for {
		switch string(buf.getNextInput()) {
		case "y", "Y":
			out.Write([]byte("-> yes\n"))
			return true, nil
		case "n", "N":
			out.Write([]byte("-> no\n"))
			return false, nil
		case "\x03": // Ctrl-C
			return false, errInterrupted{}
		}
	}
}

//Choice is a thing that the user can choose during Query().
type Choice struct {
	//If given, the choice can be selected by pressing the key that
	//produces this character.
	Shortcut byte
	//The display string that describes this choice.
	Text string
	//The string to return from Interface.Query().
	Return string
}

func (c Choice) hasShortcut() bool {
	return c.Shortcut != '\000'
}

func (t terminalTUI) Query(prompt string, choices ...Choice) (string, error) {
	if len(choices) == 0 {
		panic("no choices")
	}

	//disable line wrap; unexpected wrapping would confuse our cursor-moving code
	out := t.i.safeStdout()
	out.Write([]byte("\x1B[?7l"))
	defer out.Write([]byte("\x1B[?7h"))

	//display question
	out.Write([]byte(strings.TrimSuffix(prompt, "\n") + "\n"))
	selected := 0

	buf := buffer{Input: t.i.stdin}
OUTER:
	for {
		displayChoices(out, choices, selected)

		input := buf.getNextInput()
		if len(input) == 1 {
			//single character entered - check if a shortcut matches
			for idx, choice := range choices {
				if choice.Shortcut == input[0] {
					selected = idx
					break OUTER
				}
			}
		}

		switch string(input) {
		case "\r", "\n":
			break OUTER
		case "\x1B[A": // Up arrow key
			selected--
			if selected < 0 {
				selected = 0
			}
		case "\x1B[B": // Down arrow key
			selected++
			if selected >= len(choices) {
				selected = len(choices) - 1
			}
		case "\x03": // Ctrl-C
			return "", errInterrupted{}
		}

		//prepare to re-render choices
		removeDisplayLines(out, len(choices))
	}

	//clear query display
	removeDisplayLines(out, len(choices)+1)

	//display question + chosen answer
	fmt.Fprintf(out, "%s -> %s\n",
		strings.TrimSuffix(prompt, "\n"),
		strings.TrimSpace(choices[selected].Text),
	)

	return choices[selected].Return, nil
}

func removeDisplayLines(stdout io.Writer, n int) {
	for idx := 0; idx < n; idx++ {
		stdout.Write([]byte("\x1B[A\x1B[2K"))
	}
}

func displayChoices(out io.Writer, choices []Choice, selectedIndex int) {
	hasShortcuts := false
	for _, choice := range choices {
		if choice.hasShortcut() {
			hasShortcuts = true
			break
		}
	}

	for idx, choice := range choices {
		text := " " + strings.TrimSpace(choice.Text) + " \n"
		if hasShortcuts {
			shortcut := choice.Shortcut
			if !choice.hasShortcut() {
				shortcut = ' '
			}
			text = fmt.Sprintf(" [%c]%s", shortcut, text)
		}

		if idx == selectedIndex {
			out.Write(Styled(text, AnsiInverse).DisplayString(true))
		} else {
			out.Write([]byte(text))
		}
	}
}

var ansiEscapeRx = regexp.MustCompile(`^\x1B\[[\x20-\x3F]*[\x40-\x7E]`)

type buffer struct {
	Input io.Reader
	buf   [128]byte
	fill  int
}

func (b *buffer) getNextInput() []byte {
	//do we have a simple input character?
	if b.fill > 0 && b.buf[0] != '\x1B' {
		result := append([]byte(nil), b.buf[0])
		copy(b.buf[0:], b.buf[1:])
		b.fill--
		return result
	}

	//do we have a full ANSI escape sequence?
	match := ansiEscapeRx.Find(b.buf[0:b.fill])
	if match != nil {
		result := append([]byte(nil), match...)
		copy(b.buf[0:], b.buf[len(match):])
		b.fill -= len(match)
		return result
	}

	oldState, err := terminal.MakeRaw(0)
	if err != nil {
		panic(err)
	}
	defer terminal.Restore(0, oldState)

	//fill buffer some more
	n, err := b.Input.Read(b.buf[b.fill:])
	if err != nil {
		panic(err)
	}
	b.fill += n

	return b.getNextInput() //restart
}