Ccli.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "stdinc.h"
  10. #include "9.h"
  11. typedef struct {
  12. int8_t* argv0;
  13. int (*cmd)(int, int8_t*[]);
  14. } Cmd;
  15. static struct {
  16. VtLock* lock;
  17. Cmd* cmd;
  18. int ncmd;
  19. int hi;
  20. } cbox;
  21. enum {
  22. NCmdIncr = 20,
  23. };
  24. int
  25. cliError(int8_t* fmt, ...)
  26. {
  27. int8_t *p;
  28. va_list arg;
  29. va_start(arg, fmt);
  30. p = vsmprint(fmt, arg);
  31. vtSetError("%s", p);
  32. free(p);
  33. va_end(arg);
  34. return 0;
  35. }
  36. int
  37. cliExec(int8_t* buf)
  38. {
  39. int argc, i, r;
  40. int8_t *argv[20], *p;
  41. p = vtStrDup(buf);
  42. if((argc = tokenize(p, argv, nelem(argv)-1)) == 0){
  43. vtMemFree(p);
  44. return 1;
  45. }
  46. argv[argc] = 0;
  47. if(argv[0][0] == '#'){
  48. vtMemFree(p);
  49. return 1;
  50. }
  51. vtLock(cbox.lock);
  52. for(i = 0; i < cbox.hi; i++){
  53. if(strcmp(cbox.cmd[i].argv0, argv[0]) == 0){
  54. vtUnlock(cbox.lock);
  55. if(!(r = cbox.cmd[i].cmd(argc, argv)))
  56. consPrint("%s\n", vtGetError());
  57. vtMemFree(p);
  58. return r;
  59. }
  60. }
  61. vtUnlock(cbox.lock);
  62. consPrint("%s: - eh?\n", argv[0]);
  63. vtMemFree(p);
  64. return 0;
  65. }
  66. int
  67. cliAddCmd(int8_t* argv0, int (*cmd)(int, int8_t*[]))
  68. {
  69. int i;
  70. Cmd *opt;
  71. vtLock(cbox.lock);
  72. for(i = 0; i < cbox.hi; i++){
  73. if(strcmp(argv0, cbox.cmd[i].argv0) == 0){
  74. vtUnlock(cbox.lock);
  75. return 0;
  76. }
  77. }
  78. if(i >= cbox.hi){
  79. if(cbox.hi >= cbox.ncmd){
  80. cbox.cmd = vtMemRealloc(cbox.cmd,
  81. (cbox.ncmd+NCmdIncr)*sizeof(Cmd));
  82. memset(&cbox.cmd[cbox.ncmd], 0, NCmdIncr*sizeof(Cmd));
  83. cbox.ncmd += NCmdIncr;
  84. }
  85. }
  86. opt = &cbox.cmd[cbox.hi];
  87. opt->argv0 = argv0;
  88. opt->cmd = cmd;
  89. cbox.hi++;
  90. vtUnlock(cbox.lock);
  91. return 1;
  92. }
  93. int
  94. cliInit(void)
  95. {
  96. cbox.lock = vtLockAlloc();
  97. cbox.cmd = vtMemAllocZ(NCmdIncr*sizeof(Cmd));
  98. cbox.ncmd = NCmdIncr;
  99. cbox.hi = 0;
  100. return 1;
  101. }