chiark / gitweb /
As submitted as bug and sent to PJB and RJK.
[chiark-utils.git] / cprogs / myopt.c
1 /*
2  * myopt.c - my very own option parsing
3  *
4  * Copyright (C) 1994,1995,1998 Ian Jackson <ian@chiark.greenend.org.uk>
5  *
6  * This is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2,
9  * or (at your option) any later version.
10  *
11  * This is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this file; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #include <string.h>
22
23 #include "myopt.h"
24
25 void myopt(const char *const **argvp, const struct cmdinfo *cmdinfos) {
26   const struct cmdinfo *cip;
27   const char *p, *value;
28   int l;
29
30   ++(*argvp);
31   while ((p= **argvp) && *p == '-') {
32     ++(*argvp);
33     if (!strcmp(p,"--")) break;
34     if (*++p == '-') {
35       ++p; value=0;
36       for (cip= cmdinfos;
37            cip->olong || cip->oshort;
38            cip++) {
39         if (!cip->olong) continue;
40         if (!strcmp(p,cip->olong)) break;
41         l= strlen(cip->olong);
42         if (!strncmp(p,cip->olong,l) &&
43             (p[l]== ((cip->takesvalue==2) ? '-' : '='))) { value=p+l+1; break; }
44       }
45       if (!cip->olong) badusage("unknown option --%s",p);
46       if (cip->takesvalue) {
47         if (!value) {
48           value= *(*argvp)++;
49           if (!value) badusage("--%s option takes a value",cip->olong);
50         }
51         if (cip->call) cip->call(cip,value);
52         else *cip->sassignto= value;
53       } else {
54         if (value) badusage("--%s option does not take a value",cip->olong);
55         if (cip->call) cip->call(cip,0);
56         else *cip->iassignto= cip->arg;
57       }
58     } else {
59       while (*p) {
60         for (cip= cmdinfos; (cip->olong || cip->oshort) && *p != cip->oshort; cip++);
61         if (!cip->oshort) badusage("unknown option -%c",*p);
62         p++;
63         if (cip->takesvalue) {
64           if (!*p) {
65             value= *(*argvp)++;
66             if (!value) badusage("-%c option takes a value",cip->oshort);
67           } else {
68             value= p; p="";
69             if (*value == '=') value++;
70           }
71           if (cip->call) cip->call(cip,value);
72           else *cip->sassignto= value;
73         } else {
74           if (*p == '=') badusage("-%c option does not take a value",cip->oshort);
75           if (cip->call) cip->call(cip,0);
76           else *cip->iassignto= cip->arg;
77         }
78       }
79     }
80   }
81 }