module vmakepkg import os import vile.reader import vile.scheme // Scheme and Vile recipes share the same metadata and phase bindings. const recipe_list_keys = [ 'pkgname', 'arch', 'license', 'depends', 'makedepends', 'checkdepends', 'optdepends', 'provides', 'conflicts', 'backup', 'options', 'source', 'validpgpkeys', 'hook-files', 'b2sums', 'sha256sums', ] const recipe_phases = ['prepare', 'build', 'check', 'package'] const recipe_hooks = ['pre-install', 'post-install', 'pre-upgrade', 'post-upgrade', 'pre-remove', 'post-remove'] // upgrade hooks receive the new and old versions, in that order. fn recipe_hook_arity(hook string) int { if hook in ['pre-upgrade', 'post-upgrade'] { return 2 } return 1 } // quote one argument for callers that execute a plain PKGBUILD or elevate through su. pub fn shell_quote(s string) string { return "'" + s.replace("'", "'\\''") + "'" } // recipe_tag_name is for error text: 'a keyword' reads better than a dump of the // tag enum fn recipe_tag_name(t scheme.Kind) string { return match t { .nil { 'an empty list' } .boolean { 'a boolean' } .integer { 'an integer' } .real, .rational { 'a number' } .character { 'a character' } .string { 'a string' } .symbol { 'a symbol' } .keyword { 'a keyword' } .pair { 'a list' } .vector { 'a vector' } .procedure { 'a procedure' } else { 'a ${t}' } } } fn recipe_item(v scheme.Value) !string { return match v.kind() { .string { v.as_string()! } .symbol { v.symbol_name()! } .keyword { v.keyword_name()! } else { error('items must be strings or keywords, not ${recipe_tag_name(v.kind())}') } } } // list_items also rejects dotted and cyclic lists, without dropping a tail. fn recipe_items_of(v scheme.Value, what string) ![]string { match v.kind() { .string, .symbol, .keyword { return [recipe_item(v)!] } .nil { return []string{} } .pair, .vector { items := if v.kind() == .vector { v.vector_items()! } else { v.list_items() or { return error('pkgbuild #:${what}: a list ends in (): ${err.msg()}') } } mut out := []string{} for item in items { out << recipe_item(item) or { return error('pkgbuild #:${what}: ${err.msg()}') } } return out } else { return error('pkgbuild #:${what} must be a string or a quoted list') } } } // package metadata uses the kernel spelling of x86_64. fn recipe_arch(a string) string { if a == 'x86-64' { return 'x86_64' } return a } // Scheme keywords spell a disabled option as #:no-strip and package metadata uses !strip. fn recipe_option(keyword string) string { if keyword.starts_with('no-') { return '!' + keyword[3..] } return keyword } // a source checksum is either its full hexadecimal digest or SKIP. fn recipe_hex(s string, len int, what string) ! { if s == 'SKIP' { return } if s.len != len { return error('${what}: ${s} is ${s.len} characters; ${what} entries are ${len} hex characters or SKIP') } for c in s { if !c.is_hex_digit() { return error('${what}: ${s} has a character that is not hex (${c.ascii_str()})') } } } // recipe_key40 checks a PGP fingerprint: the full 40 uppercase hex characters fn recipe_key40(s string, i int) ! { if s.len != 40 { return error('validpgpkeys: entry ${i} is ${s.len} characters; fingerprints are 40: the full uppercase one') } for c in s { if !c.is_hex_digit() { return error('validpgpkeys: entry ${i} has a character that is not hex (${c.ascii_str()})') } if c >= `a` && c <= `f` { return error('validpgpkeys: entry ${i} is lowercase hex (${c.ascii_str()}); uppercase fingerprints only') } } } // keep phase closures in the VM that evaluated the recipe. fn prim_defpkgbuild(mut vm scheme.VM, input []scheme.Value) !scheme.Value { scheme.check_arity('vpac-defpkgbuild', input.len, 2, 2)! forms := input[0].list_items()! mut args := input[1].list_items()! if forms.len != args.len { return error('pkgbuild: source and value counts differ') } if args.len == 0 { return error('pkgbuild: (defpkgbuild name ...) needs the name') } // the macro quotes the name so package names never resolve as variables. if args[0].kind() == .pair { quoted := args[0].list_items()! if quoted.len == 2 && quoted[0].kind() == .symbol && quoted[0].symbol_name()! == 'quote' { args[0] = quoted[1] } } if args[0].kind() !in [.string, .symbol] { return error('pkgbuild: the name is a symbol or a string, not ${recipe_tag_name(args[0].kind())}') } pkgbase_name := recipe_item(args[0])! if (args.len - 1) % 2 != 0 { return error('pkgbuild: #:key and value come in pairs') } mut fields := []string{} mut vals := map[string]scheme.Value{} fields << 'name' vals['name'] = scheme.string_value(pkgbase_name) mut i := 1 for i < args.len { kv := args[i] if kv.kind() != .keyword { return error('pkgbuild: expected a #:key, got ${scheme.write(kv)!}') } key := kv.keyword_name()! val := args[i + 1] if key in fields { return error('pkgbuild #:${key} is set twice') } if key in recipe_list_keys { mut items := recipe_items_of(val, key)! match key { 'pkgname' { if items.len == 0 { return error('pkgbuild #:pkgname must not be empty') } for it in items { if it.contains(' ') { return error('pkgbuild #:pkgname: "${it}" has whitespace in it') } } } 'arch' { if items.len == 0 { return error('pkgbuild #:arch must not be empty') } for j, it in items { items[j] = recipe_arch(it) } } 'validpgpkeys' { for j, it in items { recipe_key40(it, j)! } } 'b2sums' { for it in items { recipe_hex(it, 128, 'b2sums')! } } 'sha256sums' { for it in items { recipe_hex(it, 64, 'sha256sums')! } } 'backup' { for it in items { if it.starts_with('/') { return error('pkgbuild #:backup: "${it}" is absolute; backup paths are relative, no leading slash') } } } else {} } mut item_vals := []scheme.Value{} for it in items { item_vals << scheme.string_value(it) } fields << key vals[key] = scheme.list(item_vals) i += 2 continue } if key in recipe_phases || key in recipe_hooks { if val.kind() != .procedure { return error('pkgbuild #:${key} must be a (lambda ...)') } arity := if key in recipe_hooks { recipe_hook_arity(key) } else { 0 } recipe_check_lambda(forms[i + 1], key, arity)! fields << key vals[key] = val i += 2 continue } match key { 'pkgver' { // VCS recipes can calculate the version after extracting the sources. if val.kind() != .string && val.kind() != .procedure { return error('pkgbuild #:pkgver must be a string or a (lambda ...)') } fields << key vals[key] = val } 'pkgrel', 'epoch' { if val.kind() != .integer { return error('pkgbuild #:${key} must be an integer') } if key == 'epoch' && val.as_integer()! < 0 { return error('pkgbuild #:epoch is negative; 0 means absent') } fields << key vals[key] = val } 'pkgdesc', 'url' { if val.kind() != .string { return error('pkgbuild #:${key} must be a string') } fields << key vals[key] = val } else { return error('pkgbuild has no key #:${key}') } } i += 2 } // data-only packages can go straight to the package phase. for req in ['pkgname', 'pkgver', 'pkgrel', 'pkgdesc', 'arch', 'package'] { if req !in fields { return error('pkgbuild: #:${req} is required') } } return vm.call(vm.lookup('vpac-make-pkgbuild')!, [ scheme.vector(fields.map(scheme.string_value(it))), scheme.vector(fields.map(vals[it])), ]) } fn prim_exec(mut _vm scheme.VM, args []scheme.Value) !scheme.Value { mut argv := []string{cap: args.len} for arg in args { argv << arg.as_string()! } run(argv)! return scheme.nil_value() } // prim_glob returns a sorted scheme list for for-each, empty when nothing // matches: the loop in the format example iterates it directly fn prim_glob(mut _vm scheme.VM, args []scheme.Value) !scheme.Value { if args.len != 1 || args[0].kind() != .string { return error('(glob pattern) takes one string pattern') } matches := glob(args[0].as_string()!)! mut out := []scheme.Value{} for m in matches { out << scheme.string_value(m) } return scheme.list(out) } fn prim_pkgdir(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value { return scheme.string_value(pkgdir()!) } fn prim_srcdir(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value { return scheme.string_value(srcdir()!) } fn prim_startdir(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value { return scheme.string_value(startdir()!) } fn prim_this_pkg(mut _vm scheme.VM, _ []scheme.Value) !scheme.Value { return scheme.string_value(this_pkg()!) } // a repository can use a fallback version before it has a matching tag. fn prim_git_desc(mut _vm scheme.VM, args []scheme.Value) !scheme.Value { if args.len == 0 || args.len > 2 || args[0].kind() != .string { return error('(git-desc pattern fallback?) takes a string pattern and an optional string fallback') } pattern := args[0].as_string()! mut fallback := '' if args.len == 2 { if args[1].kind() != .string { return error('(git-desc ...): the fallback must be a string') } fallback = args[1].as_string()! } return scheme.string_value(git_desc(pattern, fallback)!) } // source forms retain literal lambda parameter lists for validation, without // invoking build phases while reading package metadata. fn recipe_check_lambda(form scheme.Value, key string, expected int) ! { if form.kind() != .pair { return } parts := form.list_items()! if parts.len < 2 || parts[0].kind() != .symbol || parts[0].symbol_name()! != 'lambda' { return } params := parts[1].list_items() or { return error('pkgbuild #:${key} needs a fixed parameter list') } if params.len != expected { return error('pkgbuild #:${key} takes ${expected} parameter${if expected == 1 { '' } else { 's' }}, not ${params.len}') } } fn recipe_new_machine() !&scheme.VM { mut m := scheme.new_with_options(max_steps: 100_000_000)! m.register('vpac-defpkgbuild', prim_defpkgbuild)! m.register('run', prim_exec)! m.register('glob', prim_glob)! m.register('pkgdir', prim_pkgdir)! m.register('srcdir', prim_srcdir)! m.register('startdir', prim_startdir)! m.register('this-pkg', prim_this_pkg)! m.register('git-desc', prim_git_desc)! m.eval('(define-record-type vpac-pkgbuild (vpac-make-pkgbuild keys values) vpac-pkgbuild? (keys vpac-pkgbuild-keys) (values vpac-pkgbuild-values)) (define-syntax defpkgbuild (syntax-rules () ((_) (vpac-defpkgbuild (quote ()) (quote ()))) ((_ name arg ...) (vpac-defpkgbuild (quote (name arg ...)) (cons (quote name) (list arg ...))))))')! return m } // use the evaluator's reader so datum comments, escaped symbols and whitespace // have the same meaning here. quoted data is not a package declaration. fn recipe_count_form(arena &reader.DatumArena, id reader.NodeId, mut seen map[reader.NodeId]bool) !int { first := arena.canonical_id(id)! node := arena.node(first)! if node.kind != .pair || first in seen { return 0 } head := arena.node(arena.canonical_id(node.car)!)! mut count := 0 if head.kind == .symbol { name := arena.symbol_name(node.car)! if name in ['quote', 'quasiquote'] { return 0 } if name == 'defpkgbuild' { count++ } } mut cursor := first for cursor !in seen { seen[cursor] = true item := arena.node(cursor)! if item.kind != .pair { break } count += recipe_count_form(arena, item.car, mut seen)! cursor = arena.canonical_id(item.cdr)! } return count } fn recipe_defpkg_count(path string) !int { source := os.read_file(path)! doc := if os.file_ext(path) == '.vile' { reader.read_alt(source)! } else { reader.read_all(source)! } mut seen := map[reader.NodeId]bool{} mut count := 0 for form in doc.forms { count += recipe_count_form(&doc.arena, form, mut seen)! } return count } // recipe_load_in checks that the final value is the package metadata record. fn recipe_load_in(mut m scheme.VM, path string) !PackageMeta { // a recipe that cannot be read fails here, with the read's own reason: the // one-form check is never skipped on the way to a load that reads it count := recipe_defpkg_count(path) or { return error('${path}: ${err.msg()}') } if count > 1 { return error('${path}: one (defpkgbuild ...) form per file, not ${count}') } v := m.eval_file(path)! if v.kind() != .record || v.record_type()!.record_type_name()! != 'vpac-pkgbuild' { return error('${path}: the last form must be a (defpkgbuild ...)') } return package_meta(v)! } // recipe_load reads the final metadata record in the syntax selected by the filename. pub fn recipe_load(path string) !PackageMeta { mut m := recipe_new_machine()! return recipe_load_in(mut m, path)! } // evaluate the phase in the same VM as its metadata and closures. pub fn recipe_run_phase(recipe string, phase string, params []string) ! { mut m := recipe_new_machine()! // load on this machine, not recipe_load's: the bootstrap macro has to be // in the machine that runs the file, with its phases meta := recipe_load_in(mut m, recipe)! if !meta.has(phase) { return error('${recipe}: the pkgbuild has no #:${phase}') } cb := meta.get(phase) if cb.kind() != .procedure { return error('${recipe}: #:${phase} is not a (lambda ...)') } res := m.call(cb, params.map(scheme.string_value(it)))! if phase == 'pkgver' { if res.kind() != .string { return error('pkgver: the lambda ran into ${recipe_tag_name(res.kind())}, not a version string') } println(res.as_string()!) } }