usage.c (1210B)
1 #include <u.h> 2 #include <libc.h> 3 4 void 5 main(int argc, char **argv) 6 { 7 Fmt fmt; 8 char buf[512]; 9 char *argv0, *args, *flags, *p, *p0; 10 int single; 11 Rune r; 12 13 argv0 = getenv("0"); 14 if(argv0 == nil) { 15 if(argc > 1) 16 argv0 = argv[1]; 17 else 18 argv0 = "unknown-program-name"; 19 } 20 if((p = strrchr(argv0, '/')) != nil) 21 argv0 = p+1; 22 flags = getenv("flagfmt"); 23 args = getenv("args"); 24 25 if(argv0 == nil){ 26 fprint(2, "aux/usage: $0 not set\n"); 27 exits("$0"); 28 } 29 if(flags == nil) 30 flags = ""; 31 if(args == nil) 32 args = ""; 33 34 fmtfdinit(&fmt, 2, buf, sizeof buf); 35 fmtprint(&fmt, "usage: %s", argv0); 36 if(flags[0]){ 37 single = 0; 38 for(p=flags; *p; ){ 39 p += chartorune(&r, p); 40 if(*p == ',' || *p == 0){ 41 if(!single){ 42 fmtprint(&fmt, " [-"); 43 single = 1; 44 } 45 fmtprint(&fmt, "%C", r); 46 if(*p == ',') 47 p++; 48 continue; 49 } 50 while(*p == ' ') 51 p++; 52 if(single){ 53 fmtprint(&fmt, "]"); 54 single = 0; 55 } 56 p0 = p; 57 p = strchr(p0, ','); 58 if(p == nil) 59 p = ""; 60 else 61 *p++ = 0; 62 fmtprint(&fmt, " [-%C %s]", r, p0); 63 } 64 if(single) 65 fmtprint(&fmt, "]"); 66 } 67 if(args) 68 fmtprint(&fmt, " %s", args); 69 fmtprint(&fmt, "\n"); 70 fmtfdflush(&fmt); 71 exits("usage"); 72 }