diff options
author | Jo-Philipp Wich <jo@mein.io> | 2020-09-17 13:57:22 +0200 |
---|---|---|
committer | Jo-Philipp Wich <jo@mein.io> | 2020-09-20 20:45:26 +0200 |
commit | 9a74b811f007986a3e6015af0c06b33147d05951 (patch) | |
tree | 43e794cb1f35582c98eab8f8a1f4d54299cf2557 /main.c | |
parent | 2601b1e17f5ba2e15fb16e126ec5d22a39246649 (diff) |
eval: implement -m option to preload modules
The -m option instructs the interpreter to automatically require the named
module and to register the module context as global variable.
The following two commands are equivalent, with the former one serving as
a shortcut for the latter:
utpl -m fs -s '{{ fs.open("test.txt").read("all") }}'
utpl -s '{% fs = require("fs"); print(fs.open("test.txt").read("all")) %}'
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
Diffstat (limited to 'main.c')
-rw-r--r-- | main.c | 23 |
1 files changed, 17 insertions, 6 deletions
@@ -47,7 +47,8 @@ print_usage(char *app) " -r Do not trim trailing block newlines\n" " -S Enable strict mode\n" " -e Set global variables from given JSON object\n" - " -E Set global variables from given JSON file\n", + " -E Set global variables from given JSON file\n" + " -m Preload given module\n", app); } @@ -141,7 +142,8 @@ static void dump(struct ut_state *s, uint32_t off, int level) { #endif /* NDEBUG */ static enum ut_error_type -parse(struct ut_state *state, const char *source, bool dumponly, struct json_object *env) +parse(struct ut_state *state, const char *source, bool dumponly, + struct json_object *env, struct json_object *modules) { enum ut_error_type err; char *msg; @@ -158,7 +160,7 @@ parse(struct ut_state *state, const char *source, bool dumponly, struct json_obj #endif /* NDEBUG */ } else { - err = ut_run(state, env); + err = ut_run(state, env, modules); } } @@ -232,7 +234,7 @@ int main(int argc, char **argv) { char *srcstr = NULL, *srcfile = NULL, *envstr = NULL; - struct json_object *env = NULL, *o; + struct json_object *env = NULL, *modules = NULL, *o; struct ut_state *state; bool dumponly = false; int opt, rv = 0; @@ -253,7 +255,7 @@ main(int argc, char **argv) state->lstrip_blocks = 1; state->trim_blocks = 1; - while ((opt = getopt(argc, argv, "dhlrSe:E:i:s:")) != -1) + while ((opt = getopt(argc, argv, "dhlrSe:E:i:s:m:")) != -1) { switch (opt) { case 'h': @@ -322,6 +324,13 @@ main(int argc, char **argv) json_object_object_add(env, key, val); break; + + case 'm': + modules = modules ? modules : json_object_new_array(); + + json_object_array_add(modules, json_object_new_string(optarg)); + + break; } } @@ -332,9 +341,11 @@ main(int argc, char **argv) goto out; } - rv = parse(state, srcstr ? srcstr : srcfile, dumponly, env); + rv = parse(state, srcstr ? srcstr : srcfile, dumponly, env, modules); out: + json_object_put(modules); + json_object_put(env); free(srcfile); return rv; |