Blob
1 #include "stdinc.h"3 #include "9.h"5 typedef struct {6 char* argv0;7 int (*cmd)(int, char*[]);8 } Cmd;10 static struct {11 QLock lock;12 Cmd* cmd;13 int ncmd;14 int hi;15 } cbox;17 enum {18 NCmdIncr = 20,19 };21 int22 cliError(char* fmt, ...)23 {24 char *p;25 va_list arg;27 va_start(arg, fmt);28 p = vsmprint(fmt, arg);29 werrstr("%s", p);30 free(p);31 va_end(arg);33 return 0;34 }36 int37 cliExec(char* buf)38 {39 int argc, i, r;40 char *argv[20], *p;42 p = vtstrdup(buf);43 if((argc = tokenize(p, argv, nelem(argv)-1)) == 0){44 vtfree(p);45 return 1;46 }47 argv[argc] = 0;49 if(argv[0][0] == '#'){50 vtfree(p);51 return 1;52 }54 qlock(&cbox.lock);55 for(i = 0; i < cbox.hi; i++){56 if(strcmp(cbox.cmd[i].argv0, argv[0]) == 0){57 qunlock(&cbox.lock);58 if(!(r = cbox.cmd[i].cmd(argc, argv)))59 consPrint("%r\n");60 vtfree(p);61 return r;62 }63 }64 qunlock(&cbox.lock);66 consPrint("%s: - eh?\n", argv[0]);67 vtfree(p);69 return 0;70 }72 int73 cliAddCmd(char* argv0, int (*cmd)(int, char*[]))74 {75 int i;76 Cmd *opt;78 qlock(&cbox.lock);79 for(i = 0; i < cbox.hi; i++){80 if(strcmp(argv0, cbox.cmd[i].argv0) == 0){81 qunlock(&cbox.lock);82 return 0;83 }84 }85 if(i >= cbox.hi){86 if(cbox.hi >= cbox.ncmd){87 cbox.cmd = vtrealloc(cbox.cmd,88 (cbox.ncmd+NCmdIncr)*sizeof(Cmd));89 memset(&cbox.cmd[cbox.ncmd], 0, NCmdIncr*sizeof(Cmd));90 cbox.ncmd += NCmdIncr;91 }92 }94 opt = &cbox.cmd[cbox.hi];95 opt->argv0 = argv0;96 opt->cmd = cmd;97 cbox.hi++;98 qunlock(&cbox.lock);100 return 1;101 }103 int104 cliInit(void)105 {106 cbox.cmd = vtmallocz(NCmdIncr*sizeof(Cmd));107 cbox.ncmd = NCmdIncr;108 cbox.hi = 0;110 return 1;111 }