(svn r27950) -Merge: Documentation updates from 1.7 branch
[openttd.git] / src / misc / getoptdata.cpp
blob7859594dd91337aee2a87bb3f701e87f54e310f7
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file getoptdata.cpp Library for parsing command line options. */
12 #include "../stdafx.h"
13 #include "getoptdata.h"
15 #include "../safeguards.h"
17 /**
18 * Find the next option.
19 * @return Function returns one
20 * - An option letter if it found another option.
21 * - -1 if option processing is finished. Inspect #argv and #numleft to find the command line arguments.
22 * - -2 if an error was encountered.
24 int GetOptData::GetOpt()
26 const OptionData *odata;
28 char *s = this->cont;
29 if (s == NULL) {
30 if (this->numleft == 0) return -1; // No arguments left -> finished.
32 s = this->argv[0];
33 if (*s != '-') return -1; // No leading '-' -> not an option -> finished.
35 this->argv++;
36 this->numleft--;
38 /* Is it a long option? */
39 for (odata = this->options; odata->flags != ODF_END; odata++) {
40 if (odata->longname != NULL && !strcmp(odata->longname, s)) { // Long options always use the entire argument.
41 this->cont = NULL;
42 goto set_optval;
46 s++; // Skip leading '-'.
49 /* Is it a short option? */
50 for (odata = this->options; odata->flags != ODF_END; odata++) {
51 if (odata->shortname != '\0' && *s == odata->shortname) {
52 this->cont = (s[1] != '\0') ? s + 1 : NULL;
54 set_optval: // Handle option value of *odata .
55 this->opt = NULL;
56 switch (odata->flags) {
57 case ODF_NO_VALUE:
58 return odata->id;
60 case ODF_HAS_VALUE:
61 case ODF_OPTIONAL_VALUE:
62 if (this->cont != NULL) { // Remainder of the argument is the option value.
63 this->opt = this->cont;
64 this->cont = NULL;
65 return odata->id;
67 /* No more arguments, either return an error or a value-less option. */
68 if (this->numleft == 0) return (odata->flags == ODF_HAS_VALUE) ? -2 : odata->id;
70 /* Next argument looks like another option, let's not return it as option value. */
71 if (odata->flags == ODF_OPTIONAL_VALUE && this->argv[0][0] == '-') return odata->id;
73 this->opt = this->argv[0]; // Next argument is the option value.
74 this->argv++;
75 this->numleft--;
76 return odata->id;
78 default: NOT_REACHED();
83 return -2; // No other ways to interpret the text -> error.