| 1 | module vmakepkg |
| 2 | |
| 3 | import json2 |
| 4 | import vile.scheme |
| 5 | import os |
| 6 | |
| 7 | // the body goes through vpac inside the transaction root. paths in the bundle |
| 8 | // are relative to the recipe, including helpers loaded by a later hook. |
| 9 | struct RecipeHook { |
| 10 | recipe string |
| 11 | files map[string]string |
| 12 | } |
| 13 | |
| 14 | const hook_header = '#!/usr/bin/env -S vpac --package-hook\n' |
| 15 | |
| 16 | fn hook_relative_path(name string) bool { |
| 17 | return !name.contains('\x00') && !name.split('/').any(it in ['', '.', '..']) |
| 18 | } |
| 19 | |
| 20 | fn write_recipe_hook(recipe string, work string, helpers []string) !string { |
| 21 | name := os.base(recipe) |
| 22 | base := os.real_path(os.dir(recipe)) + '/' |
| 23 | mut files := { |
| 24 | name: os.read_file(recipe)! |
| 25 | } |
| 26 | for rel in helpers { |
| 27 | path := os.join_path(base, rel) |
| 28 | if !hook_relative_path(rel) || !os.real_path(path).starts_with(base) || !os.is_file(path) { |
| 29 | return error('invalid native hook file: ${rel}') |
| 30 | } |
| 31 | files[rel] = os.read_file(path)! |
| 32 | } |
| 33 | path := os.join_path(work, 'hook') |
| 34 | os.write_file(path, hook_header + json2.encode(RecipeHook{ recipe: name, files: files }))! |
| 35 | return path |
| 36 | } |
| 37 | |
| 38 | pub fn package_hook(args []string) ! { |
| 39 | if args.len < 5 || args[1] != '--nspkg-hook' || args[2] !in recipe_hooks || args.len != 4 + recipe_hook_arity(args[2]) { |
| 40 | return error('invalid native hook arguments') |
| 41 | } |
| 42 | source := os.read_file(args[0])! |
| 43 | if !source.starts_with(hook_header) { return error('unknown recipe hook format') } |
| 44 | bundle := json2.decode[RecipeHook](source[hook_header.len..])! |
| 45 | if bundle.recipe !in ['PKGBUILD.scm', 'PKGBUILD.vile'] || bundle.recipe !in bundle.files { |
| 46 | return error('missing recipe in native hook') |
| 47 | } |
| 48 | dir := private_dir(os.temp_dir())! |
| 49 | defer { os.rmdir_all(dir) or { eprintln('remove staged hook: ${err}') } } |
| 50 | for name, contents in bundle.files { |
| 51 | if !hook_relative_path(name) { |
| 52 | return error('invalid path in native hook') |
| 53 | } |
| 54 | path := os.join_path(dir, name) |
| 55 | os.mkdir_all(os.dir(path))! |
| 56 | os.write_file(path, contents)! |
| 57 | } |
| 58 | path := os.join_path(dir, bundle.recipe) |
| 59 | os.setenv('VPAC_PKGNAME', args[3], true) |
| 60 | mut vm := recipe_new_machine()! |
| 61 | meta := recipe_load_in(mut vm, path)! |
| 62 | if meta.has(args[2]) { vm.call(meta.get(args[2]), args[4..].map(scheme.string_value(it)))! } |
| 63 | } |
| 64 | |