test-json-script.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <json.h>
  4. #include "blobmsg.h"
  5. #include "blobmsg_json.h"
  6. #include "json_script.h"
  7. struct json_script_ctx jctx;
  8. struct blob_buf b_vars;
  9. struct blob_buf b_script;
  10. static void handle_command(struct json_script_ctx *ctx, const char *name,
  11. struct blob_attr *data, struct blob_attr *vars)
  12. {
  13. struct blob_attr *cur;
  14. size_t rem;
  15. fprintf(stdout, "%s", name);
  16. blobmsg_for_each_attr(cur, data, rem)
  17. fprintf(stdout, " %s", (char *) blobmsg_data(cur));
  18. fprintf(stdout, "\n");
  19. }
  20. static struct json_script_file *
  21. handle_file(struct json_script_ctx *ctx, const char *filename)
  22. {
  23. json_object *obj;
  24. obj = json_object_from_file(filename);
  25. if (!obj) {
  26. fprintf(stderr, "load JSON data from %s failed.\n", filename);
  27. return NULL;
  28. }
  29. blob_buf_init(&b_script, 0);
  30. blobmsg_add_json_element(&b_script, "", obj);
  31. json_object_put(obj);
  32. return json_script_file_from_blobmsg(filename,
  33. blob_data(b_script.head), blob_len(b_script.head));
  34. }
  35. static void usage(const char *prog, int exit_code)
  36. {
  37. fprintf(stderr, "Usage: %s [VARNAME=value] <filename_json_script>\n", prog);
  38. exit(exit_code);
  39. }
  40. int main(int argc, char *argv[])
  41. {
  42. int i;
  43. char *file = NULL;
  44. const char *prog = argv[0];
  45. blobmsg_buf_init(&b_vars);
  46. blobmsg_buf_init(&b_script);
  47. json_script_init(&jctx);
  48. jctx.handle_command = handle_command;
  49. jctx.handle_file = handle_file;
  50. for (i = 1; i < argc; i++) {
  51. char *sep = strchr(argv[i], '=');
  52. if (sep) {
  53. *sep = '\0';
  54. blobmsg_add_string(&b_vars, argv[i], sep + 1);
  55. } else if (!file) {
  56. file = argv[i];
  57. } else {
  58. usage(prog, -1);
  59. }
  60. }
  61. if (i < argc || !file)
  62. usage(prog, -2);
  63. json_script_run(&jctx, file, b_vars.head);
  64. json_script_free(&jctx);
  65. blob_buf_free(&b_script);
  66. blob_buf_free(&b_vars);
  67. return 0;
  68. }