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