stew

a monorepo of some sort
git clone git://git.nsmpr.xyz/stew.git
Log | Files | Refs

cli.c (1621B)


      1 /*
      2 	primitive client for primitive key-value database
      3 */
      4 
      5 #include <u.h>
      6 #include <libc.h>
      7 
      8 #include "keyval.h"
      9 
     10 int i, fd;
     11 char *opstr, *keystr;
     12 
     13 Keyval kv;
     14 KVHeader *kh = (KVHeader *)(&kv);;		
     15 
     16 struct Dict { char *s; int op; };
     17 struct Dict dict[] = {
     18 	{"get", KVGet},
     19 	{"set", KVSet},
     20 	{"keyreg", KVKeyreg},
     21 	{nil, 0},
     22 };
     23 
     24 void
     25 usage(void)
     26 {
     27 	fprint(2, "usage: %s get|set key\n", argv0);
     28 	exits("usage");
     29 }
     30 
     31 void
     32 main(int argc, char **argv)
     33 {
     34 	ARGBEGIN{
     35 	default:
     36 		usage();
     37 	}ARGEND;
     38 	fd = open("/mnt/keyval/ctl", ORDWR);
     39 	if (fd < 0) sysfatal("%r");
     40 
     41 	if (argc == 0) usage();
     42 	opstr = argv[0];
     43 	argc--, argv++;
     44 
     45 	for(kv.op = 0, i = 0; dict[i].s != nil; i++) {
     46 		if (strcmp(opstr, dict[i].s) == 0) {
     47 			kv.op = dict[i].op;
     48 			break;
     49 		}
     50 	}
     51 
     52 	if (argc == 0) usage();
     53 	keystr = argv[0];
     54 	argc--;// argv++;
     55 	if (argc != 0) usage();
     56 
     57 	memcpy(kv.key, keystr, strlen(keystr));
     58 
     59 	switch(kv.op) {
     60 	case KVGet:
     61 		kv.count = MetaSize;
     62 		write(fd, &kv, MetaSize);
     63 		read(fd, &kv, BufSize);
     64 		if (kv.count == 0) return;
     65 		write(1, kv.data, kv.count - MetaSize);
     66 		break;
     67 	case KVSet:
     68 		kv.count = MetaSize + read(0, kv.data, DataSize);
     69 		kv.count = write(fd, &kv, kv.count);
     70 		break;
     71 	case KVKeyreg:
     72 		kv.count = MetaSize + strlen(keystr);
     73 		memcpy(kv.data, keystr, kv.count - MetaSize);
     74 		write(fd, &kv, kv.count);
     75 		read(fd, &kv, BufSize);
     76 		keystr = mallocz(KeySize + 1, 1);
     77 		for (i = 0; i < 32; i++) {
     78 			if (kh[i].count == 0) break;
     79 			memcpy(keystr, kh[i].key, KeySize);
     80 			print("%s\n", keystr);
     81 		}
     82 		free(keystr);
     83 		break;
     84 	case KVValreg:
     85 		break;
     86 	default:
     87 		fprint(2, "bad op\n");
     88 		exits("bad op");
     89 	}
     90 	exits(nil);
     91 }