@[has_globals] module main import os import sync import json2 #include // --ui ipc is vpac spoken to by a program instead of a person: a GUI, a web // UI or a test runs a mode as a child and reads json lines, one event per // line, from its stdout, answering the questions on its stdin. a root child // re-executed through the root provider keeps the same pipes, so it speaks // on them too. // every event is an object whose "type" says what it is; protocol is bumped // when an event changes in a way a reader must know about: a new event // type, a new question kind, a field whose meaning or presence changes, or // a new field a reader has to read to get the answer right. a field that // is only ever left out when empty and adds detail a reader may ignore // rides along without a bump, and is described at its struct. 2: clean's // build_root is absent when no invoker is known, and owner sends one event // per owner of a directory. 3: the select question (a group's members, // answered with a list of indices), clean's unused sync dbs, and the // changelog event. 4: a provides event of an expression or a bare file name // carries files, the paths matched in each entry's package. 5: clean's // build_size_partial, which makes build_size a floor const ipc_protocol = 5 // ui_kind is --ui: 'tty' draws for a terminal, 'ipc' speaks the protocol __global ui_kind = 'tty' // ipc_fd is the channel the events go out on, the stdout vpac was given. // fd 1 itself is pointed at stderr once the channel is open, so a plain // print of a mode not yet speaking the protocol lands in the log and never // in the channel __global ipc_fd = 1 __global ipc_started = false __global ipc_mu = sync.new_mutex() fn C.dup2(oldfd int, newfd int) int fn C.fcntl(fd int, cmd int, arg int) int fn ipc_on() bool { return ui_kind == 'ipc' } // ipc_start opens the channel. it runs in the process that does the work, // after the escalation: a re-executed child must find the original fds, and // opens its own channel. the channel is close-on-exec, so the builds and // hooks vpac runs never hold the frontend's pipe open fn ipc_start() { if ipc_started { return } ipc_started = true fd := C.dup(1) if fd < 0 { // a frontend would read plain text as the protocol: better no run eprintln(error_text('--ui ipc: could not open the channel on stdout')) exit(1) } if C.fcntl(fd, C.F_SETFD, C.FD_CLOEXEC) < 0 { // without it, every build and every hook keeps the frontend's pipe // open: said, since the channel is still good for this run eprintln('--ui ipc: could not mark the channel close-on-exec') } // dup2 answers its new fd (1) on success, so only a negative one is a // failure: fd 1 otherwise still carries the channel, and a plain print // of a mode that does not speak the protocol would land there if C.dup2(2, 1) < 0 { eprintln(error_text('--ui ipc: could not lead the logs onto stderr')) exit(1) } ipc_fd = fd // the texts of the events are plain color_flag = 'never' emit(HelloEvent{ protocol: ipc_protocol root: os.geteuid() == 0 }) } // emit writes one event as one line. the lock keeps the lines of the // download callbacks and the main thread whole fn emit[T](event T) { line := json2.encode(event) + '\n' ipc_mu.lock() ok := channel_write(line) ipc_mu.unlock() if !ok { // the reader of the channel is gone, so the run is over; stderr // still reaches a log, where a person may learn why eprintln('${error_text('the frontend closed the channel')} -- last event: ${line.trim_space()}') exit(1) } } // channel_write writes the whole line on the channel, and answers whether it // went out, through write(2) fn channel_write(line string) bool { return channel_write_to(ipc_fd, line, ipc_write) } // WriteFn is write(2) as channel_write_to calls it: what it wrote, and the // errno's code when that is -1. the system's in a run; a test's own to script the // interruptions and the stalls no real channel produces on demand type WriteFn = fn (fd int, buf voidptr, n int) (int, int) fn ipc_write(fd int, buf voidptr, n int) (int, int) { written := int(C.write(fd, buf, n)) return written, if written < 0 { C.errno } else { 0 } } // channel_write_to writes the whole line on fd. os.fd_write gives up without // a word when the reader is gone, and a half-written json line is garbage to // a frontend: every byte is seen out, any failure is reported. a write that // is interrupted is taken again, and a write that answers nothing has made // no progress, so it is a failure too — waiting it out would be an endless // loop for a channel nobody reads fn channel_write_to(fd int, line string, write WriteFn) bool { str := line.clone() mut p := unsafe { voidptr(uint(str.str)) } mut left := str.len for left > 0 { written, code := write(fd, p, left) if written < 0 { // a signal cut the write short of starting: errno.h's name for // it on this system, not a number if code == C.EINTR { continue } return false } if written == 0 { return false } left -= written p = unsafe { voidptr(uint(p) + uint(written)) } } return true } // HelpEvent is a help text, the overview or one mode's struct HelpEvent { kind string = 'help' @[json: 'type'] text string } // HelloEvent opens the stream: the protocol, and whether this process runs // as root (a child the root provider started) struct HelloEvent { kind string = 'hello' @[json: 'type'] protocol int root bool } // ExitEvent closes it with the exit status the process is about to have struct ExitEvent { kind string = 'exit' @[json: 'type'] status int } // ErrorEvent is an error line. target marks the error of one target a query // skipped and went on from; any other error ends the run struct ErrorEvent { kind string = 'error' @[json: 'type'] msg string target bool } // MessageEvent is a line of text a mode reports, a result line such as // 'system upgraded' or a warning. error marks one of libalpm's errors, which // is a warning too, for a reader that knows no error flag struct MessageEvent { kind string = 'message' @[json: 'type'] text string warning bool error bool @[omitempty] // verbose marks a line of the verbose log: a failure of housekeeping // the run went on from, said only because --verbose asked verbose bool @[omitempty] } // PhaseEvent is a step of the work: a terminal's spinner. it starts, may be // renamed by another start, and is done struct PhaseEvent { kind string = 'phase' @[json: 'type'] text string state string } // ProgressEvent is libalpm's progress through a transaction step: per // package for the package steps (pkg names it, current of total), once for // the whole-transaction checks. vpac's own counted steps use it too struct ProgressEvent { kind string = 'progress' @[json: 'type'] op string pkg string @[omitempty] percent int current int total int } // DownloadEvent is a file libalpm downloads: sent as its percent moves (or // every quarter second while it does not), and once more when it is done, // with libalpm's result: 0 fetched, 1 already up to date, -1 failed. a retry // — libalpm moving on to the next mirror — is an event of its own, retry // set: resume says the download goes on from where it stopped, otherwise it // starts over, and its byte counts with it struct DownloadEvent { kind string = 'download' @[json: 'type'] file string downloaded i64 total i64 done bool result int retry bool @[omitempty] resume bool @[omitempty] } // TransPkg is one package of a transaction listing. version is what the // transaction installs or removes; old_version the installed one an // install or upgrade replaces, empty for a new package. the sizes are in // bytes: what it downloads, and what it takes on disk once installed struct TransPkg { name string version string old_version string download_size i64 installed_size i64 } // TransactionEvent is the listing a transaction asks its go-ahead for: the // proceed question follows it. action is install, upgrade, remove or // autoremove. a --print preview sends it with preview set, and stops there struct TransactionEvent { kind string = 'transaction' @[json: 'type'] action string packages []TransPkg download_size i64 installed_size i64 mut: preview bool } // PackagesEvent is a titled list of packages shown beside a transaction or a // question: the packages an install removes, the ones an upgrade skips struct PackagesEvent { kind string = 'packages' @[json: 'type'] title string packages []TransPkg } // DoneEvent is a committed transaction's result, the last word of every // mode that commits one: what it did — installed, downloaded, removed, // upgraded, marked — and to which packages (install's and remove's targets, // autoremove's and upgrade's whole transaction). a mark says the reason the // packages have now: explicit, depend or unknown. a declined or failed // transaction sends none struct DoneEvent { kind string = 'done' @[json: 'type'] action string reason string @[omitempty] packages []string } // QuestionEvent asks the frontend. question is confirm (yes or no, preset // the answer an empty one takes), proceed (a transaction's go-ahead, preset // true) or choose (one of choices, by index, preset 0). the answer is a line // {"id": id, "answer": true|false|index} on stdin, the same type as preset. // select asks for any number of choices: preset is every index, and the // answer a list of indices, an empty one for none. // under --noconfirm, answer carries the default taken and nothing is read struct QuestionEvent { kind string = 'question' @[json: 'type'] id int question string msg string preset json2.Any choices []string @[omitempty] answer ?json2.Any } // InvalidEvent says an answer line did not answer the question asked; the // question stands and the next line is read struct InvalidEvent { kind string = 'invalid' @[json: 'type'] id int msg string } // IpcPrompter asks over the channel: each question is an event with an id, // and its answer the next valid line on stdin. end of input answers as a // terminal's does: no, and the first choice struct IpcPrompter { mut: noconfirm bool last_id int } fn (mut p IpcPrompter) confirm(msg string, preset bool) bool { return p.ask('confirm', msg, if preset { 1 } else { 0 }, []string{}) == 1 } fn (mut p IpcPrompter) proceed(msg string) bool { return p.ask('proceed', msg, 1, []string{}) == 1 } fn (mut p IpcPrompter) choose(msg string, choices []string) int { return p.ask('choose', msg, 0, choices) } // pick asks which of the choices, the select question. the choices were // sent ahead as the listing they are, so the question carries their count // as the preset alone: every index fn (mut p IpcPrompter) pick(msg string, count int) []bool { p.last_id++ id := p.last_id all := json2.Any([]json2.Any{len: count, init: json2.Any(index)}) if p.noconfirm { emit(QuestionEvent{ id: id question: 'select' msg: msg preset: all answer: all }) return []bool{len: count, init: true} } emit(QuestionEvent{ id: id question: 'select' msg: msg preset: all }) for { // end of input selects nothing, as on a terminal line := stdin_line() or { return []bool{len: count} } return parse_select_answer(line, id, count) or { emit(InvalidEvent{ id: id msg: err.msg() }) continue } } return []bool{len: count} } // answer_of reads an answer line down to its answer: the object, and the id // of the question asked, are what tell an answer from noise fn answer_of(line string, id int) !json2.Any { doc := json2.decode[json2.Any](line) or { return error('not json: ${line.trim_space()}') } if doc !is map[string]json2.Any { return error('an answer is an object: {"id": id, "answer": answer}') } m := doc.as_map() got := m['id'] or { return error('the answer has no id') } // json2 hands every json number over as f64: a whole one is an id's // number, a text is not an id at all gid := whole_of(got) or { return error("the answer's id is not a number") } if gid != id { return error('the question asked is ${id}, not ${gid}') } return m['answer'] or { return error('the answer has no answer') } } // parse_select_answer reads the answer to a select question: a list of // indices into its count choices, which may be empty fn parse_select_answer(line string, id int, count int) ![]bool { answer := answer_of(line, id)! if answer !is []json2.Any { return error('question ${id} takes a list of indices, 0 to ${count - 1}') } mut picked := []bool{len: count} for item in answer.as_array() { n := whole_of(item) or { return error('question ${id} takes a list of indices, 0 to ${count - 1}') } if n < 0 || n >= count { return error('question ${id} takes a list of indices, 0 to ${count - 1}') } picked[n] = true } return picked } // ask sends a question and waits for its answer: 1 or 0 for a yes or no, // the index for a choice fn (mut p IpcPrompter) ask(kind string, msg string, preset int, choices []string) int { p.last_id++ id := p.last_id // a yes or no travels as a bool, a choice as its index preset_v := if kind == 'choose' { json2.Any(preset) } else { json2.Any(preset == 1) } if p.noconfirm { emit(QuestionEvent{ id: id question: kind msg: msg preset: preset_v choices: choices answer: preset_v }) return preset } emit(QuestionEvent{ id: id question: kind msg: msg preset: preset_v choices: choices }) for { // end of input, or a stdin that cannot be read: no, or the first // choice, as on a terminal. an empty line is a line, and invalid line := stdin_line() or { return 0 } answer := parse_answer(line, id, kind, choices.len) or { emit(InvalidEvent{ id: id msg: err.msg() }) continue } return answer } } // parse_answer reads one answer line for question id: a bool for a yes or // no, an index into the choices for a choose. the object, the id and the // answer's type are what tell an answer from noise, and anything else comes // back as the error the asker turns into an invalid event, keeping the // question and reading the next line fn parse_answer(line string, id int, kind string, count int) !int { answer := answer_of(line, id)! if kind == 'choose' { n := whole_of(answer) or { return error('question ${id} takes an index, 0 to ${count - 1}') } if n < 0 || n >= count { return error('question ${id} takes an index, 0 to ${count - 1}') } return n } if answer !is bool { return error('question ${id} takes true or false') } return if answer.bool() { 1 } else { 0 } } // whole_of keeps a json number that is a whole one, like 1 but not 1.5: the // question ids and the choice indices travel as integers, and json2's f64 is // the one type describing them fn whole_of(a json2.Any) ?int { if a is f64 && a == f64(int(a)) { return int(a) } return none } // report is a result line of a mode: printed on a terminal, a message event // for a frontend fn report(text string) { if ipc_on() { emit(MessageEvent{ text: text }) return } println(text) } // advise is a plain line that goes with a warning, the advice after it: on // stderr for a terminal, a message event marked as a warning for a frontend fn advise(text string) { warning_line(text, text) } // warn is a warning: on stderr for a terminal, a message event marked as a // warning for a frontend fn warn(text string) { warning_line(text, warning(text)) } // verbose_flag is --verbose on the command line, cfg_verbose the config's // (options #:verbose #t): either turns the verbose log on. the config's is // reset with the config; the flag is the command line's and stays __global verbose_flag = false __global cfg_verbose = false fn verbose_on() bool { return verbose_flag || cfg_verbose } // went_on is the verbose log's one kind of line: something of the run's // housekeeping failed — a handle's release, a temp dir's removal — and the // run went on, because nothing the user asked for depended on it. without // --verbose it is kept quiet, as it always was; with it the failure is said, // on stderr for a terminal and as a message event marked verbose for a // frontend, so a run that leaves something behind can be asked why fn went_on(what string, err IError) { if !verbose_on() { return } text := 'could not ${what}: ${err.msg()}' if ipc_on() { emit(MessageEvent{ text: text warning: true verbose: true }) return } eprintln('verbose: ${text}') } // warning_line is the one way a warning or its advice leaves: the plain // text as a warning message event for a frontend, the terminal's spelling // of it on stderr otherwise fn warning_line(text string, on_terminal string) { if ipc_on() { emit(MessageEvent{ text: text warning: true }) return } eprintln(on_terminal) } // ListingEvent is a package list, search's or orphans': the fields, and for // each package its name and its value of every field, in their order. a // quiet listing sends the names alone; search -g's entries name the group // they were listed for struct ListingEvent { kind string = 'listing' @[json: 'type'] fields []string entries []ListEntry } // GroupsEvent lists the groups of the sync dbs, search -g without names struct GroupsEvent { kind string = 'groups' @[json: 'type'] groups []GroupRef } // InfoEvent is one package as info shows it: every field asked for, its // value as one text, and the items of a list field struct InfoEvent { kind string = 'info' @[json: 'type'] fields []InfoField } // ChangelogEvent is a package's changelog, info -c: the text as the package // carries it struct ChangelogEvent { kind string = 'changelog' @[json: 'type'] package string text string } // FilesEvent is the files of a package: an installed one's under the root // (files), or a sync one's as its file db lists them (find -l, with repo) struct FilesEvent { kind string = 'files' @[json: 'type'] package string repo string @[omitempty] paths []string } // ProvidesEvent is find's answer for one path: the sync packages whose files // hold it, as a listing. a target that matches many files (-x, or a file // name with no slash) also names them: files[i] are the paths matched in the // package of entries[i] struct ProvidesEvent { kind string = 'provides' @[json: 'type'] path string fields []string entries []ListEntry files [][]string @[omitempty] } // OwnerEvent is an installed package that owns a path: one event for a // file, one per owner for a directory (packages share those), the path // repeated, as pacman -Qo lists them struct OwnerEvent { kind string = 'owner' @[json: 'type'] path string package string version string } // UnsatisfiedEvent is deptest's answer: the dependencies no installed // package satisfies, none when all are struct UnsatisfiedEvent { kind string = 'unsatisfied' @[json: 'type'] deps []string } // TreeItem is a node of a dependency tree: a package (found), or the // dependency nothing provides (name is then how it was asked for). seen // marks a package expanded elsewhere in the tree, whose branches are there struct TreeItem { name string version string found bool optional bool seen bool children []TreeItem } // TreeEvent is one target's tree: its dependencies, or with reverse what // requires it struct TreeEvent { kind string = 'tree' @[json: 'type'] reverse bool root TreeItem } // VerifyEvent is verify's report: a line per finding, problem telling the // ones that count against a package from notes, and how many packages have // problems struct VerifyEvent { kind string = 'verify' @[json: 'type'] lines []VerifyLine bad int } // MirrorEvent is one mirror of a ranking: latency in ms, speed in bytes per // second, last_sync as the mirror status gives it struct MirrorEvent { url string latency_ms i64 speed f64 last_sync string } // MirrorsEvent is rank's result, the fastest first struct MirrorsEvent { kind string = 'mirrors' @[json: 'type'] mirrors []MirrorEvent } // CleanEvent is what clean removes: the cached files and the pkgbuild build // dirs, with their sizes, and the sync db files of repos the config no // longer names (dbs). the proceed question follows it, except for a // --print preview, which stops there. build_root is absent when no invoker // is known (root running vpac c itself): the builds were not looked at then, // which an empty root beside an empty list would tell as none found struct CleanEvent { kind string = 'clean' @[json: 'type'] cache_dirs []string build_root ?string files []string files_size u64 builds []string build_size u64 // build_size_partial: part of a build could not be read, and build_size // is a floor, not the size build_size_partial bool dbs []string preview bool }