module main import os import strconv // Prompter is the one way vpac asks the user anything: a yes or no // question, the go-ahead of a transaction, a pick among numbered choices. // every prompt of every command goes through the one its TransUI carries // (ui.yesno, ui.noyes, ui.proceed, ui.choose), so a second frontend answers // them all by bringing its own. the terminal is the default. // noconfirm is --noconfirm, the policy every prompter honours: each question // is still shown, and its default taken without waiting for an answer, so an // unattended run never blocks interface Prompter { mut: noconfirm bool // confirm asks a yes or no question; preset is what an empty answer takes confirm(msg string, preset bool) bool // proceed asks for the go-ahead of a transaction: pacman's 'Proceed with // installation? [Y/n]', where an empty answer is yes. noconfirm gives it proceed(msg string) bool // choose asks for one of the choices and returns its index; the first is // the preset. the terminal has listed them already, and asks a number choose(msg string, choices []string) int // pick asks for any number of the choices and returns which, one bool // per choice; all of them is the preset. the terminal has listed them // already, and asks for numbers and ranges pick(msg string, count int) []bool } // TermPrompter asks on the terminal, following pacman's question() and // select_question(). every prompt goes to stderr, the noconfirm echo too, so // piped output (install -p, search -q) carries only results; pacman prints // the noconfirm echo on stdout, which mixes it into such output struct TermPrompter { mut: noconfirm bool } // StdinEnd is what stdin_line answers once stdin has nothing left struct StdinEnd { Error } fn (e StdinEnd) msg() string { return 'end of input' } // stdin_line reads one line from stdin, without its newline; a last line // that has none is a line too, as pacman's fgets gives it. the end of input // is a StdinEnd, and a read error (stdin closed, or a directory) an error of // its own: a prompt takes both as no, the way pacman's question() takes the // NULL fgets answers to both, while a reader of a whole list must not take // a cut for its end. os.get_raw_line panics on the read error, and keeps the // newline, which a caller then has to tell an empty answer from the end by fn stdin_line() !string { mut buf := &u8(unsafe { nil }) mut size := uint(0) n := C.getline(voidptr(&buf), voidptr(&size), C.stdin) // getline allocates with libc's malloc, even when it fails defer { unsafe { C.free(buf) } } if n < 0 { if C.ferror(C.stdin) != 0 { return error('could not read stdin: ${os.posix_get_error_msg(C.errno)}') } return StdinEnd{} } // the line is cloned out of getline's buffer either way: a plain slice // would still point into what the defer frees line := unsafe { tos(buf, n) } return if line.ends_with('\n') { line[..line.len - 1].clone() } else { line.clone() } } // the answer labels of a question, the default in bold fn q_yes_no() string { return '[' + erole('default', 'Y') + '/n]' } fn q_no_yes() string { return '[y/' + erole('default', 'N') + ']' } // confirm follows pacman's question(): an empty answer takes the preset, // y/yes is yes, and anything else is no — the end of input and a stdin that // cannot be read too, whatever the preset, so an unattended run that meant // no answer never says yes. with noconfirm the question is printed and the // preset taken without reading stdin fn (mut p TermPrompter) confirm(msg string, preset bool) bool { label := if preset { q_yes_no() } else { q_no_yes() } os.flush() if p.noconfirm { eprintln(erole('prompt', '${msg} ${label}')) return preset } eprint(erole('prompt', '${msg} ${label} ')) line := stdin_line() or { return false } return match line.trim_space().to_lower() { '' { preset } 'y', 'yes' { true } else { false } } } // proceed is confirm with a yes preset; with noconfirm the echo says the // yes came from the flag fn (mut p TermPrompter) proceed(msg string) bool { if p.noconfirm { os.flush() eprintln(erole('prompt', '${msg} ${q_yes_no()} (yes, --noconfirm)')) return true } return p.confirm(msg, true) } // choose follows pacman's select_question(): it asks for a number from 1 to // the count of choices, where an empty answer and end of input (or a stdin // that cannot be read) take the first, and an answer that is not one of the // numbers asks again. with noconfirm the question is printed and the first // taken without reading stdin. end of input is safe to default here: the // transaction's own 'proceed?' comes after and takes end of input as no fn (mut p TermPrompter) choose(msg string, choices []string) int { count := choices.len label := '[1-${count}, default ' + erole('default', '1') + ']' os.flush() if p.noconfirm { eprintln(erole('prompt', '${msg} ${label}')) return 0 } for { eprint(erole('prompt', '${msg} ${label} ')) answer := (stdin_line() or { return 0 }).trim_space() if answer == '' { return 0 } n := strconv.atoi(answer) or { 0 } if n >= 1 && n <= count { return n - 1 } eprintln('invalid number: ${answer}') } } // parse_selection reads an answer to pick the way pacman's // multiselect_parse does: numbers and ranges (2-4) parted by spaces or // commas, a leading ^ leaving one out. everything starts selected; an answer // whose first word selects starts from nothing instead, so '2 5' is those // two and '^3' is all but the third fn parse_selection(answer string, count int) ![]bool { mut picked := []bool{len: count, init: true} words := answer.replace(',', ' ').fields() for i, word in words { mut text := word include := !text.starts_with('^') if !include { text = text[1..] } else if i == 0 { picked = []bool{len: count} } // a range's dash is looked for past the first byte, as pacman does mut first := text mut last := ?string(none) if text.len > 1 { if dash := text.index_after('-', 1) { first = text[..dash] last = text[dash + 1..] } } start := selection_index(first, 1, count)! mut end := start if upto := last { end = selection_index(upto, start, count)! } for n in start .. end + 1 { picked[n - 1] = include } } return picked } // selection_index is one number of a selection, within its bounds fn selection_index(text string, min int, max int) !int { n := strconv.atoi(text) or { return error('invalid number: ${text}') } if n < min || n > max { return error('invalid value: ${n} is not between ${min} and ${max}') } return n } // pick follows pacman's multiselect_question(): an empty answer takes them // all, an answer that does not parse asks again. with noconfirm the // question is printed and all taken. end of input, or a stdin that cannot be // read, selects nothing: pacman fails the target there, and nothing chosen // is the same refusal without the abort fn (mut p TermPrompter) pick(msg string, count int) []bool { label := '(default=' + erole('default', 'all') + '):' os.flush() if p.noconfirm { eprintln(erole('prompt', '${msg} ${label}')) return []bool{len: count, init: true} } for { eprint(erole('prompt', '${msg} ${label} ')) answer := (stdin_line() or { return []bool{len: count} }).trim_space() if answer == '' { return []bool{len: count, init: true} } return parse_selection(answer, count) or { eprintln(err.msg()) continue } } return []bool{len: count} } // yesno asks a question whose empty answer is yes. the live display is // paused first, as for every prompt: a redraw would erase the question and // leave the program waiting on one nobody sees fn (mut ui TransUI) yesno(msg string) bool { ui.pause() return ui.prompt.confirm(msg, true) } // noyes asks a question whose empty answer is no fn (mut ui TransUI) noyes(msg string) bool { ui.pause() return ui.prompt.confirm(msg, false) } // proceed asks for the go-ahead of a transaction fn (mut ui TransUI) proceed(msg string) bool { ui.pause() return ui.prompt.proceed(msg) } // choose asks for one of the choices and returns its index fn (mut ui TransUI) choose(msg string, choices []string) int { ui.pause() return ui.prompt.choose(msg, choices) } // pick asks for any number of count choices, already listed fn (mut ui TransUI) pick(msg string, count int) []bool { ui.pause() return ui.prompt.pick(msg, count) }