/include/SimpleOpt.h

http://github.com/digego/extempore · C Header · 1060 lines · 503 code · 114 blank · 443 comment · 118 complexity · 626789bc9b024987a05327c8e6b3f307 MD5 · raw file

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