utils.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #define _GNU_SOURCE
  2. #include <ccan/tap/tap.h>
  3. #include <stdarg.h>
  4. #include <stdlib.h>
  5. #include <ccan/opt/opt.h>
  6. #include <getopt.h>
  7. #include <string.h>
  8. #include <stdio.h>
  9. #include "utils.h"
  10. unsigned int test_cb_called;
  11. char *test_noarg(void *arg)
  12. {
  13. test_cb_called++;
  14. return NULL;
  15. }
  16. char *test_arg(const char *optarg, const char *arg)
  17. {
  18. test_cb_called++;
  19. ok1(strcmp(optarg, arg) == 0);
  20. return NULL;
  21. }
  22. void show_arg(char buf[OPT_SHOW_LEN], const char *arg)
  23. {
  24. strncpy(buf, arg, OPT_SHOW_LEN);
  25. }
  26. char *err_output = NULL;
  27. static void save_err_output(const char *fmt, ...)
  28. {
  29. va_list ap;
  30. char *p;
  31. va_start(ap, fmt);
  32. vasprintf(&p, fmt, ap);
  33. va_end(ap);
  34. if (err_output) {
  35. err_output = realloc(err_output,
  36. strlen(err_output) + strlen(p) + 1);
  37. strcat(err_output, p);
  38. free(p);
  39. } else
  40. err_output = p;
  41. }
  42. /* FIXME: This leaks, BTW. */
  43. bool parse_args(int *argc, char ***argv, ...)
  44. {
  45. char **a;
  46. va_list ap;
  47. va_start(ap, argv);
  48. *argc = 1;
  49. a = malloc(sizeof(*a) * (*argc + 1));
  50. a[0] = (*argv)[0];
  51. while ((a[*argc] = va_arg(ap, char *)) != NULL) {
  52. (*argc)++;
  53. a = realloc(a, sizeof(*a) * (*argc + 1));
  54. }
  55. *argv = a;
  56. /* Re-set before parsing. */
  57. optind = 0;
  58. return opt_parse(argc, *argv, save_err_output);
  59. }
  60. struct opt_table short_table[] = {
  61. /* Short opts, different args. */
  62. OPT_WITHOUT_ARG("-a", test_noarg, "a", "Description of a"),
  63. OPT_WITH_ARG("-b", test_arg, show_arg, "b", "Description of b"),
  64. OPT_ENDTABLE
  65. };
  66. struct opt_table long_table[] = {
  67. /* Long opts, different args. */
  68. OPT_WITHOUT_ARG("--ddd", test_noarg, "ddd", "Description of ddd"),
  69. OPT_WITH_ARG("--eee <filename>", test_arg, show_arg, "eee", ""),
  70. OPT_ENDTABLE
  71. };
  72. struct opt_table long_and_short_table[] = {
  73. /* Short and long, different args. */
  74. OPT_WITHOUT_ARG("--ggg/-g", test_noarg, "ggg", "Description of ggg"),
  75. OPT_WITH_ARG("-h/--hhh", test_arg, NULL, "hhh", "Description of hhh"),
  76. OPT_ENDTABLE
  77. };
  78. /* Sub-table test. */
  79. struct opt_table subtables[] = {
  80. /* Two short, and two long long, no description */
  81. OPT_WITH_ARG("--jjj/-j/--lll/-l", test_arg, show_arg, "jjj", ""),
  82. /* Hidden option */
  83. OPT_WITH_ARG("--mmm/-m", test_arg, show_arg, "mmm", opt_hidden),
  84. OPT_SUBTABLE(short_table, NULL),
  85. OPT_SUBTABLE(long_table, "long table options"),
  86. OPT_SUBTABLE(long_and_short_table, NULL),
  87. OPT_ENDTABLE
  88. };