cmdline.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * \file cmdline.c
  3. *
  4. * \brief Commandline utilities.
  5. *
  6. * Frontend to QA, proving an easy command line inteface according with the
  7. * POSIX standard.
  8. */
  9. #define _GNU_SOURCE
  10. #include <getopt.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <errno.h>
  15. #include "qa.h"
  16. /**
  17. * \brief Prints the usage message, then exit.
  18. *
  19. * Prints in POSIX format the various options for using qa.
  20. *
  21. */
  22. void usage(void)
  23. {
  24. static const char* help_message = "%s usage: %s"
  25. " [-r HOST:port | -f FILE]"
  26. " \n";
  27. fprintf(stderr, help_message,
  28. program_invocation_short_name,
  29. program_invocation_name);
  30. }
  31. void conflicting_args(void)
  32. {
  33. printf("Conflicting fuffa\n");
  34. usage();
  35. exit(EXIT_FAILURE);
  36. }
  37. int main(int argc, char** argv)
  38. {
  39. char opt;
  40. int option_index;
  41. size_t i;
  42. struct option long_options[] = {
  43. {"help", no_argument, NULL, 'h'},
  44. {"remote", required_argument, NULL, 'r'},
  45. {"file", required_argument, NULL, 'f'},
  46. {0, 0, 0, 0}
  47. };
  48. static const char* short_options = "hr:f:";
  49. struct qa_conf conf = {
  50. .src_type = NONE,
  51. };
  52. while ((opt=getopt_long(argc, argv,
  53. short_options, long_options,
  54. &option_index)) != -1)
  55. switch (opt) {
  56. case 'h':
  57. usage();
  58. exit(EXIT_SUCCESS);
  59. break;
  60. case 'f':
  61. if (conf.src_type != NONE) conflicting_args();
  62. conf.src_type = LOCAL;
  63. conf.src = optarg;
  64. break;
  65. case 'r':
  66. if (conf.src_type != NONE) conflicting_args();
  67. conf.src_type = REMOTE;
  68. conf.src = optarg;
  69. break;
  70. case '?':
  71. default:
  72. usage();
  73. exit(EXIT_FAILURE);
  74. }
  75. if (conf.src_type == NONE) {
  76. conf.src_type = REMOTE;
  77. if (optind == argc)
  78. conf.src = "-";
  79. else if (optind == argc-1)
  80. conf.src = argv[optind];
  81. else if (optind == argc-2 && !strcmp(argv[optind], "--"))
  82. conf.src = argv[optind+1];
  83. else {
  84. usage();
  85. exit(EXIT_FAILURE);
  86. }
  87. }
  88. return qa_init(&conf);
  89. }