kcommand.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include <faux/str.h>
  6. #include <faux/list.h>
  7. #include <klish/khelper.h>
  8. #include <klish/kparam.h>
  9. #include <klish/kaction.h>
  10. #include <klish/kcommand.h>
  11. struct kcommand_s {
  12. char *name;
  13. char *help;
  14. faux_list_t *params;
  15. faux_list_t *actions;
  16. };
  17. // Simple attributes
  18. // Name
  19. KGET_STR(command, name);
  20. // Help
  21. KGET_STR(command, help);
  22. KSET_STR(command, help);
  23. // PARAM list
  24. KGET(command, faux_list_t *, params);
  25. static KCMP_NESTED(command, param, name);
  26. static KCMP_NESTED_BY_KEY(command, param, name);
  27. KADD_NESTED(command, kparam_t *, params);
  28. KFIND_NESTED(command, param);
  29. KNESTED_LEN(command, params);
  30. KNESTED_ITER(command, params);
  31. KNESTED_EACH(command, kparam_t *, params);
  32. // ACTION list
  33. KGET(command, faux_list_t *, actions);
  34. KADD_NESTED(command, kaction_t *, actions);
  35. KNESTED_LEN(command, actions);
  36. KNESTED_ITER(command, actions);
  37. KNESTED_EACH(command, kaction_t *, actions);
  38. kcommand_t *kcommand_new(const char *name)
  39. {
  40. kcommand_t *command = NULL;
  41. if (faux_str_is_empty(name))
  42. return NULL;
  43. command = faux_zmalloc(sizeof(*command));
  44. assert(command);
  45. if (!command)
  46. return NULL;
  47. // Initialize
  48. command->name = faux_str_dup(name);
  49. command->help = NULL;
  50. // PARAM list
  51. command->params = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_UNIQUE,
  52. kcommand_param_compare, kcommand_param_kcompare,
  53. (void (*)(void *))kparam_free);
  54. assert(command->params);
  55. // ACTION list
  56. command->actions = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_NONUNIQUE,
  57. NULL, NULL, (void (*)(void *))kaction_free);
  58. assert(command->actions);
  59. return command;
  60. }
  61. void kcommand_free(kcommand_t *command)
  62. {
  63. if (!command)
  64. return;
  65. faux_str_free(command->name);
  66. faux_str_free(command->help);
  67. faux_list_free(command->params);
  68. faux_list_free(command->actions);
  69. faux_free(command);
  70. }