1 /*****************************************************************************
2 * getopt.c - competent and free getopt library.
3 *
4 * Copyright (c)2002-2003 Mark K. Kim
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 *   * Redistributions of source code must retain the above copyright
12 *     notice, this list of conditions and the following disclaimer.
13 *
14 *   * Redistributions in binary form must reproduce the above copyright
15 *     notice, this list of conditions and the following disclaimer in
16 *     the documentation and/or other materials provided with the
17 *     distribution.
18 *
19 *   * Neither the original author of this software nor the names of its
20 *     contributors may be used to endorse or promote products derived
21 *     from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
30 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
31 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
33 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
34 * DAMAGE.
35 */
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include "getopt.h"
40 
41 
42 char* optarg = NULL;
43 int optind = 0;
44 int opterr = 1;
45 int optopt = '?';
46 
47 
48 static char** prev_argv = NULL;        /* Keep a copy of argv and argc to */
49 static int prev_argc = 0;              /*    tell if getopt params change */
50 static int argv_index = 0;             /* Option we're checking */
51 static int argv_index2 = 0;            /* Option argument we're checking */
52 static int opt_offset = 0;             /* Index into compounded "-option" */
53 static int dashdash = 0;               /* True if "--" option reached */
54 static int nonopt = 0;                 /* How many nonopts we've found */
55 
increment_index()56 static void increment_index()
57 {
58 	/* Move onto the next option */
59 	if(argv_index < argv_index2)
60 	{
61 		while(prev_argv[++argv_index] && prev_argv[argv_index][0] != '-'
62 				&& argv_index < argv_index2+1);
63 	}
64 	else argv_index++;
65 	opt_offset = 1;
66 }
67 
68 
69 /*
70 * Permutes argv[] so that the argument currently being processed is moved
71 * to the end.
72 */
permute_argv_once()73 static int permute_argv_once()
74 {
75 	/* Movability check */
76 	if(argv_index + nonopt >= prev_argc) return 1;
77 	/* Move the current option to the end, bring the others to front */
78 	else
79 	{
80 		char* tmp = prev_argv[argv_index];
81 
82 		/* Move the data */
83 		memmove(&prev_argv[argv_index], &prev_argv[argv_index+1],
84 				sizeof(char**) * (prev_argc - argv_index - 1));
85 		prev_argv[prev_argc - 1] = tmp;
86 
87 		nonopt++;
88 		return 0;
89 	}
90 }
91 
92 
getopt(int argc,char ** argv,char * optstr)93 int getopt(int argc, char** argv, char* optstr)
94 {
95 	int c = 0;
96 
97 	/* If we have new argv, reinitialize */
98 	if(prev_argv != argv || prev_argc != argc)
99 	{
100 		/* Initialize variables */
101 		prev_argv = argv;
102 		prev_argc = argc;
103 		argv_index = 1;
104 		argv_index2 = 1;
105 		opt_offset = 1;
106 		dashdash = 0;
107 		nonopt = 0;
108 	}
109 
110 	/* Jump point in case we want to ignore the current argv_index */
111 	getopt_top:
112 
113 	/* Misc. initializations */
114 	optarg = NULL;
115 
116 	/* Dash-dash check */
117 	if(argv[argv_index] && !strcmp(argv[argv_index], "--"))
118 	{
119 		dashdash = 1;
120 		increment_index();
121 	}
122 
123 	/* If we're at the end of argv, that's it. */
124 	if(argv[argv_index] == NULL)
125 	{
126 		c = -1;
127 	}
128 	/* Are we looking at a string? Single dash is also a string */
129 	else if(dashdash || argv[argv_index][0] != '-' || !strcmp(argv[argv_index], "-"))
130 	{
131 		/* If we want a string... */
132 		if(optstr[0] == '-')
133 		{
134 			c = 1;
135 			optarg = argv[argv_index];
136 			increment_index();
137 		}
138 		/* If we really don't want it (we're in POSIX mode), we're done */
139 		else if(optstr[0] == '+' || getenv("POSIXLY_CORRECT"))
140 		{
141 			c = -1;
142 
143 			/* Everything else is a non-opt argument */
144 			nonopt = argc - argv_index;
145 		}
146 		/* If we mildly don't want it, then move it back */
147 		else
148 		{
149 			if(!permute_argv_once()) goto getopt_top;
150 			else c = -1;
151 		}
152 	}
153 	/* Otherwise we're looking at an option */
154 	else
155 	{
156 		char* opt_ptr = NULL;
157 
158 		/* Grab the option */
159 		c = argv[argv_index][opt_offset++];
160 
161 		/* Is the option in the optstr? */
162 		if(optstr[0] == '-') opt_ptr = strchr(optstr+1, c);
163 		else opt_ptr = strchr(optstr, c);
164 		/* Invalid argument */
165 		if(!opt_ptr)
166 		{
167 			if(opterr)
168 			{
169 				fprintf(stderr, "%s: invalid option -- %c\n", argv[0], c);
170 			}
171 
172 			optopt = c;
173 			c = '?';
174 
175 			/* Move onto the next option */
176 			increment_index();
177 		}
178 		/* Option takes argument */
179 		else if(opt_ptr[1] == ':')
180 		{
181 			/* ie, -oARGUMENT, -xxxoARGUMENT, etc. */
182 			if(argv[argv_index][opt_offset] != '\0')
183 			{
184 				optarg = &argv[argv_index][opt_offset];
185 				increment_index();
186 			}
187 			/* ie, -o ARGUMENT (only if it's a required argument) */
188 			else if(opt_ptr[2] != ':')
189 			{
190 				/* One of those "you're not expected to understand this" moment */
191 				if(argv_index2 < argv_index) argv_index2 = argv_index;
192 				while(argv[++argv_index2] && argv[argv_index2][0] == '-');
193 				optarg = argv[argv_index2];
194 
195 				/* Don't cross into the non-option argument list */
196 				if(argv_index2 + nonopt >= prev_argc) optarg = NULL;
197 
198 				/* Move onto the next option */
199 				increment_index();
200 			}
201 			else
202 			{
203 				/* Move onto the next option */
204 				increment_index();
205 			}
206 
207 			/* In case we got no argument for an option with required argument */
208 			if(optarg == NULL && opt_ptr[2] != ':')
209 			{
210 				optopt = c;
211 				c = '?';
212 
213 				if(opterr)
214 				{
215 					fprintf(stderr,"%s: option requires an argument -- %c\n",
216 							argv[0], optopt);
217 				}
218 			}
219 		}
220 		/* Option does not take argument */
221 		else
222 		{
223 			/* Next argv_index */
224 			if(argv[argv_index][opt_offset] == '\0')
225 			{
226 				increment_index();
227 			}
228 		}
229 	}
230 
231 	/* Calculate optind */
232 	if(c == -1)
233 	{
234 		optind = argc - nonopt;
235 	}
236 	else
237 	{
238 		optind = argv_index;
239 	}
240 
241 	return c;
242 }
243 
244 
245 /* vim:ts=3
246 */
247