vpac / src / prompt.v
247 lines · 228 sloc · 8.22 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1module main
2
3import os
4import strconv
5
6// Prompter is the one way vpac asks the user anything: a yes or no
7// question, the go-ahead of a transaction, a pick among numbered choices.
8// every prompt of every command goes through the one its TransUI carries
9// (ui.yesno, ui.noyes, ui.proceed, ui.choose), so a second frontend answers
10// them all by bringing its own. the terminal is the default.
11// noconfirm is --noconfirm, the policy every prompter honours: each question
12// is still shown, and its default taken without waiting for an answer, so an
13// unattended run never blocks
14interface Prompter {
15mut:
16 noconfirm bool
17 // confirm asks a yes or no question; preset is what an empty answer takes
18 confirm(msg string, preset bool) bool
19 // proceed asks for the go-ahead of a transaction: pacman's 'Proceed with
20 // installation? [Y/n]', where an empty answer is yes. noconfirm gives it
21 proceed(msg string) bool
22 // choose asks for one of the choices and returns its index; the first is
23 // the preset. the terminal has listed them already, and asks a number
24 choose(msg string, choices []string) int
25 // pick asks for any number of the choices and returns which, one bool
26 // per choice; all of them is the preset. the terminal has listed them
27 // already, and asks for numbers and ranges
28 pick(msg string, count int) []bool
29}
30
31// TermPrompter asks on the terminal, following pacman's question() and
32// select_question(). every prompt goes to stderr, the noconfirm echo too, so
33// piped output (install -p, search -q) carries only results; pacman prints
34// the noconfirm echo on stdout, which mixes it into such output
35struct TermPrompter {
36mut:
37 noconfirm bool
38}
39
40// StdinEnd is what stdin_line answers once stdin has nothing left
41struct StdinEnd {
42 Error
43}
44
45fn (e StdinEnd) msg() string {
46 return 'end of input'
47}
48
49// stdin_line reads one line from stdin, without its newline; a last line
50// that has none is a line too, as pacman's fgets gives it. the end of input
51// is a StdinEnd, and a read error (stdin closed, or a directory) an error of
52// its own: a prompt takes both as no, the way pacman's question() takes the
53// NULL fgets answers to both, while a reader of a whole list must not take
54// a cut for its end. os.get_raw_line panics on the read error, and keeps the
55// newline, which a caller then has to tell an empty answer from the end by
56fn stdin_line() !string {
57 mut buf := &u8(unsafe { nil })
58 mut size := uint(0)
59 n := C.getline(voidptr(&buf), voidptr(&size), C.stdin)
60 // getline allocates with libc's malloc, even when it fails
61 defer {
62 unsafe { C.free(buf) }
63 }
64 if n < 0 {
65 if C.ferror(C.stdin) != 0 {
66 return error('could not read stdin: ${os.posix_get_error_msg(C.errno)}')
67 }
68 return StdinEnd{}
69 }
70 // the line is cloned out of getline's buffer either way: a plain slice
71 // would still point into what the defer frees
72 line := unsafe { tos(buf, n) }
73 return if line.ends_with('\n') { line[..line.len - 1].clone() } else { line.clone() }
74}
75
76// the answer labels of a question, the default in bold
77fn q_yes_no() string {
78 return '[' + erole('default', 'Y') + '/n]'
79}
80
81fn q_no_yes() string {
82 return '[y/' + erole('default', 'N') + ']'
83}
84
85// confirm follows pacman's question(): an empty answer takes the preset,
86// y/yes is yes, and anything else is no — the end of input and a stdin that
87// cannot be read too, whatever the preset, so an unattended run that meant
88// no answer never says yes. with noconfirm the question is printed and the
89// preset taken without reading stdin
90fn (mut p TermPrompter) confirm(msg string, preset bool) bool {
91 label := if preset { q_yes_no() } else { q_no_yes() }
92 os.flush()
93 if p.noconfirm {
94 eprintln(erole('prompt', '${msg} ${label}'))
95 return preset
96 }
97 eprint(erole('prompt', '${msg} ${label} '))
98 line := stdin_line() or { return false }
99 return match line.trim_space().to_lower() {
100 '' { preset }
101 'y', 'yes' { true }
102 else { false }
103 }
104}
105
106// proceed is confirm with a yes preset; with noconfirm the echo says the
107// yes came from the flag
108fn (mut p TermPrompter) proceed(msg string) bool {
109 if p.noconfirm {
110 os.flush()
111 eprintln(erole('prompt', '${msg} ${q_yes_no()} (yes, --noconfirm)'))
112 return true
113 }
114 return p.confirm(msg, true)
115}
116
117// choose follows pacman's select_question(): it asks for a number from 1 to
118// the count of choices, where an empty answer and end of input (or a stdin
119// that cannot be read) take the first, and an answer that is not one of the
120// numbers asks again. with noconfirm the question is printed and the first
121// taken without reading stdin. end of input is safe to default here: the
122// transaction's own 'proceed?' comes after and takes end of input as no
123fn (mut p TermPrompter) choose(msg string, choices []string) int {
124 count := choices.len
125 label := '[1-${count}, default ' + erole('default', '1') + ']'
126 os.flush()
127 if p.noconfirm {
128 eprintln(erole('prompt', '${msg} ${label}'))
129 return 0
130 }
131 for {
132 eprint(erole('prompt', '${msg} ${label} '))
133 answer := (stdin_line() or { return 0 }).trim_space()
134 if answer == '' {
135 return 0
136 }
137 n := strconv.atoi(answer) or { 0 }
138 if n >= 1 && n <= count {
139 return n - 1
140 }
141 eprintln('invalid number: ${answer}')
142 }
143}
144
145// parse_selection reads an answer to pick the way pacman's
146// multiselect_parse does: numbers and ranges (2-4) parted by spaces or
147// commas, a leading ^ leaving one out. everything starts selected; an answer
148// whose first word selects starts from nothing instead, so '2 5' is those
149// two and '^3' is all but the third
150fn parse_selection(answer string, count int) ![]bool {
151 mut picked := []bool{len: count, init: true}
152 words := answer.replace(',', ' ').fields()
153 for i, word in words {
154 mut text := word
155 include := !text.starts_with('^')
156 if !include {
157 text = text[1..]
158 } else if i == 0 {
159 picked = []bool{len: count}
160 }
161 // a range's dash is looked for past the first byte, as pacman does
162 mut first := text
163 mut last := ?string(none)
164 if text.len > 1 {
165 if dash := text.index_after('-', 1) {
166 first = text[..dash]
167 last = text[dash + 1..]
168 }
169 }
170 start := selection_index(first, 1, count)!
171 mut end := start
172 if upto := last {
173 end = selection_index(upto, start, count)!
174 }
175 for n in start .. end + 1 {
176 picked[n - 1] = include
177 }
178 }
179 return picked
180}
181
182// selection_index is one number of a selection, within its bounds
183fn selection_index(text string, min int, max int) !int {
184 n := strconv.atoi(text) or { return error('invalid number: ${text}') }
185 if n < min || n > max {
186 return error('invalid value: ${n} is not between ${min} and ${max}')
187 }
188 return n
189}
190
191// pick follows pacman's multiselect_question(): an empty answer takes them
192// all, an answer that does not parse asks again. with noconfirm the
193// question is printed and all taken. end of input, or a stdin that cannot be
194// read, selects nothing: pacman fails the target there, and nothing chosen
195// is the same refusal without the abort
196fn (mut p TermPrompter) pick(msg string, count int) []bool {
197 label := '(default=' + erole('default', 'all') + '):'
198 os.flush()
199 if p.noconfirm {
200 eprintln(erole('prompt', '${msg} ${label}'))
201 return []bool{len: count, init: true}
202 }
203 for {
204 eprint(erole('prompt', '${msg} ${label} '))
205 answer := (stdin_line() or { return []bool{len: count} }).trim_space()
206 if answer == '' {
207 return []bool{len: count, init: true}
208 }
209 return parse_selection(answer, count) or {
210 eprintln(err.msg())
211 continue
212 }
213 }
214 return []bool{len: count}
215}
216
217// yesno asks a question whose empty answer is yes. the live display is
218// paused first, as for every prompt: a redraw would erase the question and
219// leave the program waiting on one nobody sees
220fn (mut ui TransUI) yesno(msg string) bool {
221 ui.pause()
222 return ui.prompt.confirm(msg, true)
223}
224
225// noyes asks a question whose empty answer is no
226fn (mut ui TransUI) noyes(msg string) bool {
227 ui.pause()
228 return ui.prompt.confirm(msg, false)
229}
230
231// proceed asks for the go-ahead of a transaction
232fn (mut ui TransUI) proceed(msg string) bool {
233 ui.pause()
234 return ui.prompt.proceed(msg)
235}
236
237// choose asks for one of the choices and returns its index
238fn (mut ui TransUI) choose(msg string, choices []string) int {
239 ui.pause()
240 return ui.prompt.choose(msg, choices)
241}
242
243// pick asks for any number of count choices, already listed
244fn (mut ui TransUI) pick(msg string, count int) []bool {
245 ui.pause()
246 return ui.prompt.pick(msg, count)
247}
248