@[has_globals] module main import alpm import sync import time import x.progress #include "@VMODROOT/src/alpm_log.h" fn C.vpac_set_alpm_log(handle &alpm.Handle, ctx voidptr) int // ALPM_LOG_ERROR: the one level the log callback tells apart, the other one // it passes being a warning (alpm_log.h) const alpm_log_error = 1 // ProgressCfg is how the live display draws, the config's (progress ...) and // (spinner ...) forms. style is the bar graphic, 'classic' or 'block', and // parts holds the pieces of it the config respelled (start, end, fill, // head, empty), the style's own standing for the rest. frames empty is the // display's own spinner struct ProgressCfg { mut: style string = 'classic' parts map[string]string length int = 30 percent bool = true eta bool = true elapsed bool rate bool = true delay int = 50 frames []string interval int = 80 done string = '✓' timed bool } __global cfg_progress = ProgressCfg{} // spinner_sets are the frame sets (spinner :frames) knows by name const spinner_sets = ['dots', 'braille', 'line', 'arrows', 'circle', 'quarters', 'grow', 'bounce', 'pulse', 'ellipsis', 'earth', 'moon'] // spinner_frames_named is a frame set by its name, none for a name outside // spinner_sets fn spinner_frames_named(name string) ?[]string { return match name { 'dots' { progress.spinner_dots() } 'braille' { progress.spinner_braille() } 'line' { progress.spinner_line() } 'arrows' { progress.spinner_arrows() } 'circle' { progress.spinner_circle() } 'quarters' { progress.spinner_quarters() } 'grow' { progress.spinner_grow() } 'bounce' { progress.spinner_bounce() } 'pulse' { progress.spinner_pulse() } 'ellipsis' { progress.spinner_ellipsis() } 'earth' { progress.spinner_earth() } 'moon' { progress.spinner_moon() } else { none } } } // part_rune is one cell of a bar graphic as the config spelled it: the // first rune, or fallback for a part it left alone or emptied fn part_rune(name string, fallback rune) rune { text := cfg_progress.parts[name] or { return fallback } runes := text.runes() return if runes.len > 0 { runes[0] } else { fallback } } // bar_style is the bar graphic the config draws fn bar_style() progress.Style { if cfg_progress.style == 'block' { d := progress.BlockStyle{} return progress.BlockStyle{ start: cfg_progress.parts['start'] or { d.start } end: cfg_progress.parts['end'] or { d.end } fill: part_rune('fill', d.fill) empty: part_rune('empty', d.empty) } } d := progress.ClassicStyle{} return progress.ClassicStyle{ start: cfg_progress.parts['start'] or { d.start } end: cfg_progress.parts['end'] or { d.end } fill: part_rune('fill', d.fill) // an emptied head is no head: the bar ends in its fill head: if 'head' in cfg_progress.parts { part_rune('head', 0) } else { d.head } empty: part_rune('empty', d.empty) } } // bar_opts dresses a bar the config's way: what a caller asks of its bar // stays, and the rate is shown only where the caller has one to show fn bar_opts(o progress.BarOptions) progress.BarOptions { return progress.BarOptions{ ...o style: bar_style() length: cfg_progress.length show_percent: cfg_progress.percent show_left: cfg_progress.eta show_elapsed: cfg_progress.elapsed show_rate: o.show_rate && cfg_progress.rate } } // spinner_opts dresses a spinner the config's way fn spinner_opts(o progress.SpinnerOptions) progress.SpinnerOptions { return progress.SpinnerOptions{ ...o frames: if cfg_progress.frames.len > 0 { cfg_progress.frames.clone() } else { o.frames.clone() } interval: cfg_progress.interval * time.millisecond done_frame: cfg_progress.done show_elapsed: cfg_progress.timed } } // TransUI is a command's user interface: the shared progress display (one // MultiBar that holds spinners for the command phases, download bars fed by // alpm's dlcb and transaction phase bars fed by alpm's progresscb) and the // prompter every question goes through, libalpm's own included. It is passed // to alpm as the callback context. under --ui ipc there is no MultiBar: the // same calls send events (Phase, Meter, the callbacks) // every ui-bearing function spells its ui `mut ui TransUI`, the way it does // for the _locked helpers: TransUI is @[heap], and a mut value parameter of // one writes through, so the ui handed to a mode and the one its helpers // reach are the same struct. only init_handle takes the reference spelled // out, since it hands the pointer itself to libalpm @[heap] struct TransUI { mut: mb &progress.MultiBar = unsafe { nil } // mu guards the fields below against libalpm's download callbacks: with // parallel downloads on, dlcb arrives on several threads at once, and // progresscb may join it. every method here takes mu before it touches // state other callbacks or threads can see, and the _locked helpers // below it are reached only with the mutex held. the bars and the // multibar are drawn thread-safely by x.progress itself mu &sync.Mutex = sync.new_mutex() dbars map[string]&progress.Bar pbar &progress.Bar = unsafe { nil } pkey int // dpad is the width every download bar reserves for its name, so all // bars start at the same X coordinate; grows to the longest name seen dpad int // prompt asks the user; its noconfirm is --noconfirm, which every // command that asks anything passes to new_trans_ui prompt Prompter // print_only (--print) answers every question silently, as pacman's // --print does, so the listing on stdout stays clean print_only bool // download_only (install -w) fetches an ignored package without asking download_only bool // walking is set while install looks dependencies up for itself: the // questions libalpm raises then are answered as --print answers them walking bool // dlast is what each download last reported under --ui ipc, so an event // goes out as the percent moves or the time passes (download_due), not // for every chunk; plast is the last progress event, which libalpm may // send twice dlast map[string]DownloadSent plast ProgressEvent } // TransUIOptions are what a command tells its TransUI @[params] struct TransUIOptions { // noconfirm is --noconfirm: every prompt takes its default unasked noconfirm bool } // new_trans_ui makes a command's TransUI, with the prompter of the frontend // --ui chose fn new_trans_ui(o TransUIOptions) &TransUI { return &TransUI{ dbars: {} prompt: if ipc_on() { Prompter(IpcPrompter{ noconfirm: o.noconfirm }) } else { Prompter(TermPrompter{ noconfirm: o.noconfirm }) } } } // group returns the live MultiBar, starting a new one if the previous one was // paused for a prompt. the alpm callbacks reach the display through this // struct, so they always draw on the current MultiBar fn (mut ui TransUI) group() &progress.MultiBar { ui.mu.lock() defer { ui.mu.unlock() } return ui.group_locked() } // group_locked is group, with the ui's mutex already held: download bars and // the lazy creation of the MultiBar must not race fn (mut ui TransUI) group_locked() &progress.MultiBar { if ui.mb == unsafe { nil } { // the cursor stays visible: confirmation prompts are asked on a // running display otherwise, and a hidden cursor makes them look dead ui.mb = progress.MultiBar.new( hide_cursor: false delay: cfg_progress.delay * time.millisecond ) } return ui.mb } // Phase is a step a command shows while it works: a spinner on a terminal, // phase events under --ui ipc @[heap] struct Phase { mut: spinner &progress.Spinner = unsafe { nil } text string started bool done bool } fn (mut ui TransUI) spinner(opts progress.SpinnerOptions) &Phase { if ipc_on() { return &Phase{ text: opts.text } } return &Phase{ spinner: ui.group().add_spinner(spinner_opts(opts)) text: opts.text } } fn (mut p Phase) start() { if p.spinner != unsafe { nil } { p.spinner.start() return } p.started = true emit(PhaseEvent{ text: p.text state: 'start' }) } // set_text renames the step; a running one reports the new name as a start fn (mut p Phase) set_text(text string) { p.text = text if p.spinner != unsafe { nil } { p.spinner.set_text(text) return } if p.started && !p.done { emit(PhaseEvent{ text: text state: 'start' }) } } fn (p &Phase) is_done() bool { if p.spinner != unsafe { nil } { return p.spinner.is_done() } return p.done } fn (mut p Phase) finish() { if p.spinner != unsafe { nil } { p.spinner.finish() return } if p.done { return } p.done = true if p.started { emit(PhaseEvent{ text: p.text state: 'done' }) } } // Meter is a counted step: a bar on a terminal, progress events under // --ui ipc, one each time the percent moves @[heap] struct Meter { mut: bar &progress.Bar = unsafe { nil } text string total i64 count i64 percent int = -1 } fn (mut ui TransUI) meter(total i64, text string) &Meter { if ipc_on() { return &Meter{ text: text total: total } } return &Meter{ bar: ui.group().add_bar(total, bar_opts(text: text + ' ')) text: text total: total } } fn (mut m Meter) start() { if m.bar != unsafe { nil } { m.bar.start() return } m.add(0) } fn (mut m Meter) add(n i64) { if m.bar != unsafe { nil } { m.bar.add(n) return } m.count += n pct := if m.total > 0 { int(m.count * 100 / m.total) } else { 100 } if pct != m.percent { m.percent = pct emit(ProgressEvent{ op: m.text percent: pct current: int(m.count) total: int(m.total) }) } } // pause stops the live display before a confirmation prompt. the render // thread must be gone before the prompt is written, otherwise its redraw can // erase the prompt and leave the program waiting on a question nobody sees fn (mut ui TransUI) pause() { ui.mu.lock() defer { ui.mu.unlock() } if ui.mb != unsafe { nil } { ui.mb.stop() ui.mb = unsafe { nil } } ui.pbar = unsafe { nil } ui.dbars = map[string]&progress.Bar{} ui.dpad = 0 ui.dlast = map[string]DownloadSent{} ui.plast = ProgressEvent{} } // stop ends the live display, the run over. reached with the ui's mutex, // like every touch of the display's fields: a download callback creating a // bar on another thread must not race the stop that tears it down fn (mut ui TransUI) stop() { ui.mu.lock() defer { ui.mu.unlock() } if ui.mb != unsafe { nil } { ui.mb.stop() } } // sync asks the live display to paint right away: the finished frame of a // spinner that just stopped is otherwise drawn by the next tick, which lands // behind the result line the caller is about to print fn (mut ui TransUI) sync() { if ui.mb != unsafe { nil } { ui.mb.flush() } } // stop_spinner finishes a spinner that is still running, so a command that // fails or asks a question does not leave it turning on screen fn stop_spinner(mut s Phase) { if !s.is_done() { s.finish() } } // end_frame is the stop a spinner window needs before plain printlns: the // finished frame goes out right away, and the render thread is stopped. // stopping the spinner alone leaves the thread drawing, and a further tick // lands right inside the lines that follow (the report of verify showed it). // the writes that are safe beside a live frame are the group's own println // and the prompts, which reach it through ui.pause fn end_frame(mut ui TransUI, mut s Phase) { stop_spinner(mut s) ui.sync() ui.pause() } // print_done is the transaction result line, e.g. "removed: ". // every command that commits a transaction reports through it fn print_done(mut ui TransUI, label string, names []string) { if ipc_on() { emit(DoneEvent{ action: label.trim_right(':') packages: names }) return } ui.sync() ui.group().println('${success(label)} ${names.join(' ')}') } // say is a result line printed beside the live display, a message event // under --ui ipc fn (mut ui TransUI) say(text string) { if ipc_on() { emit(MessageEvent{ text: text }) return } ui.group().println(text) } // warn is a warning printed beside the live display, as say prints a result // line: above the bars a download may still draw, never through them. under // --ui ipc it is the warning message event warn() sends fn (mut ui TransUI) warn(text string) { if ipc_on() { warn(text) return } ui.group().println(warning(text)) } // show_packages lists packages under a heading, the way a transaction shows // the ones it removes or skips: name and version fn (mut ui TransUI) show_packages(title string, pkgs []&alpm.Package) { if ipc_on() { emit(PackagesEvent{ title: title.trim_right(':') packages: pkgs.map(TransPkg{ name: it.get_name() version: it.get_version() }) }) return } println(heading(title)) println(table_text(pkgs.map(row(name_style(it.get_name()), version_style(it.get_version()))), ' ', ' ')) } fn safe_vstring(p &u8) string { return if p == unsafe { nil } { '' } else { unsafe { p.vstring() } } } // download_text pads a download bar's text to the shared name column: every // bar reserves the same cells for its name (as wide as the longest name seen // so far, plus the trailing space), so all bars sit at the same X coordinate // whatever their filenames' lengths. when a longer name arrives later, the // column widens and the running bars are re-padded in place (set_text is // thread-safe); finished bars are left alone, their lines are already printed // reached only with the ui's mutex held, from download_bar fn (mut ui TransUI) download_text_locked(name string) string { if name.len + 1 > ui.dpad { ui.dpad = name.len + 1 } for key, mut bar in ui.dbars { if bar.is_done() { continue } bar.set_text(key + ' '.repeat(ui.dpad - key.len)) } return name + ' '.repeat(ui.dpad - name.len) } // download_bar returns the display bar of one download, created on the file's // first event, when its size is known; the shown group starts with it // libalpm runs its dlcb on the parallel download threads, so the shared // state is reached with the ui's mutex, and never the drawing itself fn (mut ui TransUI) download_bar(name string, total i64, on_end string, show_rate bool) &progress.Bar { ui.mu.lock() defer { ui.mu.unlock() } bar := ui.dbars[name] or { mb := ui.group_locked() b := mb.add_bar(total, bar_opts( text: ui.download_text_locked(name) show_rate: show_rate rate_unit: progress.RateUnit.bytes_iec() on_end: on_end )) ui.dbars[name] = b mb.start() b } return bar } fn cb_download(ctx voidptr, filename &u8, event alpm.DownloadEventType, data voidptr) { mut ui := &TransUI(ctx) name := safe_vstring(filename) if ipc_on() { ipc_download(mut ui, name, event, data) return } match event { .init { // the bar is created at the first progress event, when the // download size is known } .progress { p := unsafe { &alpm.DownloadEventProgress(data) } // libalpm runs this callback on its parallel download threads: // the shared display state is reached through the ui's mutex, the // drawing itself is x.progress's to keep thread-safe bar := ui.download_bar(name, p.total, '', true) bar.set(p.downloaded) } .retry { // libalpm moves on to the next mirror: a download that starts over // starts its bar over, as pacman's dload_retry_event does, and one // that resumes keeps its place r := unsafe { &alpm.DownloadEventRetry(data) } if r.resume == 0 { ui.restart_download_bar(name) } } .completed { c := unsafe { &alpm.DownloadEventCompleted(data) } // libalpm's result: 1 means the local copy met the time condition // and nothing was fetched, 0 a finished download, -1 an error. a // download can finish before its first progress event, so the bar // may not exist yet; only result 1 is labelled up to date on_end := if c.result == 1 { '${name} is up to date' } else { '' } bar := ui.download_bar(name, c.total, on_end, false) bar.set(c.total) } } } // restart_download_bar puts a download's bar back at nothing, when libalpm // starts the file over from another mirror. a bar not drawn yet has nothing // to restart fn (mut ui TransUI) restart_download_bar(name string) { ui.mu.lock() defer { ui.mu.unlock() } mut bar := ui.dbars[name] or { return } bar.set(0) } // DownloadSent is what a download last reported under --ui ipc: its percent, // and when, in the monotonic clock's nanoseconds struct DownloadSent { percent int at i64 } // download_beat is the longest a download in progress goes without an // event: a large file on a slow line moves a percent in minutes, and a // frontend's rate would stand still that long const download_beat = i64(250 * time.millisecond) // download_due tells whether a progress report goes out: the first one of a // download, then each time the percent moves or a beat has passed fn download_due(last ?DownloadSent, percent int, now i64) bool { sent := last or { return true } return percent != sent.percent || now - sent.at >= download_beat } // ipc_download reports a download as events: as its percent moves or a beat // passes, once more when libalpm retries it from the next mirror, and once // when it is done. the dlcb arrives on libalpm's parallel download threads, // so the dedupe table is reached with the ui's mutex, and the event goes out // once the lock is gone fn ipc_download(mut ui TransUI, name string, event alpm.DownloadEventType, data voidptr) { match event { .progress { p := unsafe { &alpm.DownloadEventProgress(data) } pct := if p.total > 0 { int(p.downloaded * 100 / p.total) } else { 0 } now := time.sys_mono_now() ui.mu.lock() if !download_due(ui.dlast[name] or { none }, pct, i64(now)) { ui.mu.unlock() return } ui.dlast[name] = DownloadSent{ percent: pct at: i64(now) } ui.mu.unlock() emit(DownloadEvent{ file: name downloaded: p.downloaded total: p.total }) } .retry { r := unsafe { &alpm.DownloadEventRetry(data) } // what was reported is history: the next progress goes out ui.mu.lock() ui.dlast.delete(name) ui.mu.unlock() emit(DownloadEvent{ file: name retry: true resume: r.resume != 0 }) } .completed { c := unsafe { &alpm.DownloadEventCompleted(data) } emit(DownloadEvent{ file: name downloaded: c.total total: c.total done: true result: int(c.result) }) } else {} } } fn progress_verb(kind alpm.Progress) string { return match kind { .add_start { 'installing' } .upgrade_start { 'upgrading' } .downgrade_start { 'downgrading' } .reinstall_start { 'reinstalling' } .remove_start { 'removing' } .conflicts_start { 'checking for file conflicts' } .diskspace_start { 'checking available disk space' } .integrity_start { 'checking package integrity' } .load_start { 'loading package files' } .keyring_start { 'checking keys in keyring' } } } fn cb_progress(ctx voidptr, kind alpm.Progress, pkgname &u8, percent i32, howmany uint, current uint) { mut ui := &TransUI(ctx) verb := progress_verb(kind) name := safe_vstring(pkgname) // pacman draws one bar per package for the package phases (the text is // '(current/howmany) verb name' and the percent restarts for each // package), and a single bar per whole-transaction check phase // (conflicts, diskspace, integrity, load, keyring). libalpm also sends // the final 100% event with a different `current`, so the phase bars // must not be keyed on it. pkg_wise := match kind { .add_start, .upgrade_start, .downgrade_start, .reinstall_start, .remove_start { true } else { false } } if ipc_on() { ev := ProgressEvent{ op: verb pkg: if pkg_wise { name } else { '' } percent: int(percent) current: int(current) total: int(howmany) } // plast guards the repeats; the shared state is touched holding the // ui's mutex, and the event goes out with the lock gone ui.mu.lock() dup := ev == ui.plast if !dup { ui.plast = ev } ui.mu.unlock() if !dup { emit(ev) } return } // the key pairs the phase with the package the progress belongs to: the // bar restarts when either changes. 1000003 is prime; a collision would // need a transaction packaging over a million files in one phase pkey := if pkg_wise { int(kind) * 1000003 + int(current) } else { int(kind) } text := if !pkg_wise || name == '' { '${verb} ' } else { '(${int(current)}/${int(howmany)}) ${verb} ${name} ' } ui.mu.lock() defer { ui.mu.unlock() } if ui.pbar == unsafe { nil } || ui.pkey != pkey { ui.pkey = pkey ui.pbar = ui.group_locked().add_bar(100, bar_opts(text: text)) ui.group_locked().start() } ui.pbar.set_text(text) ui.pbar.set(i64(percent)) } // cb_question asks libalpm's questions the way pacman's frontend does, with // pacman's defaults: yes to installing an ignored package, replacing a // package, deleting a corrupted package file and importing a missing key; no // to removing a conflicting package and to skipping packages whose // dependencies cannot be resolved; the first of several providers. libalpm // presets every answer to 0 before it asks, so a question left unanswered is // a no, which is not pacman's default for half of them. the live display is // paused first so it cannot draw over the listings, and every question goes // through the ui's prompter, whose --noconfirm prints each one and takes its // default. all of it follows pacman's cb_question in src/pacman/callback.c fn cb_question(ctx voidptr, q &alpm.Question) { mut ui := &TransUI(ctx) kind := unsafe { q.type_ } // --print lists the transaction and asks nothing: an ignored package and // a replacement stay in the list, every other question is a no, and a // provider is the first. install's own dependency walks answer the same if ui.print_only || ui.walking { set_answer(q, flag_answer(kind in [.install_ignorepkg, .replace_pkg])) return } ui.pause() answer := match kind { .install_ignorepkg { pkg := unsafe { q.install_ignorepkg.pkg } // a download installs nothing, so the ignored package is fetched if ui.download_only { i32(1) } else { flag_answer(ui.yesno('${pkg.get_name()} is ignored. install it anyway?')) } } .replace_pkg { r := unsafe { q.replace } old := r.oldpkg.get_name() flag_answer(ui.yesno('replace ${old} with ${r.newdb.get_name()}/${r.newpkg.get_name()}?')) } .conflict_pkg { conflict := unsafe { q.conflict.conflict } kept := conflict.package1.get_name() removed := conflict.package2.get_name() flag_answer(ui.noyes('${kept} conflicts with ${removed}. remove ${removed}?')) } .corrupted_pkg { c := unsafe { q.corrupted } path := safe_vstring(c.filepath) flag_answer(ui.yesno('${path} is corrupted (${c.reason.strerror()}). delete it?')) } .remove_pkgs { // a sysupgrade whose packages have unresolvable dependencies: // skipping them lets the rest of the upgrade go on mut list := unsafe { q.remove_pkgs.packages } pkgs := list.pkgs() noun := if pkgs.len == 1 { 'package' } else { 'packages' } ui.show_packages('${pkgs.len} ${noun} cannot be upgraded, their dependencies cannot be resolved:', pkgs) flag_answer(ui.noyes('skip them for this upgrade?')) } .select_provider { sp := unsafe { q.select_provider } mut list := sp.providers providers := list.pkgs() title := '${providers.len} providers for ${sp.depend.compute_string()}:' // a frontend gets them as the choices; the terminal lists them as // numbered rows first, and those are built only for it choices := providers.map(provider_choice(it)) if !ipc_on() { println(heading(title)) println(table_text(provider_rows(providers), ' ', ' ')) } i32(ui.choose(if ipc_on() { title.trim_right(':') } else { 'which one?' }, choices)) } .import_key { k := unsafe { q.import_key } fingerprint := safe_vstring(k.fingerprint) // the uid is unknown for a db signature uid := safe_vstring(k.uid) key := if uid == '' { fingerprint } else { '${fingerprint}, "${uid}"' } flag_answer(ui.yesno('import pgp key ${key}?')) } } set_answer(q, answer) } // provider_choice is a provider as a frontend's choice: repo/name version fn provider_choice(pkg &alpm.Package) string { repo := if db := pkg.get_db() { db.get_name() + '/' } else { '' } return '${repo}${pkg.get_name()} ${pkg.get_version()}' } // provider_rows are the providers numbered for the terminal's listing, the // number the choose question asks for fn provider_rows(providers []&alpm.Package) []Row { mut rows := []Row{} for i, pkg in providers { styled := if db := pkg.get_db() { source_style(db.get_name()) + '/' } else { '' } rows << row('${i + 1})', styled + name_style(pkg.get_name()), version_style(pkg.get_version())) } return rows } // alpm_log_line is libalpm's log callback, its V half: alpm_log.h formats // each error and warning libalpm says, and it is said to the user as // pacman's cb_log says it. vpac's own dependency walks (ui.walking) look // things up the transaction's prepare looks up again; what they would say // is said then, once @[export: 'vpac_log_line'] fn alpm_log_line(ctx voidptr, level int, text &char) { if ctx == unsafe { nil } || text == unsafe { nil } { return } mut ui := unsafe { &TransUI(ctx) } if ui.walking { return } msg := unsafe { cstring_to_vstring(text) }.trim_space() if msg == '' { return } ui.alpm_said(level == alpm_log_error, msg) } // alpm_said is a line libalpm logged: printed above any live bars (which // hold it while they draw, as pacman buffers during progress), or a message // event a frontend reads as a warning, an error flagged as one fn (mut ui TransUI) alpm_said(is_error bool, text string) { if ipc_on() { emit(MessageEvent{ text: text warning: true error: is_error }) return } line := if is_error { error_text(text) } else { warning(text) } ui.mu.lock() defer { ui.mu.unlock() } if ui.mb != unsafe { nil } { ui.mb.println(line) } else { eprintln(line) } } // set_answer writes a question's answer. every question struct keeps its // answer right after the type, which is what libalpm's alpm_question_any_t // exposes fn set_answer(q &alpm.Question, answer i32) { unsafe { mut any := &alpm.QuestionAny(q) any.answer = answer } } fn flag_answer(yes bool) i32 { return if yes { 1 } else { 0 } } // init_handle initializes alpm and attaches the progress display callbacks // and the configured parallel download count fn init_handle(ui &TransUI) !&alpm.Handle { handle := alpm.initialize(root_path, db_path) or { return error('failed to initialize alpm') } handle.option_set_dlcb(cb_download, voidptr(ui))! handle.option_set_progresscb(cb_progress, voidptr(ui))! handle.option_set_questioncb(cb_question, voidptr(ui))! // libalpm's errors and warnings, which it says through this alone if C.vpac_set_alpm_log(handle, voidptr(ui)) != 0 { return error('could not set the log callback: ${handle.error().msg()}') } // the freshly calloc'd handle verifies nothing: pacman defaults to // checking signature levels, so the configured level is made the // handle's default for every db registered later, and for local and // remote files the transaction loads (libalpm tells the two apart as // pacman's SigLevel does; RemoteFileSigLevel follows SigLevel when it // is not named). a file is checked at its load only, at the level of its // origin (load_file_target); the remote level also decides whether a // url's .sig is fetched, and the url install warns by it handle.option_set_default_siglevel(cfg_siglevel)! handle.option_set_local_file_siglevel(cfg_siglevel)! handle.option_set_remote_file_siglevel(cfg_siglevel)! // pacman's frontend sets these from the config; without a cache dir // libalpm falls back to /tmp for downloads for dir in cfg_cachedirs { handle.option_add_cachedir(dir)! } // pacman's Architecture: without one libalpm's check_arch passes every // package, whatever it was built for handle.option_add_architecture(arch)! // libalpm's own hook dir (under the root) is on the handle already; // these are the config's, pacman's HookDir for dir in cfg_hookdirs { handle.option_add_hookdir(dir)! } if cfg_logfile != '' { handle.option_set_logfile(cfg_logfile)! } if cfg_syslog { handle.option_set_usesyslog(1)! } if cfg_gpgdir != '' { handle.option_set_gpgdir(cfg_gpgdir)! } // the ignored packages are libalpm's to skip on upgrades, with a question // for the user at the start of one for name in cfg_ignore { handle.option_add_ignore_pkg(name)! } for group in cfg_ignore_groups { handle.option_add_ignore_group(group)! } // pacman.conf's NoUpgrade and NoExtract: globs of files an upgrade keeps // (writing .pacnew beside them) and files an install never writes for glob in cfg_noupgrade { handle.option_add_noupgrade(glob)! } for glob in cfg_noextract { handle.option_add_no_extract(glob)! } if cfg_disable_timeout { handle.option_set_disable_dl_timeout(1)! } // pacman's DownloadUser: downloads run as this user, sandboxed. an empty // one is pacman without DownloadUser, downloads as root, unsandboxed if download_user != '' { handle.option_set_sandboxuser(download_user) or { return error('problem setting the download user "${download_user}" (user does not exist)') } } // pacman's DisableSandboxFilesystem and DisableSandboxSyscalls: the // downloader and the extraction run without either part of libalpm's // sandbox. the installed libalpm has these two, not a whole-sandbox switch if cfg_disable_sandbox { handle.option_set_disable_sandbox_filesystem(1)! handle.option_set_disable_sandbox_syscalls(1)! } handle.option_set_parallel_downloads(u32(parallel_downloads))! return handle }