/** * gjs_context_scan_file_for_js_version: * @file_path: (type filename): A file path * * Like gjs_context_scan_buffer_for_js_version(), but will open * the file and use the initial 1024 bytes as a buffer. * * Returns: A string suitable for use as GjsContext::version property. */ const char * gjs_context_scan_file_for_js_version (const char *file_path) { char *utf8_buf; guint8 buf[1024]; const char *version = NULL; gssize len; FILE *f; f = fopen(file_path, "r"); if (!f) return NULL; len = fread(buf, 1, sizeof(buf)-1, f); fclose(f); if (len < 0) return NULL; buf[len] = '\0'; utf8_buf = _gjs_g_utf8_make_valid((const char*)buf); version = gjs_context_scan_buffer_for_js_version(utf8_buf, sizeof(buf)); g_free(utf8_buf); return version; }
int main(int argc, char **argv) { char *command_line; GOptionContext *context; GError *error = NULL; GjsContext *js_context; char *script; const char *filename; gsize len; int code; const char *source_js_version; context = g_option_context_new(NULL); /* pass unknown through to the JS script */ g_option_context_set_ignore_unknown_options(context, TRUE); g_option_context_add_main_entries(context, entries, NULL); if (!g_option_context_parse(context, &argc, &argv, &error)) g_error("option parsing failed: %s", error->message); setlocale(LC_ALL, ""); g_type_init(); command_line = g_strjoinv(" ", argv); g_free(command_line); if (command != NULL) { script = command; source_js_version = gjs_context_scan_buffer_for_js_version(script, 1024); len = strlen(script); filename = "<command line>"; } else if (argc <= 1) { source_js_version = NULL; script = g_strdup("const Console = imports.console; Console.interact();"); len = strlen(script); filename = "<stdin>"; } else /*if (argc >= 2)*/ { error = NULL; if (!g_file_get_contents(argv[1], &script, &len, &error)) { g_printerr("%s\n", error->message); exit(1); } source_js_version = gjs_context_scan_buffer_for_js_version(script, 1024); filename = argv[1]; argc--; argv++; } /* If user explicitly specifies a version, use it */ if (js_version != NULL) source_js_version = js_version; if (source_js_version != NULL) js_context = g_object_new(GJS_TYPE_CONTEXT, "search-path", include_path, "js-version", source_js_version, NULL); else js_context = g_object_new(GJS_TYPE_CONTEXT, "search-path", include_path, NULL); /* prepare command line arguments */ if (!gjs_context_define_string_array(js_context, "ARGV", argc - 1, (const char**)argv + 1, &error)) { g_printerr("Failed to defined ARGV: %s", error->message); exit(1); } /* evaluate the script */ error = NULL; if (!gjs_context_eval(js_context, script, len, filename, &code, &error)) { g_free(script); g_printerr("%s\n", error->message); exit(1); } g_free(script); exit(code); }