9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

getflags.c (1360B)


      1 #include <u.h>
      2 #include <libc.h>
      3 
      4 void
      5 usage(void)
      6 {
      7 	print("status=usage\n");
      8 	exits(0);
      9 }
     10 
     11 char*
     12 findarg(char *flags, Rune r)
     13 {
     14 	char *p;
     15 	Rune rr;
     16 	
     17 	for(p=flags; p!=(char*)1; p=strchr(p, ',')+1){
     18 		chartorune(&rr, p);
     19 		if(rr == r)
     20 			return p;
     21 	}
     22 	return nil;	
     23 }
     24 
     25 int
     26 countargs(char *p)
     27 {
     28 	int n;
     29 
     30 	n = 1;
     31 	while(*p == ' ')
     32 		p++;
     33 	for(; *p && *p != ','; p++)
     34 		if(*p == ' ' && *(p-1) != ' ')
     35 			n++;
     36 	return n;
     37 }
     38 
     39 void
     40 main(int argc, char *argv[])
     41 {
     42 	char *flags, *p, buf[512];
     43 	int i, n;
     44 	Fmt fmt;
     45 	
     46 	quotefmtinstall();
     47 	argv0 = argv[0];	/* for sysfatal */
     48 	
     49 	flags = getenv("flagfmt");
     50 	if(flags == nil){
     51 		fprint(2, "$flagfmt not set\n");
     52 		print("exit 'missing flagfmt'");
     53 		exits(0);
     54 	}
     55 
     56 	fmtfdinit(&fmt, 1, buf, sizeof buf);
     57 	for(p=flags; p!=(char*)1; p=strchr(p, ',')+1)
     58 		fmtprint(&fmt, "flag%.1s=()\n", p);
     59 	ARGBEGIN{
     60 	default:
     61 		if((p = findarg(flags, ARGC())) == nil)
     62 			usage();
     63 		p += runelen(ARGC());
     64 		if(*p == ',' || *p == 0){
     65 			fmtprint(&fmt, "flag%C=1\n", ARGC());
     66 			break;
     67 		}
     68 		n = countargs(p);
     69 		fmtprint(&fmt, "flag%C=(", ARGC());
     70 		for(i=0; i<n; i++)
     71 			fmtprint(&fmt, "%s%q", i ? " " : "", EARGF(usage()));
     72 		fmtprint(&fmt, ")\n");
     73 	}ARGEND
     74 	
     75 	fmtprint(&fmt, "*=(");
     76 	for(i=0; i<argc; i++)
     77 		fmtprint(&fmt, "%s%q", i ? " " : "", argv[i]);
     78 	fmtprint(&fmt, ")\n");
     79 	fmtprint(&fmt, "status=''\n");
     80 	fmtfdflush(&fmt);
     81 	exits(0);
     82 }