| 1 | /*! @file SimpleOpt.h |
| 2 | |
| 3 | @version 2.8 |
| 4 | @note This is a modified version of SimpleOpt for OpenCity-0.0.5 |
| 5 | |
| 6 | @brief A cross-platform command line library which can parse almost any |
| 7 | of the standard command line formats in use today. It is designed explicitly |
| 8 | to be portable to any platform and has been tested on Windows and Linux. |
| 9 | See CSimpleOptTempl for the class definition. |
| 10 | |
| 11 | @section features FEATURES |
| 12 | |
| 13 | - MIT Licence allows free use in all software (including GPL and commercial) |
| 14 | - multi-platform (Windows 95/98/ME/NT/2K/XP, Linux, Unix) |
| 15 | - supports all lengths of option names: |
| 16 | <table width="60%"> |
| 17 | <tr><td width="30%"> - <td>switch character only (e.g. use stdin for input) |
| 18 | <tr><td> -o <td>short (single character) |
| 19 | <tr><td> -long <td>long (multiple character, single switch character) |
| 20 | <tr><td> --longer <td>long (multiple character, multiple switch characters) |
| 21 | </table> |
| 22 | - supports all types of arguments for options: |
| 23 | <table width="60%"> |
| 24 | <tr><td width="30%"> --option <td>short/long option flag (no argument) |
| 25 | <tr><td> --option ARG <td>short/long option with separate required argument |
| 26 | <tr><td> --option=ARG <td>short/long option with combined required argument |
| 27 | <tr><td> --option[=ARG] <td>short/long option with combined optional argument |
| 28 | <tr><td> -oARG <td>short option with combined required argument |
| 29 | <tr><td> -o[ARG] <td>short option with combined optional argument |
| 30 | </table> |
| 31 | - supports options with multiple or variable numbers of arguments: |
| 32 | <table width="60%"> |
| 33 | <tr><td width="30%"> --multi ARG1 ARG2 <td>Multiple arguments |
| 34 | <tr><td> --multi N ARG-1 ARG-2 ... ARG-N <td>Variable number of arguments |
| 35 | </table> |
| 36 | - supports options which do not use a switch character. i.e. a special word |
| 37 | which is construed as an option. e.g. "foo.exe open /directory/file.txt" |
| 38 | supports clumping of multiple short options (no arguments) in a string, e.g. |
| 39 | "foo.exe -abcdef file1" <==> "foo.exe -a -b -c -d -e -f file1" |
| 40 | - automatic recognition of a single slash as equivalent to a single hyphen |
| 41 | on Windows, e.g. "/f FILE" is equivalent to "-f FILE". |
| 42 | - file arguments can appear anywhere in the argument list: |
| 43 | "foo.exe file1.txt -a ARG file2.txt --flag file3.txt file4.txt" |
| 44 | files will be returned to the application in the same order they were supplied |
| 45 | on the command line |
| 46 | - short-circuit option matching: "--man" will match "--mandate" |
| 47 | invalid options can be handled while continuing to parse the command line |
| 48 | valid options list can be changed dynamically during command line processing, |
| 49 | i.e. accept different options depending on an option supplied earlier in the |
| 50 | command line. |
| 51 | - implemented with only a single C++ header file |
| 52 | - uses no C runtime or OS functions |
| 53 | - char, wchar_t and Windows TCHAR in the same program |
| 54 | - complete working examples included |
| 55 | - compiles cleanly at warning level 4 (Windows/VC.NET 2003), warning level |
| 56 | 3 (Windows/VC6) and -Wall (Linux/gcc) |
| 57 | |
| 58 | @section usage USAGE |
| 59 | |
| 60 | The SimpleOpt class is used by following these steps: |
| 61 | |
| 62 | <ol> |
| 63 | <li> Include the SimpleOpt.h header file |
| 64 | |
| 65 | <pre> |
| 66 | \#include "SimpleOpt.h" |
| 67 | </pre> |
| 68 | |
| 69 | <li> Define an array of valid options for your program. |
| 70 | |
| 71 | <pre> |
| 72 | @link CSimpleOptTempl::SOption CSimpleOpt::SOption @endlink g_rgOptions[] = { |
| 73 | { OPT_FLAG, _T("-a"), SO_NONE }, // "-a" |
| 74 | { OPT_FLAG, _T("-b"), SO_NONE }, // "-b" |
| 75 | { OPT_ARG, _T("-f"), SO_REQ_SEP }, // "-f ARG" |
| 76 | { OPT_HELP, _T("-?"), SO_NONE }, // "-?" |
| 77 | { OPT_HELP, _T("--help"), SO_NONE }, // "--help" |
| 78 | SO_END_OF_OPTIONS // END |
| 79 | }; |
| 80 | </pre> |
| 81 | |
| 82 | Note that all options must start with a hyphen even if the slash will |
| 83 | be accepted. This is because the slash character is automatically |
| 84 | converted into a hyphen to test against the list of options. For example, |
| 85 | the following line matches both "-?" and "/?" (on Windows). |
| 86 | |
| 87 | <pre> |
| 88 | { OPT_HELP, _T("-?"), SO_NONE }, // "-?" |
| 89 | </pre> |
| 90 | |
| 91 | <li> Instantiate a CSimpleOpt object supplying argc, argv and the option table |
| 92 | |
| 93 | <pre> |
| 94 | @link CSimpleOptTempl CSimpleOpt @endlink args(argc, argv, g_rgOptions); |
| 95 | </pre> |
| 96 | |
| 97 | <li> Process the arguments by calling Next() until it returns false. On each call, |
| 98 | first check for an error by calling LastError(), then either handle the error |
| 99 | or process the argument. |
| 100 | |
| 101 | <pre> |
| 102 | while (args.Next()) { |
| 103 | if (args.LastError() == SO_SUCCESS) { |
| 104 | handle option: use OptionId(), OptionText() and OptionArg() |
| 105 | } |
| 106 | else { |
| 107 | handle error: see ESOError enums |
| 108 | } |
| 109 | } |
| 110 | </pre> |
| 111 | |
| 112 | <li> Process all non-option arguments with File(), Files() and FileCount() |
| 113 | |
| 114 | <pre> |
| 115 | ShowFiles(args.FileCount(), args.Files()); |
| 116 | </pre> |
| 117 | |
| 118 | </ol> |
| 119 | |
| 120 | @section notes NOTES |
| 121 | |
| 122 | - In MBCS mode, this library is guaranteed to work correctly only when all |
| 123 | option names use only ASCII characters. |
| 124 | |
| 125 | @section licence MIT LICENCE |
| 126 | |
| 127 | The licence text below is the boilerplate "MIT Licence" used from: |
| 128 | http://www.opensource.org/licenses/mit-license.php |
| 129 | |
| 130 | Copyright (c) 2006-2007, Brodie Thiesfield |
| 131 | |
| 132 | Permission is hereby granted, free of charge, to any person obtaining a copy |
| 133 | of this software and associated documentation files (the "Software"), to deal |
| 134 | in the Software without restriction, including without limitation the rights |
| 135 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 136 | copies of the Software, and to permit persons to whom the Software is furnished |
| 137 | to do so, subject to the following conditions: |
| 138 | |
| 139 | The above copyright notice and this permission notice shall be included in |
| 140 | all copies or substantial portions of the Software. |
| 141 | |
| 142 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 143 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS |
| 144 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR |
| 145 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER |
| 146 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 147 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 148 | */ |
| 149 | |
| 150 | /*! @mainpage |
| 151 | |
| 152 | <table> |
| 153 | <tr><th>Library <td>SimpleOpt |
| 154 | <tr><th>Author <td>Brodie Thiesfield [code at jellycan dot com] |
| 155 | <tr><th>Source <td>http://code.jellycan.com/simpleopt/ |
| 156 | </table> |
| 157 | |
| 158 | @section SimpleOpt SimpleOpt |
| 159 | |
| 160 | A cross-platform library providing a simple method to parse almost any of the |
| 161 | standard command-line formats in use today. |
| 162 | |
| 163 | See the @link SimpleOpt.h SimpleOpt @endlink documentation for full details. |
| 164 | |
| 165 | @section SimpleGlob SimpleGlob |
| 166 | |
| 167 | A cross-platform file globbing library providing the ability to |
| 168 | expand wildcards in command-line arguments to a list of all matching files. |
| 169 | |
| 170 | See the @link SimpleGlob.h SimpleGlob @endlink documentation for full details. |
| 171 | */ |
| 172 | |
| 173 | #ifndef INCLUDED_SimpleOpt |
| 174 | #define INCLUDED_SimpleOpt |
| 175 | |
| 176 | |
| 177 | //! Error values |
| 178 | typedef enum _ESOError |
| 179 | { |
| 180 | SO_SUCCESS = 0, //!< No error |
| 181 | SO_OPT_INVALID = -1, /*!< It looks like an option (it starts with a switch character), |
| 182 | but it isn't registered in the option table. */ |
| 183 | SO_OPT_MULTIPLE = -2, /*!< Multiple options matched the supplied option text. |
| 184 | Only returned when NOT using SO_O_EXACT. */ |
| 185 | SO_ARG_INVALID = -3, /*!< Option doesn't take an argument, but a combined argument |
| 186 | was supplied. */ |
| 187 | SO_ARG_INVALID_TYPE = -4, /*!< SO_REQ_CMB style-argument was supplied to a SO_REQ_SEP option |
| 188 | Only returned when using SO_O_PEDANTIC. */ |
| 189 | SO_ARG_MISSING = -5, //!< Required argument was not supplied |
| 190 | SO_ARG_INVALID_DATA = -6 /*!< Option argument looks like another option. |
| 191 | Only returned when NOT using SO_O_NOERR. */ |
| 192 | } ESOError; |
| 193 | |
| 194 | //! Option flags |
| 195 | enum _ESOFlags |
| 196 | { |
| 197 | SO_O_EXACT = 0x0001, /*!< Disallow partial matching of option names */ |
| 198 | SO_O_NOSLASH = 0x0002, /*!< Disallow use of slash as an option marker on Windows. |
| 199 | Un*x only ever recognizes a hyphen. */ |
| 200 | SO_O_SHORTARG = 0x0004, /*!< Permit arguments on single letter options with |
| 201 | no equals sign. e.g. -oARG or -o[ARG] */ |
| 202 | SO_O_CLUMP = 0x0008, /*!< Permit single character options to be clumped into |
| 203 | a single option string. e.g. "-a -b -c" <==> "-abc" */ |
| 204 | SO_O_USEALL = 0x0010, /*!< Process the entire argv array for options, including |
| 205 | the argv[0] entry. */ |
| 206 | SO_O_NOERR = 0x0020, /*!< Do not generate an error for invalid options. errors |
| 207 | for missing arguments will still be generated. invalid |
| 208 | options will be treated as files. invalid options in |
| 209 | clumps will be silently ignored. */ |
| 210 | SO_O_PEDANTIC = 0x0040 /*!< Validate argument type pedantically. Return an error when |
| 211 | a separated argument "-opt arg" is supplied by the user |
| 212 | as a combined argument "-opt=arg". By default this is |
| 213 | not considered an error. */ |
| 214 | }; |
| 215 | |
| 216 | /*! Types of arguments that options may have. Note that some of the _ESOFlags are |
| 217 | not compatible with all argument types. SO_O_SHORTARG requires that relevant |
| 218 | options use either SO_REQ_CMB or SO_OPT. SO_O_CLUMP requires that relevant options |
| 219 | use only SO_NONE. |
| 220 | */ |
| 221 | typedef enum _ESOArgType { |
| 222 | SO_NONE, //!< No argument. -o --opt |
| 223 | SO_REQ_SEP, //!< Required separate argument. -o ARG --opt ARG |
| 224 | SO_REQ_CMB, //!< Required combined argument. -oARG -o=ARG --opt=ARG |
| 225 | SO_OPT, //!< Optional combined argument. -o[ARG] -o[=ARG] --opt[=ARG] |
| 226 | SO_MULTI //!< Multiple separate arguments. -o ARG1 ARG2 ... --opt ARG1 ARG2 ... |
| 227 | } ESOArgType; |
| 228 | |
| 229 | //! this option definition must be the last entry in the table |
| 230 | #define SO_END_OF_OPTIONS { -1, NULL, SO_NONE } |
| 231 | |
| 232 | #ifdef _DEBUG |
| 233 | # ifdef _WIN32 |
| 234 | # include <crtdbg.h> |
| 235 | # define SO_ASSERT(b) _ASSERTE(b) |
| 236 | # else |
| 237 | # include <assert.h> |
| 238 | # define SO_ASSERT(b) assert(b) |
| 239 | # endif |
| 240 | #else |
| 241 | # define SO_ASSERT(b) //!< assertion used to test input data |
| 242 | #endif |
| 243 | |
| 244 | // --------------------------------------------------------------------------- |
| 245 | // MAIN TEMPLATE CLASS |
| 246 | // --------------------------------------------------------------------------- |
| 247 | |
| 248 | /*! @brief Implementation of the SimpleOpt class */ |
| 249 | template<class SOCHAR> |
| 250 | class CSimpleOptTempl |
| 251 | { |
| 252 | public: |
| 253 | /*! @brief Structure used to define all known options. */ |
| 254 | struct SOption { |
| 255 | int nId; //!< ID to return for this flag. Optional but must be >= 0 |
| 256 | SOCHAR * pszArg; //!< arg string to search for, e.g. "open", "-", "-f", "--file" |
| 257 | // Note that on Windows the slash option marker will be converted |
| 258 | // to a hyphen so that "-f" will also match "/f". |
| 259 | ESOArgType nArgType; //!< type of argument accepted by this option |
| 260 | }; |
| 261 | |
| 262 | /*! @brief Initialize the class. Init() must be called later. */ |
| 263 | CSimpleOptTempl() { Init(0, NULL, NULL, 0); } |
| 264 | |
| 265 | /*! @brief Initialize the class in preparation for use. */ |
| 266 | CSimpleOptTempl(int argc, SOCHAR * argv[], const SOption * a_rgOptions, int a_nFlags = 0) { |
| 267 | Init(argc, argv, a_rgOptions, a_nFlags); |
| 268 | } |
| 269 | |
| 270 | /*! @brief Initialize the class in preparation for calling Next. |
| 271 | |
| 272 | The table of options pointed to by a_rgOptions does not need to be valid |
| 273 | at the time that Init() is called. However on every call to Next() the |
| 274 | table pointed to must be a valid options table with the last valid |
| 275 | entry set to SO_END_OF_OPTIONS. |
| 276 | |
| 277 | NOTE: the array pointed to by a_argv will be modified by this |
| 278 | class and must not be used or modified outside of member calls to |
| 279 | this class. |
| 280 | |
| 281 | @param a_argc Argument array size |
| 282 | @param a_argv Argument array |
| 283 | @param a_rgOptions Valid option array |
| 284 | @param a_nFlags Optional flags to modify the processing of the arguments |
| 285 | */ |
| 286 | void Init(int a_argc, SOCHAR * a_argv[], const SOption * a_rgOptions, int a_nFlags = 0); |
| 287 | |
| 288 | /*! @brief Change the current options table during option parsing. |
| 289 | |
| 290 | @param a_rgOptions Valid option array |
| 291 | */ |
| 292 | inline void SetOptions(const SOption * a_rgOptions) { m_rgOptions = a_rgOptions; } |
| 293 | |
| 294 | /*! @brief Change the current flags during option parsing. |
| 295 | |
| 296 | Note that changing the SO_O_USEALL flag here will have no affect. |
| 297 | It must be set using Init() or the constructor. |
| 298 | |
| 299 | @param a_nFlags Flags to modify the processing of the arguments |
| 300 | */ |
| 301 | inline void SetFlags(int a_nFlags) { m_nFlags = a_nFlags; } |
| 302 | |
| 303 | /*! @brief Query if a particular flag is set */ |
| 304 | inline bool HasFlag(int a_nFlag) const { return (m_nFlags & a_nFlag) == a_nFlag; } |
| 305 | |
| 306 | /*! @brief Advance to the next option if available. |
| 307 | |
| 308 | When all options have been processed it will return false. When true has been |
| 309 | returned, you must check for an invalid or unrecognized option using the |
| 310 | LastError() method. This will be return an error value other than SO_SUCCESS |
| 311 | on an error. All standard data (e.g. OptionText(), OptionArg(), OptionId(), etc) |
| 312 | will be available depending on the error. |
| 313 | |
| 314 | After all options have been processed, the remaining files from the |
| 315 | command line can be processed in same order as they were passed to |
| 316 | the program. |
| 317 | |
| 318 | @return true option or error available for processing |
| 319 | @return false all options have been processed |
| 320 | */ |
| 321 | bool Next(); |
| 322 | |
| 323 | /*! @brief Return the last error that occurred. |
| 324 | |
| 325 | This function must always be called before processing the current option. |
| 326 | This function is available only when Next() has returned true. |
| 327 | */ |
| 328 | inline ESOError LastError() const { return m_nLastError; } |
| 329 | |
| 330 | /*! @brief Return the nId value from the options array for the current option. |
| 331 | |
| 332 | This function is available only when Next() has returned true. |
| 333 | */ |
| 334 | inline int OptionId() const { return m_nOptionId; } |
| 335 | |
| 336 | /*! @brief Return the pszArg from the options array for the current option. |
| 337 | |
| 338 | This function is available only when Next() has returned true. |
| 339 | */ |
| 340 | inline SOCHAR * OptionText() const { return m_pszOptionText; } |
| 341 | |
| 342 | /*! @brief Return the argument for the current option where one exists. |
| 343 | |
| 344 | If there is no argument for the option, this will return NULL. |
| 345 | This function is available only when Next() has returned true. |
| 346 | */ |
| 347 | inline SOCHAR * OptionArg() const { return m_pszOptionArg; } |
| 348 | |
| 349 | /*! @brief Validate and return the desired number of arguments. |
| 350 | |
| 351 | This is only valid when OptionId() has return the ID of an option |
| 352 | that is registered as SO_MULTI. It may be called multiple times |
| 353 | each time returning the desired number of arguments. Previously |
| 354 | returned argument pointers are remain valid. |
| 355 | |
| 356 | If an error occurs during processing, NULL will be returned and |
| 357 | the error will be available via LastError(). |
| 358 | |
| 359 | @param n Number of arguments to return. |
| 360 | */ |
| 361 | SOCHAR ** MultiArg(int n); |
| 362 | |
| 363 | /*! @brief Returned the number of entries in the Files() array. |
| 364 | |
| 365 | After Next() has returned false, this will be the list of files (or |
| 366 | otherwise unprocessed arguments). |
| 367 | */ |
| 368 | inline int FileCount() const { return m_argc - m_nLastArg; } |
| 369 | |
| 370 | /*! @brief Return the specified file argument. |
| 371 | |
| 372 | @param n Index of the file to return. This must be between 0 |
| 373 | and FileCount() - 1; |
| 374 | */ |
| 375 | inline SOCHAR * File(int n) const { |
| 376 | SO_ASSERT(n >= 0 && n < FileCount()); |
| 377 | return m_argv[m_nLastArg + n]; |
| 378 | } |
| 379 | |
| 380 | /*! @brief Return the array of files. */ |
| 381 | inline SOCHAR ** Files() const { return &m_argv[m_nLastArg]; } |
| 382 | |
| 383 | private: |
| 384 | SOCHAR PrepareArg(SOCHAR * a_pszString) const; |
| 385 | bool NextClumped(); |
| 386 | void ShuffleArg(int a_nStartIdx, int a_nCount); |
| 387 | int LookupOption(const SOCHAR * a_pszOption) const; |
| 388 | int CalcMatch(const SOCHAR *a_pszSource, const SOCHAR *a_pszTest) const; |
| 389 | |
| 390 | // Find the '=' character within a string. |
| 391 | inline SOCHAR * FindEquals(SOCHAR *s) const { |
| 392 | while (*s && *s != (SOCHAR)'=') ++s; |
| 393 | return *s ? s : NULL; |
| 394 | } |
| 395 | |
| 396 | private: |
| 397 | const SOption * m_rgOptions; // pointer to options table as passed in to soInit() |
| 398 | int m_nFlags; // flags for parsing the command line |
| 399 | int m_nOptionIdx; // index of the current option in argv |
| 400 | int m_nOptionId; // id of the current option (or -1 if invalid option) |
| 401 | int m_nNextOption; // index of the next option to be processed |
| 402 | int m_nLastArg; // last unprocessed argument, after this are files |
| 403 | int m_argc; // argc to process |
| 404 | SOCHAR ** m_argv; // argv (rearranged during processing) |
| 405 | SOCHAR * m_pszOptionText; // text of the current option, e.g. "-f" or "--file" |
| 406 | SOCHAR * m_pszOptionArg; // argument for the current option, e.g. "c:\blah.txt" (or NULL if no argument) |
| 407 | SOCHAR * m_pszClump; // processing of clumped single character options |
| 408 | SOCHAR m_szShort[3]; // extract short option text from clumps and combined arguments |
| 409 | ESOError m_nLastError; // error status from the last call |
| 410 | }; |
| 411 | |
| 412 | // --------------------------------------------------------------------------- |
| 413 | // IMPLEMENTATION |
| 414 | // --------------------------------------------------------------------------- |
| 415 | |
| 416 | template<class SOCHAR> |
| 417 | void |
| 418 | CSimpleOptTempl<SOCHAR>::Init( |
| 419 | int a_argc, |
| 420 | SOCHAR * a_argv[], |
| 421 | const SOption * a_rgOptions, |
| 422 | int a_nFlags |
| 423 | ) |
| 424 | { |
| 425 | m_argc = a_argc; |
| 426 | m_nLastArg = a_argc; |
| 427 | m_argv = a_argv; |
| 428 | m_rgOptions = a_rgOptions; |
| 429 | m_nLastError = SO_SUCCESS; |
| 430 | m_nOptionIdx = 0; |
| 431 | m_nOptionId = -1; |
| 432 | m_pszOptionText = NULL; |
| 433 | m_pszOptionArg = NULL; |
| 434 | m_nNextOption = (a_nFlags & SO_O_USEALL) ? 0 : 1; |
| 435 | m_szShort[0] = (SOCHAR)'-'; |
| 436 | m_szShort[2] = (SOCHAR)'\0'; |
| 437 | m_nFlags = a_nFlags; |
| 438 | m_pszClump = NULL; |
| 439 | } |
| 440 | |
| 441 | template<class SOCHAR> |
| 442 | bool |
| 443 | CSimpleOptTempl<SOCHAR>::Next() |
| 444 | { |
| 445 | // process a clumped option string if appropriate |
| 446 | if (m_pszClump && *m_pszClump) { |
| 447 | // silently discard invalid clumped option |
| 448 | bool bIsValid = NextClumped(); |
| 449 | while (*m_pszClump && !bIsValid && HasFlag(SO_O_NOERR)) { |
| 450 | bIsValid = NextClumped(); |
| 451 | } |
| 452 | |
| 453 | // return this option if valid or we are returning errors |
| 454 | if (bIsValid || !HasFlag(SO_O_NOERR)) { |
| 455 | return true; |
| 456 | } |
| 457 | } |
| 458 | SO_ASSERT(!m_pszClump || !*m_pszClump); |
| 459 | m_pszClump = NULL; |
| 460 | |
| 461 | // init for the next option |
| 462 | m_nOptionIdx = m_nNextOption; |
| 463 | m_nOptionId = -1; |
| 464 | m_pszOptionText = NULL; |
| 465 | m_pszOptionArg = NULL; |
| 466 | m_nLastError = SO_SUCCESS; |
| 467 | |
| 468 | // find the next option |
| 469 | SOCHAR cFirst; |
| 470 | int nTableIdx = -1; |
| 471 | int nOptIdx = m_nOptionIdx; |
| 472 | while (nTableIdx < 0 && nOptIdx < m_nLastArg) { |
| 473 | // assumed argument |
| 474 | m_pszOptionText = m_argv[nOptIdx]; |
| 475 | m_pszOptionArg = NULL; |
| 476 | |
| 477 | // find this option in the options table |
| 478 | cFirst = PrepareArg(m_pszOptionText); |
| 479 | if (m_pszOptionText[0] == (SOCHAR)'-') { |
| 480 | // find any combined argument string and remove equals sign |
| 481 | m_pszOptionArg = FindEquals(m_pszOptionText); |
| 482 | if (m_pszOptionArg) { |
| 483 | *m_pszOptionArg++ = (SOCHAR)'\0'; |
| 484 | } |
| 485 | } |
| 486 | nTableIdx = LookupOption(m_pszOptionText); |
| 487 | |
| 488 | // if we didn't find this option but if it is a short form |
| 489 | // option then we try the alternative forms |
| 490 | if (nTableIdx < 0 |
| 491 | && !m_pszOptionArg |
| 492 | && m_pszOptionText[0] == (SOCHAR)'-' |
| 493 | && m_pszOptionText[1] |
| 494 | && m_pszOptionText[1] != (SOCHAR)'-' |
| 495 | && m_pszOptionText[2]) |
| 496 | { |
| 497 | // test for a short-form with argument if appropriate |
| 498 | if (HasFlag(SO_O_SHORTARG)) { |
| 499 | m_szShort[1] = m_pszOptionText[1]; |
| 500 | int nIdx = LookupOption(m_szShort); |
| 501 | if (nIdx >= 0 |
| 502 | && (m_rgOptions[nIdx].nArgType == SO_REQ_CMB |
| 503 | || m_rgOptions[nIdx].nArgType == SO_OPT)) |
| 504 | { |
| 505 | m_pszOptionArg = &m_pszOptionText[2]; |
| 506 | m_pszOptionText = m_szShort; |
| 507 | nTableIdx = nIdx; |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | // test for a clumped short-form option string and we didn't |
| 512 | // match on the short-form argument above |
| 513 | if (nTableIdx < 0 && HasFlag(SO_O_CLUMP)) { |
| 514 | m_pszClump = &m_pszOptionText[1]; |
| 515 | ++m_nNextOption; |
| 516 | if (nOptIdx > m_nOptionIdx) { |
| 517 | ShuffleArg(m_nOptionIdx, nOptIdx - m_nOptionIdx); |
| 518 | } |
| 519 | return Next(); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | // The option wasn't found. If it starts with a switch character |
| 524 | // and we are not suppressing errors for invalid options then it |
| 525 | // is reported as an error, otherwise it is data. |
| 526 | if (nTableIdx < 0) { |
| 527 | if (!HasFlag(SO_O_NOERR) && m_pszOptionText[0] == (SOCHAR)'-') { |
| 528 | break; |
| 529 | } |
| 530 | m_pszOptionText[0] = cFirst; |
| 531 | ++nOptIdx; |
| 532 | if (m_pszOptionArg) { |
| 533 | *(--m_pszOptionArg) = (SOCHAR)'='; |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | // end of options |
| 539 | if (nOptIdx >= m_nLastArg) { |
| 540 | if (nOptIdx > m_nOptionIdx) { |
| 541 | ShuffleArg(m_nOptionIdx, nOptIdx - m_nOptionIdx); |
| 542 | } |
| 543 | return false; |
| 544 | } |
| 545 | ++m_nNextOption; |
| 546 | |
| 547 | // get the option id |
| 548 | ESOArgType nArgType = SO_NONE; |
| 549 | if (nTableIdx < 0) { |
| 550 | m_nLastError = (ESOError) nTableIdx; // error code |
| 551 | } |
| 552 | else { |
| 553 | m_nOptionId = m_rgOptions[nTableIdx].nId; |
| 554 | m_pszOptionText = m_rgOptions[nTableIdx].pszArg; |
| 555 | |
| 556 | // ensure that the arg type is valid |
| 557 | nArgType = m_rgOptions[nTableIdx].nArgType; |
| 558 | switch (nArgType) { |
| 559 | case SO_NONE: |
| 560 | if (m_pszOptionArg) { |
| 561 | m_nLastError = SO_ARG_INVALID; |
| 562 | } |
| 563 | break; |
| 564 | |
| 565 | case SO_REQ_SEP: |
| 566 | if (m_pszOptionArg) { |
| 567 | // they wanted separate args, but we got a combined one, unless |
| 568 | // we are being pedantic about things, just accept it. |
| 569 | if (HasFlag(SO_O_PEDANTIC)) { |
| 570 | m_nLastError = SO_ARG_INVALID_TYPE; |
| 571 | } |
| 572 | } |
| 573 | // more processing after we shuffle |
| 574 | break; |
| 575 | |
| 576 | case SO_REQ_CMB: |
| 577 | if (!m_pszOptionArg) { |
| 578 | m_nLastError = SO_ARG_MISSING; |
| 579 | } |
| 580 | break; |
| 581 | |
| 582 | case SO_OPT: |
| 583 | // nothing to do |
| 584 | break; |
| 585 | |
| 586 | case SO_MULTI: |
| 587 | // nothing to do. Caller must now check for valid arguments |
| 588 | // using GetMultiArg() |
| 589 | break; |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | // shuffle the files out of the way |
| 594 | if (nOptIdx > m_nOptionIdx) { |
| 595 | ShuffleArg(m_nOptionIdx, nOptIdx - m_nOptionIdx); |
| 596 | } |
| 597 | |
| 598 | // we need to return the separate arg if required, just re-use the |
| 599 | // multi-arg code because it all does the same thing |
| 600 | if (nArgType == SO_REQ_SEP && !m_pszOptionArg && m_nLastError == SO_SUCCESS) { |
| 601 | SOCHAR ** ppArgs = MultiArg(1); |
| 602 | if (ppArgs) { |
| 603 | m_pszOptionArg = *ppArgs; |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | return true; |
| 608 | } |
| 609 | |
| 610 | template<class SOCHAR> |
| 611 | SOCHAR |
| 612 | CSimpleOptTempl<SOCHAR>::PrepareArg( |
| 613 | SOCHAR * a_pszString |
| 614 | ) const |
| 615 | { |
| 616 | #ifdef _WIN32 |
| 617 | // On Windows we can accept the forward slash as a single character |
| 618 | // option delimiter, but it cannot replace the '-' option used to |
| 619 | // denote stdin. On Un*x paths may start with slash so it may not |
| 620 | // be used to start an option. |
| 621 | if (!HasFlag(SO_O_NOSLASH) |
| 622 | && a_pszString[0] == (SOCHAR)'/' |
| 623 | && a_pszString[1] |
| 624 | && a_pszString[1] != (SOCHAR)'-') |
| 625 | { |
| 626 | a_pszString[0] = (SOCHAR)'-'; |
| 627 | return (SOCHAR)'/'; |
| 628 | } |
| 629 | #endif |
| 630 | return a_pszString[0]; |
| 631 | } |
| 632 | |
| 633 | template<class SOCHAR> |
| 634 | bool |
| 635 | CSimpleOptTempl<SOCHAR>::NextClumped() |
| 636 | { |
| 637 | // prepare for the next clumped option |
| 638 | m_szShort[1] = *m_pszClump++; |
| 639 | m_nOptionId = -1; |
| 640 | m_pszOptionText = m_szShort; |
| 641 | m_pszOptionArg = NULL; |
| 642 | m_nLastError = SO_SUCCESS; |
| 643 | |
| 644 | // lookup this option, ensure that we are using exact matching |
| 645 | int nSavedFlags = m_nFlags; |
| 646 | m_nFlags = SO_O_EXACT; |
| 647 | int nTableIdx = LookupOption(m_pszOptionText); |
| 648 | m_nFlags = nSavedFlags; |
| 649 | |
| 650 | // unknown option |
| 651 | if (nTableIdx < 0) { |
| 652 | m_nLastError = (ESOError) nTableIdx; // error code |
| 653 | return false; |
| 654 | } |
| 655 | |
| 656 | // valid option |
| 657 | ESOArgType nArgType = m_rgOptions[nTableIdx].nArgType; |
| 658 | if (nArgType == SO_NONE) { |
| 659 | m_nOptionId = m_rgOptions[nTableIdx].nId; |
| 660 | return true; |
| 661 | } |
| 662 | |
| 663 | if (nArgType == SO_REQ_CMB && *m_pszClump) { |
| 664 | m_nOptionId = m_rgOptions[nTableIdx].nId; |
| 665 | m_pszOptionArg = m_pszClump; |
| 666 | while (*m_pszClump) ++m_pszClump; // must point to an empty string |
| 667 | return true; |
| 668 | } |
| 669 | |
| 670 | // invalid option as it requires an argument |
| 671 | m_nLastError = SO_ARG_MISSING; |
| 672 | return true; |
| 673 | } |
| 674 | |
| 675 | // Shuffle arguments to the end of the argv array. |
| 676 | // |
| 677 | // For example: |
| 678 | // argv[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8" }; |
| 679 | // |
| 680 | // ShuffleArg(1, 1) = { "0", "2", "3", "4", "5", "6", "7", "8", "1" }; |
| 681 | // ShuffleArg(5, 2) = { "0", "1", "2", "3", "4", "7", "8", "5", "6" }; |
| 682 | // ShuffleArg(2, 4) = { "0", "1", "6", "7", "8", "2", "3", "4", "5" }; |
| 683 | template<class SOCHAR> |
| 684 | void |
| 685 | CSimpleOptTempl<SOCHAR>::ShuffleArg( |
| 686 | int a_nStartIdx, |
| 687 | int a_nCount |
| 688 | ) |
| 689 | { |
| 690 | SOCHAR * buf[200]; |
| 691 | int n, nSrc, nDst; |
| 692 | int nTail = m_argc - a_nStartIdx - a_nCount; |
| 693 | |
| 694 | // make a copy of the elements to be moved |
| 695 | nSrc = a_nStartIdx; |
| 696 | nDst = 0; |
| 697 | while (nDst < a_nCount) { |
| 698 | buf[nDst++] = m_argv[nSrc++]; |
| 699 | } |
| 700 | |
| 701 | // move the tail down |
| 702 | nSrc = a_nStartIdx + a_nCount; |
| 703 | nDst = a_nStartIdx; |
| 704 | for (n = 0; n < nTail; ++n) { |
| 705 | m_argv[nDst++] = m_argv[nSrc++]; |
| 706 | } |
| 707 | |
| 708 | // append the moved elements to the tail |
| 709 | nSrc = 0; |
| 710 | nDst = a_nStartIdx + nTail; |
| 711 | for (n = 0; n < a_nCount; ++n) { |
| 712 | m_argv[nDst++] = buf[nSrc++]; |
| 713 | } |
| 714 | |
| 715 | // update the index of the last unshuffled arg |
| 716 | m_nLastArg -= a_nCount; |
| 717 | } |
| 718 | |
| 719 | // match on the long format strings. partial matches will be |
| 720 | // accepted only if that feature is enabled. |
| 721 | template<class SOCHAR> |
| 722 | int |
| 723 | CSimpleOptTempl<SOCHAR>::LookupOption( |
| 724 | const SOCHAR * a_pszOption |
| 725 | ) const |
| 726 | { |
| 727 | int nBestMatch = -1; // index of best match so far |
| 728 | int nBestMatchLen = 0; // matching characters of best match |
| 729 | int nLastMatchLen = 0; // matching characters of last best match |
| 730 | |
| 731 | for (int n = 0; m_rgOptions[n].nId >= 0; ++n) { |
| 732 | // the option table must use hyphens as the option character, |
| 733 | // the slash character is converted to a hyphen for testing. |
| 734 | SO_ASSERT(m_rgOptions[n].pszArg[0] != (SOCHAR)'/'); |
| 735 | |
| 736 | int nMatchLen = CalcMatch(m_rgOptions[n].pszArg, a_pszOption); |
| 737 | if (nMatchLen == -1) { |
| 738 | return n; |
| 739 | } |
| 740 | if (nMatchLen > 0 && nMatchLen >= nBestMatchLen) { |
| 741 | nLastMatchLen = nBestMatchLen; |
| 742 | nBestMatchLen = nMatchLen; |
| 743 | nBestMatch = n; |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | // only partial matches or no match gets to here, ensure that we |
| 748 | // don't return a partial match unless it is a clear winner |
| 749 | if (HasFlag(SO_O_EXACT) || nBestMatch == -1) { |
| 750 | return SO_OPT_INVALID; |
| 751 | } |
| 752 | return (nBestMatchLen > nLastMatchLen) ? nBestMatch : SO_OPT_MULTIPLE; |
| 753 | } |
| 754 | |
| 755 | // calculate the number of characters that match (case-sensitive) |
| 756 | // 0 = no match, > 0 == number of characters, -1 == perfect match |
| 757 | template<class SOCHAR> |
| 758 | int |
| 759 | CSimpleOptTempl<SOCHAR>::CalcMatch( |
| 760 | const SOCHAR * a_pszSource, |
| 761 | const SOCHAR * a_pszTest |
| 762 | ) const |
| 763 | { |
| 764 | if (!a_pszSource || !a_pszTest) { |
| 765 | return 0; |
| 766 | } |
| 767 | |
| 768 | // match and skip leading hyphens |
| 769 | while (*a_pszSource == (SOCHAR)'-' && *a_pszSource == *a_pszTest) { |
| 770 | ++a_pszSource; ++a_pszTest; |
| 771 | } |
| 772 | if (*a_pszSource == (SOCHAR)'-' || *a_pszTest == (SOCHAR)'-') { |
| 773 | return 0; |
| 774 | } |
| 775 | |
| 776 | // find matching number of characters in the strings |
| 777 | int nLen = 0; |
| 778 | while (*a_pszSource && *a_pszSource == *a_pszTest) { |
| 779 | ++a_pszSource; ++a_pszTest; ++nLen; |
| 780 | } |
| 781 | |
| 782 | // if we have exhausted the source... |
| 783 | if (!*a_pszSource) { |
| 784 | // and the test strings, then it's a perfect match |
| 785 | if (!*a_pszTest) { |
| 786 | return -1; |
| 787 | } |
| 788 | |
| 789 | // otherwise the match failed as the test is longer than |
| 790 | // the source. i.e. "--mant" will not match the option "--man". |
| 791 | return 0; |
| 792 | } |
| 793 | |
| 794 | // if we haven't exhausted the test string then it is not a match |
| 795 | // i.e. "--mantle" will not best-fit match to "--mandate" at all. |
| 796 | if (*a_pszTest) { |
| 797 | return 0; |
| 798 | } |
| 799 | |
| 800 | // partial match to the current length of the test string |
| 801 | return nLen; |
| 802 | } |
| 803 | |
| 804 | // calculate the number of characters that match (case-sensitive) |
| 805 | // 0 = no match, > 0 == number of characters, -1 == perfect match |
| 806 | template<class SOCHAR> |
| 807 | SOCHAR ** |
| 808 | CSimpleOptTempl<SOCHAR>::MultiArg( |
| 809 | int a_nCount |
| 810 | ) |
| 811 | { |
| 812 | // ensure we have enough arguments |
| 813 | if (m_nNextOption + a_nCount > m_nLastArg) { |
| 814 | m_nLastError = SO_ARG_MISSING; |
| 815 | return NULL; |
| 816 | } |
| 817 | |
| 818 | // our argument array |
| 819 | SOCHAR ** rgpszArg = &m_argv[m_nNextOption]; |
| 820 | |
| 821 | // Ensure that each of the following don't start with an switch character. |
| 822 | // Only make this check if we are returning errors for unknown arguments. |
| 823 | if (!HasFlag(SO_O_NOERR)) { |
| 824 | for (int n = 0; n < a_nCount; ++n) { |
| 825 | SOCHAR ch = PrepareArg(rgpszArg[n]); |
| 826 | if (rgpszArg[n][0] == (SOCHAR)'-') { |
| 827 | rgpszArg[n][0] = ch; |
| 828 | m_nLastError = SO_ARG_INVALID_DATA; |
| 829 | return NULL; |
| 830 | } |
| 831 | rgpszArg[n][0] = ch; |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | // all good |
| 836 | m_nNextOption += a_nCount; |
| 837 | return rgpszArg; |
| 838 | } |
| 839 | |
| 840 | |
| 841 | // --------------------------------------------------------------------------- |
| 842 | // TYPE DEFINITIONS |
| 843 | // --------------------------------------------------------------------------- |
| 844 | |
| 845 | typedef CSimpleOptTempl<char> CSimpleOptA; /*!< @brief ASCII/MBCS version of CSimpleOpt */ |
| 846 | typedef CSimpleOptTempl<wchar_t> CSimpleOptW; /*!< @brief wchar_t version of CSimpleOpt */ |
| 847 | #if defined(_UNICODE) |
| 848 | # define CSimpleOpt CSimpleOptW /*!< @brief TCHAR version dependent on if _UNICODE is defined */ |
| 849 | #else |
| 850 | # define CSimpleOpt CSimpleOptA /*!< @brief TCHAR version dependent on if _UNICODE is defined */ |
| 851 | #endif |
| 852 | |
| 853 | #endif // INCLUDED_SimpleOpt |