script.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. /* vcc/plugins/script/script.c
  2. *
  3. * This file is part of vcc.
  4. *
  5. * vcc is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * vcc is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with vcc. If not, see <https://www.gnu.org/licenses/>
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <vcc/vcc.h>
  22. #include <vcc/pretty.h>
  23. #include <vcc/plugin.h>
  24. #include <vcc/version.h>
  25. int do_cmd_if(int argc, char **argv);
  26. int handle_command(char *s);
  27. struct cmdtable script_cmdtab[] = {
  28. { "-if", do_cmd_if, "-if condition then ... else ..." },
  29. { NULL, NULL, NULL }
  30. };
  31. struct plugin plg_script = {
  32. .state = 0,
  33. .name = "script",
  34. .descr = "Standard vcc script. ",
  35. .cmdtab = script_cmdtab
  36. };
  37. #define this_plg (&plg_script)
  38. static char *copy_until(char **argv, char *until, int *dst) {
  39. int i;
  40. char buf[MSG_SIZE];
  41. memset(buf, 0, MSG_SIZE);
  42. for (i = *dst; argv[i] && strcmp(argv[i], until); i++) {
  43. strcat(buf, argv[i]);
  44. strcat(buf, " ");
  45. }
  46. if (!argv[i]) {
  47. if (i == *dst)
  48. return NULL;
  49. else
  50. return strdup(buf);
  51. }
  52. *dst = ++i;
  53. return strdup(buf);
  54. }
  55. static int parse_if(char **argv, char **cond, char **then, char **else_then) {
  56. int i = 1;
  57. *cond = copy_until(argv, "then", &i);
  58. *then = copy_until(argv, "else", &i);
  59. /* it must present */
  60. *else_then = copy_until(argv, "", &i);
  61. if (!*cond || !*then || !*else_then)
  62. return 1;
  63. return 0;
  64. }
  65. int do_cmd_if(int argc, char **argv) {
  66. char *cond, *then, *else_then;
  67. plg_check_enabled();
  68. if (argc < 4) {
  69. fprintf(stderr, _("usage: -if condition then ... else ...\n"));
  70. return 1;
  71. }
  72. if (parse_if(argv, &cond, &then, &else_then))
  73. return 1;
  74. /* we always use '0' for success ... */
  75. if (!handle_command(cond))
  76. handle_command(then);
  77. else {
  78. if (!else_then)
  79. return 0;
  80. handle_command(else_then);
  81. }
  82. free(cond);
  83. free(then);
  84. free(else_then);
  85. return 0;
  86. }