opts.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <assert.h>
  6. #include <unistd.h>
  7. #include <errno.h>
  8. #include <sys/types.h>
  9. #include <sys/stat.h>
  10. #include <fcntl.h>
  11. #include <getopt.h>
  12. #include <faux/faux.h>
  13. #include <faux/str.h>
  14. #include <klish/ktp_session.h>
  15. #include "private.h"
  16. /** @brief Initialize option structure by defaults
  17. */
  18. struct options *opts_init(void)
  19. {
  20. struct options *opts = NULL;
  21. opts = faux_zmalloc(sizeof(*opts));
  22. assert(opts);
  23. // Initialize
  24. opts->verbose = BOOL_FALSE;
  25. opts->socket = faux_str_dup(KLISH_DEFAULT_UNIX_SOCKET_PATH);
  26. return opts;
  27. }
  28. /** @brief Free options structure
  29. */
  30. void opts_free(struct options *opts)
  31. {
  32. if (!opts)
  33. return;
  34. faux_str_free(opts->socket);
  35. faux_free(opts);
  36. }
  37. /** @brief Parse command line options
  38. */
  39. int opts_parse(int argc, char *argv[], struct options *opts)
  40. {
  41. static const char *shortopts = "hvS:";
  42. static const struct option longopts[] = {
  43. {"socket", 1, NULL, 'S'},
  44. {"help", 0, NULL, 'h'},
  45. {"verbose", 0, NULL, 'v'},
  46. {NULL, 0, NULL, 0}
  47. };
  48. optind = 1;
  49. while(1) {
  50. int opt = 0;
  51. opt = getopt_long(argc, argv, shortopts, longopts, NULL);
  52. if (-1 == opt)
  53. break;
  54. switch (opt) {
  55. case 'S':
  56. faux_str_free(opts->socket);
  57. opts->socket = faux_str_dup(optarg);
  58. break;
  59. case 'v':
  60. opts->verbose = BOOL_TRUE;
  61. break;
  62. case 'h':
  63. help(0, argv[0]);
  64. _exit(0);
  65. break;
  66. default:
  67. help(-1, argv[0]);
  68. _exit(-1);
  69. break;
  70. }
  71. }
  72. return 0;
  73. }
  74. /** @brief Print help message
  75. */
  76. void help(int status, const char *argv0)
  77. {
  78. const char *name = NULL;
  79. if (!argv0)
  80. return;
  81. // Find the basename
  82. name = strrchr(argv0, '/');
  83. if (name)
  84. name++;
  85. else
  86. name = argv0;
  87. if (status != 0) {
  88. fprintf(stderr, "Try `%s -h' for more information.\n",
  89. name);
  90. } else {
  91. printf("Version : %s\n", VERSION);
  92. printf("Usage : %s [options]\n", name);
  93. printf("Klish client\n");
  94. printf("Options :\n");
  95. printf("\t-S, --socket UNIX socket path.\n");
  96. printf("\t-h, --help Print this help.\n");
  97. printf("\t-v, --verbose Be verbose.\n");
  98. }
  99. }