kcommand.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. static KCMP_NESTED(command, param, name);
  25. static KCMP_NESTED_BY_KEY(command, param, name);
  26. KADD_NESTED(command, param);
  27. KFIND_NESTED(command, param);
  28. KNESTED_LEN(command, param);
  29. // ACTION list
  30. KADD_NESTED(command, action);
  31. KNESTED_LEN(command, action);
  32. kcommand_t *kcommand_new(const char *name)
  33. {
  34. kcommand_t *command = NULL;
  35. if (faux_str_is_empty(name))
  36. return NULL;
  37. command = faux_zmalloc(sizeof(*command));
  38. assert(command);
  39. if (!command)
  40. return NULL;
  41. // Initialize
  42. command->name = faux_str_dup(name);
  43. command->help = NULL;
  44. // PARAM list
  45. command->params = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_UNIQUE,
  46. kcommand_param_compare, kcommand_param_kcompare,
  47. (void (*)(void *))kparam_free);
  48. assert(command->params);
  49. // ACTION list
  50. command->actions = faux_list_new(FAUX_LIST_UNSORTED, FAUX_LIST_NONUNIQUE,
  51. NULL, NULL, (void (*)(void *))kaction_free);
  52. assert(command->actions);
  53. return command;
  54. }
  55. void kcommand_free(kcommand_t *command)
  56. {
  57. if (!command)
  58. return;
  59. faux_str_free(command->name);
  60. faux_str_free(command->help);
  61. faux_list_free(command->params);
  62. faux_list_free(command->actions);
  63. faux_free(command);
  64. }