Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ezOptionParser.hpp 68KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  1. /*
  2. This file is part of ezOptionParser. See MIT-LICENSE.
  3. Copyright (C) 2011,2012,2014 Remik Ziemlinski <first d0t surname att gmail>
  4. CHANGELOG
  5. v0.0.0 20110505 rsz Created.
  6. v0.1.0 20111006 rsz Added validator.
  7. v0.1.1 20111012 rsz Fixed validation of ulonglong.
  8. v0.1.2 20111126 rsz Allow flag names start with alphanumeric (previously, flag had to start with alpha).
  9. v0.1.3 20120108 rsz Created work-around for unique id generation with IDGenerator that avoids retarded c++ translation unit linker errors with single-header static variables. Forced inline on all methods to please retard compiler and avoid multiple def errors.
  10. v0.1.4 20120629 Enforced MIT license on all files.
  11. v0.2.0 20121120 Added parseIndex to OptionGroup.
  12. v0.2.1 20130506 Allow disabling doublespace of OPTIONS usage descriptions.
  13. v0.2.2 20140504 Jose Santiago added compiler warning fixes.
  14. Bruce Shankle added a crash fix in description printing.
  15. */
  16. #ifndef EZ_OPTION_PARSER_H
  17. #define EZ_OPTION_PARSER_H
  18. #include <stdlib.h>
  19. #include <vector>
  20. #include <list>
  21. #include <map>
  22. #include <string>
  23. #include <iostream>
  24. #include <fstream>
  25. #include <algorithm>
  26. #include <limits>
  27. #include <sstream>
  28. #include <cstring>
  29. namespace ez {
  30. #define DEBUGLINE() printf("%s:%d\n", __FILE__, __LINE__);
  31. /* ################################################################### */
  32. template<typename T>
  33. static T fromString(const std::string* s) {
  34. std::istringstream stream (s->c_str());
  35. T t;
  36. stream >> t;
  37. return t;
  38. };
  39. template<typename T>
  40. static T fromString(const char* s) {
  41. std::istringstream stream (s);
  42. T t;
  43. stream >> t;
  44. return t;
  45. };
  46. /* ################################################################### */
  47. static inline bool isdigit(const std::string & s, int i=0) {
  48. int n = s.length();
  49. for(; i < n; ++i)
  50. switch(s[i]) {
  51. case '0': case '1': case '2':
  52. case '3': case '4': case '5':
  53. case '6': case '7': case '8': case '9': break;
  54. default: return false;
  55. }
  56. return true;
  57. };
  58. /* ################################################################### */
  59. static bool isdigit(const std::string * s, int i=0) {
  60. int n = s->length();
  61. for(; i < n; ++i)
  62. switch(s->at(i)) {
  63. case '0': case '1': case '2':
  64. case '3': case '4': case '5':
  65. case '6': case '7': case '8': case '9': break;
  66. default: return false;
  67. }
  68. return true;
  69. };
  70. /* ################################################################### */
  71. /*
  72. Compare strings for opts, so short opt flags come before long format flags.
  73. For example, -d < --dimension < --dmn, and also lower come before upper. The default STL std::string compare doesn't do that.
  74. */
  75. static bool CmpOptStringPtr(std::string * s1, std::string * s2) {
  76. int c1,c2;
  77. const char *s=s1->c_str();
  78. for(c1=0; c1 < (long int)s1->size(); ++c1)
  79. if (isalnum(s[c1])) // locale sensitive.
  80. break;
  81. s=s2->c_str();
  82. for(c2=0; c2 < (long int)s2->size(); ++c2)
  83. if (isalnum(s[c2]))
  84. break;
  85. // Test which has more symbols before its name.
  86. if (c1 > c2)
  87. return false;
  88. else if (c1 < c2)
  89. return true;
  90. // Both have same number of symbols, so compare first letter.
  91. char char1 = s1->at(c1);
  92. char char2 = s2->at(c2);
  93. char lo1 = tolower(char1);
  94. char lo2 = tolower(char2);
  95. if (lo1 != lo2)
  96. return lo1 < lo2;
  97. // Their case doesn't match, so find which is lower.
  98. char up1 = isupper(char1);
  99. char up2 = isupper(char2);
  100. if (up1 && !up2)
  101. return false;
  102. else if (!up1 && up2)
  103. return true;
  104. return (s1->compare(*s2)<0);
  105. };
  106. /* ################################################################### */
  107. /*
  108. Makes a vector of strings from one string,
  109. splitting at (and excluding) delimiter "token".
  110. */
  111. static void SplitDelim( const std::string& s, const char token, std::vector<std::string*> * result) {
  112. std::string::const_iterator i = s.begin();
  113. std::string::const_iterator j = s.begin();
  114. const std::string::const_iterator e = s.end();
  115. while(i!=e) {
  116. while(i!=e && *i++!=token);
  117. std::string *newstr = new std::string(j, i);
  118. if (newstr->at(newstr->size()-1) == token) newstr->erase(newstr->size()-1);
  119. result->push_back(newstr);
  120. j = i;
  121. }
  122. };
  123. /* ################################################################### */
  124. // Variant that uses deep copies and references instead of pointers (less efficient).
  125. static void SplitDelim( const std::string& s, const char token, std::vector<std::string> & result) {
  126. std::string::const_iterator i = s.begin();
  127. std::string::const_iterator j = s.begin();
  128. const std::string::const_iterator e = s.end();
  129. while(i!=e) {
  130. while(i!=e && *i++!=token);
  131. std::string newstr(j, i);
  132. if (newstr.at(newstr.size()-1) == token) newstr.erase(newstr.size()-1);
  133. result.push_back(newstr);
  134. j = i;
  135. }
  136. };
  137. /* ################################################################### */
  138. // Variant that uses list instead of vector for efficient insertion, etc.
  139. static void SplitDelim( const std::string& s, const char token, std::list<std::string*> & result) {
  140. std::string::const_iterator i = s.begin();
  141. std::string::const_iterator j = s.begin();
  142. const std::string::const_iterator e = s.end();
  143. while(i!=e) {
  144. while(i!=e && *i++!=token);
  145. std::string *newstr = new std::string(j, i);
  146. if (newstr->at(newstr->size()-1) == token) newstr->erase(newstr->size()-1);
  147. result.push_back(newstr);
  148. j = i;
  149. }
  150. };
  151. /* ################################################################### */
  152. static void ToU1(std::string ** strings, unsigned char * out, int n) {
  153. for(int i=0; i < n; ++i) {
  154. out[i] = (unsigned char)atoi(strings[i]->c_str());
  155. }
  156. };
  157. /* ################################################################### */
  158. static void ToS1(std::string ** strings, char * out, int n) {
  159. for(int i=0; i < n; ++i) {
  160. out[i] = (char)atoi(strings[i]->c_str());
  161. }
  162. };
  163. /* ################################################################### */
  164. static void ToU2(std::string ** strings, unsigned short * out, int n) {
  165. for(int i=0; i < n; ++i) {
  166. out[i] = (unsigned short)atoi(strings[i]->c_str());
  167. }
  168. };
  169. /* ################################################################### */
  170. static void ToS2(std::string ** strings, short * out, int n) {
  171. for(int i=0; i < n; ++i) {
  172. out[i] = (short)atoi(strings[i]->c_str());
  173. }
  174. };
  175. /* ################################################################### */
  176. static void ToS4(std::string ** strings, int * out, int n) {
  177. for(int i=0; i < n; ++i) {
  178. out[i] = atoi(strings[i]->c_str());
  179. }
  180. };
  181. /* ################################################################### */
  182. static void ToU4(std::string ** strings, unsigned int * out, int n) {
  183. for(int i=0; i < n; ++i) {
  184. out[i] = (unsigned int)strtoul(strings[i]->c_str(), NULL, 0);
  185. }
  186. };
  187. /* ################################################################### */
  188. static void ToS8(std::string ** strings, long long * out, int n) {
  189. for(int i=0; i < n; ++i) {
  190. std::stringstream ss(strings[i]->c_str());
  191. ss >> out[i];
  192. }
  193. };
  194. /* ################################################################### */
  195. static void ToU8(std::string ** strings, unsigned long long * out, int n) {
  196. for(int i=0; i < n; ++i) {
  197. std::stringstream ss(strings[i]->c_str());
  198. ss >> out[i];
  199. }
  200. };
  201. /* ################################################################### */
  202. static void ToF(std::string ** strings, float * out, int n) {
  203. for(int i=0; i < n; ++i) {
  204. out[i] = (float)atof(strings[i]->c_str());
  205. }
  206. };
  207. /* ################################################################### */
  208. static void ToD(std::string ** strings, double * out, int n) {
  209. for(int i=0; i < n; ++i) {
  210. out[i] = (double)atof(strings[i]->c_str());
  211. }
  212. };
  213. /* ################################################################### */
  214. static void StringsToInts(std::vector<std::string> & strings, std::vector<int> & out) {
  215. for(int i=0; i < (long int)strings.size(); ++i) {
  216. out.push_back(atoi(strings[i].c_str()));
  217. }
  218. };
  219. /* ################################################################### */
  220. static void StringsToInts(std::vector<std::string*> * strings, std::vector<int> * out) {
  221. for(int i=0; i < (long int)strings->size(); ++i) {
  222. out->push_back(atoi(strings->at(i)->c_str()));
  223. }
  224. };
  225. /* ################################################################### */
  226. static void StringsToLongs(std::vector<std::string> & strings, std::vector<long> & out) {
  227. for(int i=0; i < (long int)strings.size(); ++i) {
  228. out.push_back(atol(strings[i].c_str()));
  229. }
  230. };
  231. /* ################################################################### */
  232. static void StringsToLongs(std::vector<std::string*> * strings, std::vector<long> * out) {
  233. for(int i=0; i < (long int)strings->size(); ++i) {
  234. out->push_back(atol(strings->at(i)->c_str()));
  235. }
  236. };
  237. /* ################################################################### */
  238. static void StringsToULongs(std::vector<std::string> & strings, std::vector<unsigned long> & out) {
  239. for(int i=0; i < (long int)strings.size(); ++i) {
  240. out.push_back(strtoul(strings[i].c_str(),0,0));
  241. }
  242. };
  243. /* ################################################################### */
  244. static void StringsToULongs(std::vector<std::string*> * strings, std::vector<unsigned long> * out) {
  245. for(int i=0; i < (long int)strings->size(); ++i) {
  246. out->push_back(strtoul(strings->at(i)->c_str(),0,0));
  247. }
  248. };
  249. /* ################################################################### */
  250. static void StringsToFloats(std::vector<std::string> & strings, std::vector<float> & out) {
  251. for(int i=0; i < (long int)strings.size(); ++i) {
  252. out.push_back(atof(strings[i].c_str()));
  253. }
  254. };
  255. /* ################################################################### */
  256. static void StringsToFloats(std::vector<std::string*> * strings, std::vector<float> * out) {
  257. for(int i=0; i < (long int)strings->size(); ++i) {
  258. out->push_back(atof(strings->at(i)->c_str()));
  259. }
  260. };
  261. /* ################################################################### */
  262. static void StringsToDoubles(std::vector<std::string> & strings, std::vector<double> & out) {
  263. for(int i=0; i < (long int)strings.size(); ++i) {
  264. out.push_back(atof(strings[i].c_str()));
  265. }
  266. };
  267. /* ################################################################### */
  268. static void StringsToDoubles(std::vector<std::string*> * strings, std::vector<double> * out) {
  269. for(int i=0; i < (long int)strings->size(); ++i) {
  270. out->push_back(atof(strings->at(i)->c_str()));
  271. }
  272. };
  273. /* ################################################################### */
  274. static void StringsToStrings(std::vector<std::string*> * strings, std::vector<std::string> * out) {
  275. for(int i=0; i < (long int)strings->size(); ++i) {
  276. out->push_back( *strings->at(i) );
  277. }
  278. };
  279. /* ################################################################### */
  280. static void ToLowerASCII(std::string & s) {
  281. int n = s.size();
  282. int i=0;
  283. char c;
  284. for(; i < n; ++i) {
  285. c = s[i];
  286. if(c<='Z' && c>='A')
  287. s[i] = c+32;
  288. }
  289. }
  290. /* ################################################################### */
  291. static char** CommandLineToArgvA(char* CmdLine, int* _argc) {
  292. char** argv;
  293. char* _argv;
  294. unsigned long len;
  295. unsigned long argc;
  296. char a;
  297. unsigned long i, j;
  298. bool in_QM;
  299. bool in_TEXT;
  300. bool in_SPACE;
  301. len = strlen(CmdLine);
  302. i = ((len+2)/2)*sizeof(void*) + sizeof(void*);
  303. argv = (char**)malloc(i + (len+2)*sizeof(char));
  304. _argv = (char*)(((unsigned char*)argv)+i);
  305. argc = 0;
  306. argv[argc] = _argv;
  307. in_QM = false;
  308. in_TEXT = false;
  309. in_SPACE = true;
  310. i = 0;
  311. j = 0;
  312. while( (a = CmdLine[i]) ) {
  313. if(in_QM) {
  314. if( (a == '\"') ||
  315. (a == '\'')) // rsz. Added single quote.
  316. {
  317. in_QM = false;
  318. } else {
  319. _argv[j] = a;
  320. j++;
  321. }
  322. } else {
  323. switch(a) {
  324. case '\"':
  325. case '\'': // rsz. Added single quote.
  326. in_QM = true;
  327. in_TEXT = true;
  328. if(in_SPACE) {
  329. argv[argc] = _argv+j;
  330. argc++;
  331. }
  332. in_SPACE = false;
  333. break;
  334. case ' ':
  335. case '\t':
  336. case '\n':
  337. case '\r':
  338. if(in_TEXT) {
  339. _argv[j] = '\0';
  340. j++;
  341. }
  342. in_TEXT = false;
  343. in_SPACE = true;
  344. break;
  345. default:
  346. in_TEXT = true;
  347. if(in_SPACE) {
  348. argv[argc] = _argv+j;
  349. argc++;
  350. }
  351. _argv[j] = a;
  352. j++;
  353. in_SPACE = false;
  354. break;
  355. }
  356. }
  357. i++;
  358. }
  359. _argv[j] = '\0';
  360. argv[argc] = NULL;
  361. (*_argc) = argc;
  362. return argv;
  363. };
  364. /* ################################################################### */
  365. // Create unique ids with static and still allow single header that avoids multiple definitions linker error.
  366. class ezOptionParserIDGenerator {
  367. public:
  368. static ezOptionParserIDGenerator& instance () { static ezOptionParserIDGenerator Generator; return Generator; }
  369. short next () { return ++_id; }
  370. private:
  371. ezOptionParserIDGenerator() : _id(-1) {}
  372. short _id;
  373. };
  374. /* ################################################################### */
  375. /* Validate a value by checking:
  376. - if as string, see if converted value is within datatype's limits,
  377. - and see if falls within a desired range,
  378. - or see if within set of given list of values.
  379. If comparing with a range, the values list must contain one or two values. One value is required when comparing with <, <=, >, >=. Use two values when requiring a test such as <x<, <=x<, <x<=, <=x<=.
  380. A regcomp/regexec based class could be created in the future if a need arises.
  381. */
  382. class ezOptionValidator {
  383. public:
  384. inline ezOptionValidator(const char* _type, const char* _op=0, const char* list=0, bool _insensitive=false);
  385. inline ezOptionValidator(char _type);
  386. inline ezOptionValidator(char _type, char _op, const char* list, int _size);
  387. inline ezOptionValidator(char _type, char _op, const unsigned char* list, int _size);
  388. inline ezOptionValidator(char _type, char _op, const short* list, int _size);
  389. inline ezOptionValidator(char _type, char _op, const unsigned short* list, int _size);
  390. inline ezOptionValidator(char _type, char _op, const int* list, int _size);
  391. inline ezOptionValidator(char _type, char _op, const unsigned int* list, int _size);
  392. inline ezOptionValidator(char _type, char _op, const long long* list, int _size);
  393. inline ezOptionValidator(char _type, char _op, const unsigned long long* list, int _size=0);
  394. inline ezOptionValidator(char _type, char _op, const float* list, int _size);
  395. inline ezOptionValidator(char _type, char _op, const double* list, int _size);
  396. inline ezOptionValidator(char _type, char _op, const char** list, int _size, bool _insensitive);
  397. inline ~ezOptionValidator();
  398. inline bool isValid(const std::string * value);
  399. inline void print();
  400. inline void reset();
  401. /* If value must be in custom range, use these comparison modes. */
  402. enum OP { NOOP=0,
  403. LT, /* value < list[0] */
  404. LE, /* value <= list[0] */
  405. GT, /* value > list[0] */
  406. GE, /* value >= list[0] */
  407. GTLT, /* list[0] < value < list[1] */
  408. GELT, /* list[0] <= value < list[1] */
  409. GELE, /* list[0] <= value <= list[1] */
  410. GTLE, /* list[0] < value <= list[1] */
  411. IN /* if value is in list */
  412. };
  413. enum TYPE { NOTYPE=0, S1, U1, S2, U2, S4, U4, S8, U8, F, D, T };
  414. enum TYPE2 { NOTYPE2=0, INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, FLOAT, DOUBLE, TEXT };
  415. union {
  416. unsigned char *u1;
  417. char *s1;
  418. unsigned short *u2;
  419. short *s2;
  420. unsigned int *u4;
  421. int *s4;
  422. unsigned long long *u8;
  423. long long *s8;
  424. float *f;
  425. double *d;
  426. std::string** t;
  427. };
  428. char op;
  429. bool quiet;
  430. short id;
  431. char type;
  432. int size;
  433. bool insensitive;
  434. };
  435. /* ------------------------------------------------------------------- */
  436. ezOptionValidator::~ezOptionValidator() {
  437. reset();
  438. };
  439. /* ------------------------------------------------------------------- */
  440. void ezOptionValidator::reset() {
  441. #define CLEAR(TYPE,P) case TYPE: if (P) delete [] P; P = 0; break;
  442. switch(type) {
  443. CLEAR(S1,s1);
  444. CLEAR(U1,u1);
  445. CLEAR(S2,s2);
  446. CLEAR(U2,u2);
  447. CLEAR(S4,s4);
  448. CLEAR(U4,u4);
  449. CLEAR(S8,s8);
  450. CLEAR(U8,u8);
  451. CLEAR(F,f);
  452. CLEAR(D,d);
  453. case T:
  454. for(int i=0; i < size; ++i)
  455. delete t[i];
  456. delete [] t;
  457. t = 0;
  458. break;
  459. default: break;
  460. }
  461. size = 0;
  462. op = NOOP;
  463. type = NOTYPE;
  464. };
  465. /* ------------------------------------------------------------------- */
  466. ezOptionValidator::ezOptionValidator(char _type) : s1(0), op(0), quiet(0), type(_type), size(0), insensitive(0) {
  467. id = ezOptionParserIDGenerator::instance().next();
  468. };
  469. /* ------------------------------------------------------------------- */
  470. ezOptionValidator::ezOptionValidator(char _type, char _op, const char* list, int _size) : s1(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  471. id = ezOptionParserIDGenerator::instance().next();
  472. s1 = new char[size];
  473. memcpy(s1, list, size);
  474. };
  475. /* ------------------------------------------------------------------- */
  476. ezOptionValidator::ezOptionValidator(char _type, char _op, const unsigned char* list, int _size) : u1(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  477. id = ezOptionParserIDGenerator::instance().next();
  478. u1 = new unsigned char[size];
  479. memcpy(u1, list, size);
  480. };
  481. /* ------------------------------------------------------------------- */
  482. ezOptionValidator::ezOptionValidator(char _type, char _op, const short* list, int _size) : s2(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  483. id = ezOptionParserIDGenerator::instance().next();
  484. s2 = new short[size];
  485. memcpy(s2, list, size*sizeof(short));
  486. };
  487. /* ------------------------------------------------------------------- */
  488. ezOptionValidator::ezOptionValidator(char _type, char _op, const unsigned short* list, int _size) : u2(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  489. id = ezOptionParserIDGenerator::instance().next();
  490. u2 = new unsigned short[size];
  491. memcpy(u2, list, size*sizeof(unsigned short));
  492. };
  493. /* ------------------------------------------------------------------- */
  494. ezOptionValidator::ezOptionValidator(char _type, char _op, const int* list, int _size) : s4(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  495. id = ezOptionParserIDGenerator::instance().next();
  496. s4 = new int[size];
  497. memcpy(s4, list, size*sizeof(int));
  498. };
  499. /* ------------------------------------------------------------------- */
  500. ezOptionValidator::ezOptionValidator(char _type, char _op, const unsigned int* list, int _size) : u4(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  501. id = ezOptionParserIDGenerator::instance().next();
  502. u4 = new unsigned int[size];
  503. memcpy(u4, list, size*sizeof(unsigned int));
  504. };
  505. /* ------------------------------------------------------------------- */
  506. ezOptionValidator::ezOptionValidator(char _type, char _op, const long long* list, int _size) : s8(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  507. id = ezOptionParserIDGenerator::instance().next();
  508. s8 = new long long[size];
  509. memcpy(s8, list, size*sizeof(long long));
  510. };
  511. /* ------------------------------------------------------------------- */
  512. ezOptionValidator::ezOptionValidator(char _type, char _op, const unsigned long long* list, int _size) : u8(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  513. id = ezOptionParserIDGenerator::instance().next();
  514. u8 = new unsigned long long[size];
  515. memcpy(u8, list, size*sizeof(unsigned long long));
  516. };
  517. /* ------------------------------------------------------------------- */
  518. ezOptionValidator::ezOptionValidator(char _type, char _op, const float* list, int _size) : f(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  519. id = ezOptionParserIDGenerator::instance().next();
  520. f = new float[size];
  521. memcpy(f, list, size*sizeof(float));
  522. };
  523. /* ------------------------------------------------------------------- */
  524. ezOptionValidator::ezOptionValidator(char _type, char _op, const double* list, int _size) : d(0), op(_op), quiet(0), type(_type), size(_size), insensitive(0) {
  525. id = ezOptionParserIDGenerator::instance().next();
  526. d = new double[size];
  527. memcpy(d, list, size*sizeof(double));
  528. };
  529. /* ------------------------------------------------------------------- */
  530. ezOptionValidator::ezOptionValidator(char _type, char _op, const char** list, int _size, bool _insensitive) : t(0), op(_op), quiet(0), type(_type), size(_size), insensitive(_insensitive) {
  531. id = ezOptionParserIDGenerator::instance().next();
  532. t = new std::string*[size];
  533. int i=0;
  534. for(; i < size; ++i) {
  535. t[i] = new std::string(list[i]);
  536. }
  537. };
  538. /* ------------------------------------------------------------------- */
  539. /* Less efficient but convenient ctor that parses strings to setup validator.
  540. _type: s1, u1, s2, u2, ..., f, d, t
  541. _op: lt, gt, ..., in
  542. _list: comma-delimited string
  543. */
  544. ezOptionValidator::ezOptionValidator(const char* _type, const char* _op, const char* _list, bool _insensitive) : t(0), quiet(0), type(0), size(0), insensitive(_insensitive) {
  545. id = ezOptionParserIDGenerator::instance().next();
  546. switch(_type[0]) {
  547. case 'u':
  548. switch(_type[1]) {
  549. case '1': type = U1; break;
  550. case '2': type = U2; break;
  551. case '4': type = U4; break;
  552. case '8': type = U8; break;
  553. default: break;
  554. }
  555. break;
  556. case 's':
  557. switch(_type[1]) {
  558. case '1': type = S1;
  559. break;
  560. case '2': type = S2; break;
  561. case '4': type = S4; break;
  562. case '8': type = S8; break;
  563. default: break;
  564. }
  565. break;
  566. case 'f': type = F; break;
  567. case 'd': type = D; break;
  568. case 't': type = T; break;
  569. default:
  570. if (!quiet)
  571. std::cerr << "ERROR: Unknown validator datatype \"" << _type << "\".\n";
  572. break;
  573. }
  574. int nop = 0;
  575. if (_op != 0)
  576. nop = strlen(_op);
  577. switch(nop) {
  578. case 0: op = NOOP; break;
  579. case 2:
  580. switch(_op[0]) {
  581. case 'g':
  582. switch(_op[1]) {
  583. case 'e': op = GE; break;
  584. default: op = GT; break;
  585. }
  586. break;
  587. case 'i': op = IN;
  588. break;
  589. default:
  590. switch(_op[1]) {
  591. case 'e': op = LE; break;
  592. default: op = LT; break;
  593. }
  594. break;
  595. }
  596. break;
  597. case 4:
  598. switch(_op[1]) {
  599. case 'e':
  600. switch(_op[3]) {
  601. case 'e': op = GELE; break;
  602. default: op = GELT; break;
  603. }
  604. break;
  605. default:
  606. switch(_op[3]) {
  607. case 'e': op = GTLE; break;
  608. default: op = GTLT; break;
  609. }
  610. break;
  611. }
  612. break;
  613. default:
  614. if (!quiet)
  615. std::cerr << "ERROR: Unknown validator operation \"" << _op << "\".\n";
  616. break;
  617. }
  618. if (_list == 0) return;
  619. // Create list of strings and then cast to native datatypes.
  620. std::string unsplit(_list);
  621. std::list<std::string*> split;
  622. std::list<std::string*>::iterator it;
  623. SplitDelim(unsplit, ',', split);
  624. size = split.size();
  625. std::string **strings = new std::string*[size];
  626. int i = 0;
  627. for(it = split.begin(); it != split.end(); ++it)
  628. strings[i++] = *it;
  629. if (insensitive)
  630. for(i=0; i < size; ++i)
  631. ToLowerASCII(*strings[i]);
  632. #define FreeStrings() { \
  633. for(i=0; i < size; ++i)\
  634. delete strings[i];\
  635. delete [] strings;\
  636. }
  637. #define ToArray(T,P,Y) case T: P = new Y[size]; To##T(strings, P, size); FreeStrings(); break;
  638. switch(type) {
  639. ToArray(S1,s1,char);
  640. ToArray(U1,u1,unsigned char);
  641. ToArray(S2,s2,short);
  642. ToArray(U2,u2,unsigned short);
  643. ToArray(S4,s4,int);
  644. ToArray(U4,u4,unsigned int);
  645. ToArray(S8,s8,long long);
  646. ToArray(U8,u8,unsigned long long);
  647. ToArray(F,f,float);
  648. ToArray(D,d,double);
  649. case T: t = strings; break; /* Don't erase strings array. */
  650. default: break;
  651. }
  652. };
  653. /* ------------------------------------------------------------------- */
  654. void ezOptionValidator::print() {
  655. printf("id=%d, op=%d, type=%d, size=%d, insensitive=%d\n", id, op, type, size, insensitive);
  656. };
  657. /* ------------------------------------------------------------------- */
  658. bool ezOptionValidator::isValid(const std::string * valueAsString) {
  659. if (valueAsString == 0) return false;
  660. #define CHECKRANGE(E,T) {\
  661. std::stringstream ss(valueAsString->c_str()); \
  662. long long E##value; \
  663. ss >> E##value; \
  664. long long E##min = static_cast<long long>(std::numeric_limits<T>::min()); \
  665. if (E##value < E##min) { \
  666. if (!quiet) \
  667. std::cerr << "ERROR: Invalid value " << E##value << " is less than datatype min " << E##min << ".\n"; \
  668. return false; \
  669. } \
  670. \
  671. long long E##max = static_cast<long long>(std::numeric_limits<T>::max()); \
  672. if (E##value > E##max) { \
  673. if (!quiet) \
  674. std::cerr << "ERROR: Invalid value " << E##value << " is greater than datatype max " << E##max << ".\n"; \
  675. return false; \
  676. } \
  677. }
  678. // Check if within datatype limits.
  679. if (type != T) {
  680. switch(type) {
  681. case S1: CHECKRANGE(S1,char); break;
  682. case U1: CHECKRANGE(U1,unsigned char); break;
  683. case S2: CHECKRANGE(S2,short); break;
  684. case U2: CHECKRANGE(U2,unsigned short); break;
  685. case S4: CHECKRANGE(S4,int); break;
  686. case U4: CHECKRANGE(U4,unsigned int); break;
  687. case S8: {
  688. if ( (valueAsString->at(0) == '-') &&
  689. isdigit(valueAsString,1) &&
  690. (valueAsString->size() > 19) &&
  691. (valueAsString->compare(1, 19, "9223372036854775808") > 0) ) {
  692. if (!quiet)
  693. std::cerr << "ERROR: Invalid value " << *valueAsString << " is less than datatype min -9223372036854775808.\n";
  694. return false;
  695. }
  696. if (isdigit(valueAsString) &&
  697. (valueAsString->size() > 18) &&
  698. valueAsString->compare("9223372036854775807") > 0) {
  699. if (!quiet)
  700. std::cerr << "ERROR: Invalid value " << *valueAsString << " is greater than datatype max 9223372036854775807.\n";
  701. return false;
  702. }
  703. } break;
  704. case U8: {
  705. if (valueAsString->compare("0") < 0) {
  706. if (!quiet)
  707. std::cerr << "ERROR: Invalid value " << *valueAsString << " is less than datatype min 0.\n";
  708. return false;
  709. }
  710. if (isdigit(valueAsString) &&
  711. (valueAsString->size() > 19) &&
  712. valueAsString->compare("18446744073709551615") > 0) {
  713. if (!quiet)
  714. std::cerr << "ERROR: Invalid value " << *valueAsString << " is greater than datatype max 18446744073709551615.\n";
  715. return false;
  716. }
  717. } break;
  718. case F: {
  719. double dmax = static_cast<double>(std::numeric_limits<float>::max());
  720. double dvalue = atof(valueAsString->c_str());
  721. double dmin = -dmax;
  722. if (dvalue < dmin) {
  723. if (!quiet) {
  724. fprintf(stderr, "ERROR: Invalid value %g is less than datatype min %g.\n", dvalue, dmin);
  725. }
  726. return false;
  727. }
  728. if (dvalue > dmax) {
  729. if (!quiet)
  730. std::cerr << "ERROR: Invalid value " << dvalue << " is greater than datatype max " << dmax << ".\n";
  731. return false;
  732. }
  733. } break;
  734. case D: {
  735. long double ldmax = static_cast<long double>(std::numeric_limits<double>::max());
  736. std::stringstream ss(valueAsString->c_str());
  737. long double ldvalue;
  738. ss >> ldvalue;
  739. long double ldmin = -ldmax;
  740. if (ldvalue < ldmin) {
  741. if (!quiet)
  742. std::cerr << "ERROR: Invalid value " << ldvalue << " is less than datatype min " << ldmin << ".\n";
  743. return false;
  744. }
  745. if (ldvalue > ldmax) {
  746. if (!quiet)
  747. std::cerr << "ERROR: Invalid value " << ldvalue << " is greater than datatype max " << ldmax << ".\n";
  748. return false;
  749. }
  750. } break;
  751. case NOTYPE: default: break;
  752. }
  753. } else {
  754. if (op == IN) {
  755. int i=0;
  756. if (insensitive) {
  757. std::string valueAsStringLower(*valueAsString);
  758. ToLowerASCII(valueAsStringLower);
  759. for(; i < size; ++i) {
  760. if (valueAsStringLower.compare(t[i]->c_str()) == 0)
  761. return true;
  762. }
  763. } else {
  764. for(; i < size; ++i) {
  765. if (valueAsString->compare(t[i]->c_str()) == 0)
  766. return true;
  767. }
  768. }
  769. return false;
  770. }
  771. }
  772. // Only check datatype limits, and return;
  773. if (op == NOOP) return true;
  774. #define VALIDATE(T, U, LIST) { \
  775. /* Value string converted to true native type. */ \
  776. std::stringstream ss(valueAsString->c_str());\
  777. U v;\
  778. ss >> v;\
  779. /* Check if within list. */ \
  780. if (op == IN) { \
  781. T * last = LIST + size;\
  782. return (last != std::find(LIST, last, v)); \
  783. } \
  784. \
  785. /* Check if within user's custom range. */ \
  786. T v0, v1; \
  787. if (size > 0) { \
  788. v0 = LIST[0]; \
  789. } \
  790. \
  791. if (size > 1) { \
  792. v1 = LIST[1]; \
  793. } \
  794. \
  795. switch (op) {\
  796. case LT:\
  797. if (size > 0) {\
  798. return v < v0;\
  799. } else {\
  800. std::cerr << "ERROR: No value given to validate if " << v << " < X.\n";\
  801. return false;\
  802. }\
  803. break;\
  804. case LE:\
  805. if (size > 0) {\
  806. return v <= v0;\
  807. } else {\
  808. std::cerr << "ERROR: No value given to validate if " << v << " <= X.\n";\
  809. return false;\
  810. }\
  811. break;\
  812. case GT:\
  813. if (size > 0) {\
  814. return v > v0;\
  815. } else {\
  816. std::cerr << "ERROR: No value given to validate if " << v << " > X.\n";\
  817. return false;\
  818. }\
  819. break;\
  820. case GE:\
  821. if (size > 0) {\
  822. return v >= v0;\
  823. } else {\
  824. std::cerr << "ERROR: No value given to validate if " << v << " >= X.\n";\
  825. return false;\
  826. }\
  827. break;\
  828. case GTLT:\
  829. if (size > 1) {\
  830. return (v0 < v) && (v < v1);\
  831. } else {\
  832. std::cerr << "ERROR: Missing values to validate if X1 < " << v << " < X2.\n";\
  833. return false;\
  834. }\
  835. break;\
  836. case GELT:\
  837. if (size > 1) {\
  838. return (v0 <= v) && (v < v1);\
  839. } else {\
  840. std::cerr << "ERROR: Missing values to validate if X1 <= " << v << " < X2.\n";\
  841. return false;\
  842. }\
  843. break;\
  844. case GELE:\
  845. if (size > 1) {\
  846. return (v0 <= v) && (v <= v1);\
  847. } else {\
  848. std::cerr << "ERROR: Missing values to validate if X1 <= " << v << " <= X2.\n";\
  849. return false;\
  850. }\
  851. break;\
  852. case GTLE:\
  853. if (size > 1) {\
  854. return (v0 < v) && (v <= v1);\
  855. } else {\
  856. std::cerr << "ERROR: Missing values to validate if X1 < " << v << " <= X2.\n";\
  857. return false;\
  858. }\
  859. break;\
  860. case NOOP: case IN: default: break;\
  861. } \
  862. }
  863. switch(type) {
  864. case U1: VALIDATE(unsigned char, int, u1); break;
  865. case S1: VALIDATE(char, int, s1); break;
  866. case U2: VALIDATE(unsigned short, int, u2); break;
  867. case S2: VALIDATE(short, int, s2); break;
  868. case U4: VALIDATE(unsigned int, unsigned int, u4); break;
  869. case S4: VALIDATE(int, int, s4); break;
  870. case U8: VALIDATE(unsigned long long, unsigned long long, u8); break;
  871. case S8: VALIDATE(long long, long long, s8); break;
  872. case F: VALIDATE(float, float, f); break;
  873. case D: VALIDATE(double, double, d); break;
  874. default: break;
  875. }
  876. return true;
  877. };
  878. /* ################################################################### */
  879. class OptionGroup {
  880. public:
  881. OptionGroup() : delim(0), expectArgs(0), isRequired(false), isSet(false) { }
  882. ~OptionGroup() {
  883. int i;
  884. for(i=0; i < (long int)flags.size(); ++i)
  885. delete flags[i];
  886. flags.clear();
  887. parseIndex.clear();
  888. clearArgs();
  889. };
  890. inline void clearArgs();
  891. inline void getInt(int&);
  892. inline void getLong(long&);
  893. inline void getLongLong(long long&);
  894. inline void getULong(unsigned long&);
  895. inline void getULongLong(unsigned long long&);
  896. inline void getFloat(float&);
  897. inline void getDouble(double&);
  898. inline void getString(std::string&);
  899. inline void getInts(std::vector<int>&);
  900. inline void getLongs(std::vector<long>&);
  901. inline void getULongs(std::vector<unsigned long>&);
  902. inline void getFloats(std::vector<float>&);
  903. inline void getDoubles(std::vector<double>&);
  904. inline void getStrings(std::vector<std::string>&);
  905. inline void getMultiInts(std::vector< std::vector<int> >&);
  906. inline void getMultiLongs(std::vector< std::vector<long> >&);
  907. inline void getMultiULongs(std::vector< std::vector<unsigned long> >&);
  908. inline void getMultiFloats(std::vector< std::vector<float> >&);
  909. inline void getMultiDoubles(std::vector< std::vector<double> >&);
  910. inline void getMultiStrings(std::vector< std::vector<std::string> >&);
  911. // defaults value regardless of being set by user.
  912. std::string defaults;
  913. // If expects arguments, this will delimit arg list.
  914. char delim;
  915. // If not 0, then number of delimited args. -1 for arbitrary number.
  916. int expectArgs;
  917. // Descriptive help message shown in usage instructions for option.
  918. std::string help;
  919. // 0 or 1.
  920. bool isRequired;
  921. // A list of flags that denote this option, i.e. -d, --dimension.
  922. std::vector< std::string* > flags;
  923. // If was set (or found).
  924. bool isSet;
  925. // Lists of arguments, per flag instance, after splitting by delimiter.
  926. std::vector< std::vector< std::string* > * > args;
  927. // Index where each group was parsed from input stream to track order.
  928. std::vector<int> parseIndex;
  929. };
  930. /* ################################################################### */
  931. void OptionGroup::clearArgs() {
  932. int i,j;
  933. for(i=0; i < (long int)args.size(); ++i) {
  934. for(j=0; j < (long int)args[i]->size(); ++j)
  935. delete args[i]->at(j);
  936. delete args[i];
  937. }
  938. args.clear();
  939. isSet = false;
  940. };
  941. /* ################################################################### */
  942. void OptionGroup::getInt(int & out) {
  943. if (!isSet) {
  944. if (defaults.empty())
  945. out = 0;
  946. else
  947. out = atoi(defaults.c_str());
  948. } else {
  949. if (args.empty() || args[0]->empty())
  950. out = 0;
  951. else {
  952. out = atoi(args[0]->at(0)->c_str());
  953. }
  954. }
  955. };
  956. /* ################################################################### */
  957. void OptionGroup::getLong(long & out) {
  958. if (!isSet) {
  959. if (defaults.empty())
  960. out = 0;
  961. else
  962. out = atoi(defaults.c_str());
  963. } else {
  964. if (args.empty() || args[0]->empty())
  965. out = 0;
  966. else {
  967. out = atol(args[0]->at(0)->c_str());
  968. }
  969. }
  970. };
  971. /* ################################################################### */
  972. void OptionGroup::getLongLong(long long & out) {
  973. if (!isSet) {
  974. if (defaults.empty())
  975. out = 0;
  976. else {
  977. std::stringstream ss(defaults.c_str());
  978. ss >> out;
  979. }
  980. } else {
  981. if (args.empty() || args[0]->empty())
  982. out = 0;
  983. else {
  984. std::stringstream ss(args[0]->at(0)->c_str());
  985. ss >> out;
  986. }
  987. }
  988. };
  989. /* ################################################################### */
  990. void OptionGroup::getULong(unsigned long & out) {
  991. if (!isSet) {
  992. if (defaults.empty())
  993. out = 0;
  994. else
  995. out = atoi(defaults.c_str());
  996. } else {
  997. if (args.empty() || args[0]->empty())
  998. out = 0;
  999. else {
  1000. out = strtoul(args[0]->at(0)->c_str(),0,0);
  1001. }
  1002. }
  1003. };
  1004. /* ################################################################### */
  1005. void OptionGroup::getULongLong(unsigned long long & out) {
  1006. if (!isSet) {
  1007. if (defaults.empty())
  1008. out = 0;
  1009. else {
  1010. std::stringstream ss(defaults.c_str());
  1011. ss >> out;
  1012. }
  1013. } else {
  1014. if (args.empty() || args[0]->empty())
  1015. out = 0;
  1016. else {
  1017. std::stringstream ss(args[0]->at(0)->c_str());
  1018. ss >> out;
  1019. }
  1020. }
  1021. };
  1022. /* ################################################################### */
  1023. void OptionGroup::getFloat(float & out) {
  1024. if (!isSet) {
  1025. if (defaults.empty())
  1026. out = 0.0;
  1027. else
  1028. out = (float)atof(defaults.c_str());
  1029. } else {
  1030. if (args.empty() || args[0]->empty())
  1031. out = 0.0;
  1032. else {
  1033. out = (float)atof(args[0]->at(0)->c_str());
  1034. }
  1035. }
  1036. };
  1037. /* ################################################################### */
  1038. void OptionGroup::getDouble(double & out) {
  1039. if (!isSet) {
  1040. if (defaults.empty())
  1041. out = 0.0;
  1042. else
  1043. out = atof(defaults.c_str());
  1044. } else {
  1045. if (args.empty() || args[0]->empty())
  1046. out = 0.0;
  1047. else {
  1048. out = atof(args[0]->at(0)->c_str());
  1049. }
  1050. }
  1051. };
  1052. /* ################################################################### */
  1053. void OptionGroup::getString(std::string & out) {
  1054. if (!isSet) {
  1055. out = defaults;
  1056. } else {
  1057. if (args.empty() || args[0]->empty())
  1058. out = "";
  1059. else {
  1060. out = *args[0]->at(0);
  1061. }
  1062. }
  1063. };
  1064. /* ################################################################### */
  1065. void OptionGroup::getInts(std::vector<int> & out) {
  1066. if (!isSet) {
  1067. if (!defaults.empty()) {
  1068. std::vector< std::string > strings;
  1069. SplitDelim(defaults, delim, strings);
  1070. StringsToInts(strings, out);
  1071. }
  1072. } else {
  1073. if (!(args.empty() || args[0]->empty()))
  1074. StringsToInts(args[0], &out);
  1075. }
  1076. };
  1077. /* ################################################################### */
  1078. void OptionGroup::getLongs(std::vector<long> & out) {
  1079. if (!isSet) {
  1080. if (!defaults.empty()) {
  1081. std::vector< std::string > strings;
  1082. SplitDelim(defaults, delim, strings);
  1083. StringsToLongs(strings, out);
  1084. }
  1085. } else {
  1086. if (!(args.empty() || args[0]->empty()))
  1087. StringsToLongs(args[0], &out);
  1088. }
  1089. };
  1090. /* ################################################################### */
  1091. void OptionGroup::getULongs(std::vector<unsigned long> & out) {
  1092. if (!isSet) {
  1093. if (!defaults.empty()) {
  1094. std::vector< std::string > strings;
  1095. SplitDelim(defaults, delim, strings);
  1096. StringsToULongs(strings, out);
  1097. }
  1098. } else {
  1099. if (!(args.empty() || args[0]->empty()))
  1100. StringsToULongs(args[0], &out);
  1101. }
  1102. };
  1103. /* ################################################################### */
  1104. void OptionGroup::getFloats(std::vector<float> & out) {
  1105. if (!isSet) {
  1106. if (!defaults.empty()) {
  1107. std::vector< std::string > strings;
  1108. SplitDelim(defaults, delim, strings);
  1109. StringsToFloats(strings, out);
  1110. }
  1111. } else {
  1112. if (!(args.empty() || args[0]->empty()))
  1113. StringsToFloats(args[0], &out);
  1114. }
  1115. };
  1116. /* ################################################################### */
  1117. void OptionGroup::getDoubles(std::vector<double> & out) {
  1118. if (!isSet) {
  1119. if (!defaults.empty()) {
  1120. std::vector< std::string > strings;
  1121. SplitDelim(defaults, delim, strings);
  1122. StringsToDoubles(strings, out);
  1123. }
  1124. } else {
  1125. if (!(args.empty() || args[0]->empty()))
  1126. StringsToDoubles(args[0], &out);
  1127. }
  1128. };
  1129. /* ################################################################### */
  1130. void OptionGroup::getStrings(std::vector<std::string>& out) {
  1131. if (!isSet) {
  1132. if (!defaults.empty()) {
  1133. SplitDelim(defaults, delim, out);
  1134. }
  1135. } else {
  1136. if (!(args.empty() || args[0]->empty()))
  1137. StringsToStrings(args[0], &out);
  1138. }
  1139. };
  1140. /* ################################################################### */
  1141. void OptionGroup::getMultiInts(std::vector< std::vector<int> >& out) {
  1142. if (!isSet) {
  1143. if (!defaults.empty()) {
  1144. std::vector< std::string > strings;
  1145. SplitDelim(defaults, delim, strings);
  1146. if (out.size() < 1) out.resize(1);
  1147. StringsToInts(strings, out[0]);
  1148. }
  1149. } else {
  1150. if (!args.empty()) {
  1151. int n = args.size();
  1152. if ((long int)out.size() < n) out.resize(n);
  1153. for(int i=0; i < n; ++i) {
  1154. StringsToInts(args[i], &out[i]);
  1155. }
  1156. }
  1157. }
  1158. };
  1159. /* ################################################################### */
  1160. void OptionGroup::getMultiLongs(std::vector< std::vector<long> >& out) {
  1161. if (!isSet) {
  1162. if (!defaults.empty()) {
  1163. std::vector< std::string > strings;
  1164. SplitDelim(defaults, delim, strings);
  1165. if (out.size() < 1) out.resize(1);
  1166. StringsToLongs(strings, out[0]);
  1167. }
  1168. } else {
  1169. if (!args.empty()) {
  1170. int n = args.size();
  1171. if ((long int)out.size() < n) out.resize(n);
  1172. for(int i=0; i < n; ++i) {
  1173. StringsToLongs(args[i], &out[i]);
  1174. }
  1175. }
  1176. }
  1177. };
  1178. /* ################################################################### */
  1179. void OptionGroup::getMultiULongs(std::vector< std::vector<unsigned long> >& out) {
  1180. if (!isSet) {
  1181. if (!defaults.empty()) {
  1182. std::vector< std::string > strings;
  1183. SplitDelim(defaults, delim, strings);
  1184. if (out.size() < 1) out.resize(1);
  1185. StringsToULongs(strings, out[0]);
  1186. }
  1187. } else {
  1188. if (!args.empty()) {
  1189. int n = args.size();
  1190. if ((long int)out.size() < n) out.resize(n);
  1191. for(int i=0; i < n; ++i) {
  1192. StringsToULongs(args[i], &out[i]);
  1193. }
  1194. }
  1195. }
  1196. };
  1197. /* ################################################################### */
  1198. void OptionGroup::getMultiFloats(std::vector< std::vector<float> >& out) {
  1199. if (!isSet) {
  1200. if (!defaults.empty()) {
  1201. std::vector< std::string > strings;
  1202. SplitDelim(defaults, delim, strings);
  1203. if (out.size() < 1) out.resize(1);
  1204. StringsToFloats(strings, out[0]);
  1205. }
  1206. } else {
  1207. if (!args.empty()) {
  1208. int n = args.size();
  1209. if ((long int)out.size() < n) out.resize(n);
  1210. for(int i=0; i < n; ++i) {
  1211. StringsToFloats(args[i], &out[i]);
  1212. }
  1213. }
  1214. }
  1215. };
  1216. /* ################################################################### */
  1217. void OptionGroup::getMultiDoubles(std::vector< std::vector<double> >& out) {
  1218. if (!isSet) {
  1219. if (!defaults.empty()) {
  1220. std::vector< std::string > strings;
  1221. SplitDelim(defaults, delim, strings);
  1222. if (out.size() < 1) out.resize(1);
  1223. StringsToDoubles(strings, out[0]);
  1224. }
  1225. } else {
  1226. if (!args.empty()) {
  1227. int n = args.size();
  1228. if ((long int)out.size() < n) out.resize(n);
  1229. for(int i=0; i < n; ++i) {
  1230. StringsToDoubles(args[i], &out[i]);
  1231. }
  1232. }
  1233. }
  1234. };
  1235. /* ################################################################### */
  1236. void OptionGroup::getMultiStrings(std::vector< std::vector<std::string> >& out) {
  1237. if (!isSet) {
  1238. if (!defaults.empty()) {
  1239. std::vector< std::string > strings;
  1240. SplitDelim(defaults, delim, strings);
  1241. if (out.size() < 1) out.resize(1);
  1242. out[0] = strings;
  1243. }
  1244. } else {
  1245. if (!args.empty()) {
  1246. int n = args.size();
  1247. if ((long int)out.size() < n) out.resize(n);
  1248. for(int i=0; i < n; ++i) {
  1249. for(int j=0; j < (long int)args[i]->size(); ++j)
  1250. out[i].push_back( *args[i]->at(j) );
  1251. }
  1252. }
  1253. }
  1254. };
  1255. /* ################################################################### */
  1256. typedef std::map< int, ezOptionValidator* > ValidatorMap;
  1257. class ezOptionParser {
  1258. public:
  1259. // How to layout usage descriptions with the option flags.
  1260. enum Layout { ALIGN, INTERLEAVE, STAGGER };
  1261. inline ~ezOptionParser();
  1262. inline void add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, ezOptionValidator* validator=0);
  1263. inline void add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, const char * flag2, ezOptionValidator* validator=0);
  1264. inline void add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, const char * flag2, const char * flag3, ezOptionValidator* validator=0);
  1265. inline void add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, const char * flag2, const char * flag3, const char * flag4, ezOptionValidator* validator=0);
  1266. inline bool exportFile(const char * filename, bool all=false);
  1267. inline OptionGroup * get(const char * name);
  1268. inline void getUsage(std::string & usage, int width=80, Layout layout=ALIGN);
  1269. inline void getUsageDescriptions(std::string & usage, int width=80, Layout layout=STAGGER);
  1270. inline bool gotExpected(std::vector<std::string> & badOptions);
  1271. inline bool gotRequired(std::vector<std::string> & badOptions);
  1272. inline bool gotValid(std::vector<std::string> & badOptions, std::vector<std::string> & badArgs);
  1273. inline bool importFile(const char * filename, char comment='#');
  1274. inline int isSet(const char * name);
  1275. inline int isSet(std::string & name);
  1276. inline void parse(int argc, const char * argv[]);
  1277. inline void prettyPrint(std::string & out);
  1278. inline void reset();
  1279. inline void resetArgs();
  1280. // Insert extra empty line betwee each option's usage description.
  1281. char doublespace;
  1282. // General description in human language on what the user's tool does.
  1283. // It's the first section to get printed in the full usage message.
  1284. std::string overview;
  1285. // A synopsis of command and options usage to show expected order of input arguments.
  1286. // It's the second section to get printed in the full usage message.
  1287. std::string syntax;
  1288. // Example (third) section in usage message.
  1289. std::string example;
  1290. // Final section printed in usage message. For contact, copyrights, version info.
  1291. std::string footer;
  1292. // Map from an option to an Id of its parent group.
  1293. std::map< std::string, int > optionGroupIds;
  1294. // Unordered collection of the option groups.
  1295. std::vector< OptionGroup* > groups;
  1296. // Store unexpected args in input.
  1297. std::vector< std::string* > unknownArgs;
  1298. // List of args that occur left-most before first option flag.
  1299. std::vector< std::string* > firstArgs;
  1300. // List of args that occur after last right-most option flag and its args.
  1301. std::vector< std::string* > lastArgs;
  1302. // List of validators.
  1303. ValidatorMap validators;
  1304. // Maps group id to a validator index into vector of validators. Validator index is -1 if there is no validator for group.
  1305. std::map< int, int > groupValidators;
  1306. };
  1307. /* ################################################################### */
  1308. ezOptionParser::~ezOptionParser() {
  1309. reset();
  1310. }
  1311. /* ################################################################### */
  1312. void ezOptionParser::reset() {
  1313. this->doublespace = 1;
  1314. int i;
  1315. for(i=0; i < (long int)groups.size(); ++i)
  1316. delete groups[i];
  1317. groups.clear();
  1318. for(i=0; i < (long int)unknownArgs.size(); ++i)
  1319. delete unknownArgs[i];
  1320. unknownArgs.clear();
  1321. for(i=0; i < (long int)firstArgs.size(); ++i)
  1322. delete firstArgs[i];
  1323. firstArgs.clear();
  1324. for(i=0; i < (long int)lastArgs.size(); ++i)
  1325. delete lastArgs[i];
  1326. lastArgs.clear();
  1327. ValidatorMap::iterator it;
  1328. for(it = validators.begin(); it != validators.end(); ++it)
  1329. delete it->second;
  1330. validators.clear();
  1331. optionGroupIds.clear();
  1332. groupValidators.clear();
  1333. };
  1334. /* ################################################################### */
  1335. void ezOptionParser::resetArgs() {
  1336. int i;
  1337. for(i=0; i < (long int)groups.size(); ++i)
  1338. groups[i]->clearArgs();
  1339. for(i=0; i < (long int)unknownArgs.size(); ++i)
  1340. delete unknownArgs[i];
  1341. unknownArgs.clear();
  1342. for(i=0; i < (long int)firstArgs.size(); ++i)
  1343. delete firstArgs[i];
  1344. firstArgs.clear();
  1345. for(i=0; i < (long int)lastArgs.size(); ++i)
  1346. delete lastArgs[i];
  1347. lastArgs.clear();
  1348. };
  1349. /* ################################################################### */
  1350. void ezOptionParser::add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, ezOptionValidator* validator) {
  1351. int id = this->groups.size();
  1352. OptionGroup * g = new OptionGroup;
  1353. g->defaults = defaults;
  1354. g->isRequired = required;
  1355. g->expectArgs = expectArgs;
  1356. g->delim = delim;
  1357. g->isSet = 0;
  1358. g->help = help;
  1359. std::string *f1 = new std::string(flag1);
  1360. g->flags.push_back( f1 );
  1361. this->optionGroupIds[flag1] = id;
  1362. this->groups.push_back(g);
  1363. if (validator) {
  1364. int vid = validator->id;
  1365. validators[vid] = validator;
  1366. groupValidators[id] = vid;
  1367. } else {
  1368. groupValidators[id] = -1;
  1369. }
  1370. };
  1371. /* ################################################################### */
  1372. void ezOptionParser::add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, const char * flag2, ezOptionValidator* validator) {
  1373. int id = this->groups.size();
  1374. OptionGroup * g = new OptionGroup;
  1375. g->defaults = defaults;
  1376. g->isRequired = required;
  1377. g->expectArgs = expectArgs;
  1378. g->delim = delim;
  1379. g->isSet = 0;
  1380. g->help = help;
  1381. std::string *f1 = new std::string(flag1);
  1382. g->flags.push_back( f1 );
  1383. std::string *f2 = new std::string(flag2);
  1384. g->flags.push_back( f2 );
  1385. this->optionGroupIds[flag1] = id;
  1386. this->optionGroupIds[flag2] = id;
  1387. this->groups.push_back(g);
  1388. if (validator) {
  1389. int vid = validator->id;
  1390. validators[vid] = validator;
  1391. groupValidators[id] = vid;
  1392. } else {
  1393. groupValidators[id] = -1;
  1394. }
  1395. };
  1396. /* ################################################################### */
  1397. void ezOptionParser::add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, const char * flag2, const char * flag3, ezOptionValidator* validator) {
  1398. int id = this->groups.size();
  1399. OptionGroup * g = new OptionGroup;
  1400. g->defaults = defaults;
  1401. g->isRequired = required;
  1402. g->expectArgs = expectArgs;
  1403. g->delim = delim;
  1404. g->isSet = 0;
  1405. g->help = help;
  1406. std::string *f1 = new std::string(flag1);
  1407. g->flags.push_back( f1 );
  1408. std::string *f2 = new std::string(flag2);
  1409. g->flags.push_back( f2 );
  1410. std::string *f3 = new std::string(flag3);
  1411. g->flags.push_back( f3 );
  1412. this->optionGroupIds[flag1] = id;
  1413. this->optionGroupIds[flag2] = id;
  1414. this->optionGroupIds[flag3] = id;
  1415. this->groups.push_back(g);
  1416. if (validator) {
  1417. int vid = validator->id;
  1418. validators[vid] = validator;
  1419. groupValidators[id] = vid;
  1420. } else {
  1421. groupValidators[id] = -1;
  1422. }
  1423. };
  1424. /* ################################################################### */
  1425. void ezOptionParser::add(const char * defaults, bool required, int expectArgs, char delim, const char * help, const char * flag1, const char * flag2, const char * flag3, const char * flag4, ezOptionValidator* validator) {
  1426. int id = this->groups.size();
  1427. OptionGroup * g = new OptionGroup;
  1428. g->defaults = defaults;
  1429. g->isRequired = required;
  1430. g->expectArgs = expectArgs;
  1431. g->delim = delim;
  1432. g->isSet = 0;
  1433. g->help = help;
  1434. std::string *f1 = new std::string(flag1);
  1435. g->flags.push_back( f1 );
  1436. std::string *f2 = new std::string(flag2);
  1437. g->flags.push_back( f2 );
  1438. std::string *f3 = new std::string(flag3);
  1439. g->flags.push_back( f3 );
  1440. std::string *f4 = new std::string(flag4);
  1441. g->flags.push_back( f4 );
  1442. this->optionGroupIds[flag1] = id;
  1443. this->optionGroupIds[flag2] = id;
  1444. this->optionGroupIds[flag3] = id;
  1445. this->optionGroupIds[flag4] = id;
  1446. this->groups.push_back(g);
  1447. if (validator) {
  1448. int vid = validator->id;
  1449. validators[vid] = validator;
  1450. groupValidators[id] = vid;
  1451. } else {
  1452. groupValidators[id] = -1;
  1453. }
  1454. };
  1455. /* ################################################################### */
  1456. bool ezOptionParser::exportFile(const char * filename, bool all) {
  1457. int i;
  1458. std::string out;
  1459. bool quote;
  1460. // Export the first args, except the program name, so start from 1.
  1461. for(i=1; i < (long int)firstArgs.size(); ++i) {
  1462. quote = ((firstArgs[i]->find_first_of(" \t") != std::string::npos) && (firstArgs[i]->find_first_of("\'\"") == std::string::npos));
  1463. if (quote)
  1464. out.append("\"");
  1465. out.append(*firstArgs[i]);
  1466. if (quote)
  1467. out.append("\"");
  1468. out.append(" ");
  1469. }
  1470. if (firstArgs.size() > 1)
  1471. out.append("\n");
  1472. std::vector<std::string* > stringPtrs(groups.size());
  1473. int m;
  1474. int n = groups.size();
  1475. for(i=0; i < n; ++i) {
  1476. stringPtrs[i] = groups[i]->flags[0];
  1477. }
  1478. OptionGroup *g;
  1479. // Sort first flag of each group with other groups.
  1480. std::sort(stringPtrs.begin(), stringPtrs.end(), CmpOptStringPtr);
  1481. for(i=0; i < n; ++i) {
  1482. g = get(stringPtrs[i]->c_str());
  1483. if (g->isSet || all) {
  1484. if (!g->isSet || g->args.empty()) {
  1485. if (!g->defaults.empty()) {
  1486. out.append(*stringPtrs[i]);
  1487. out.append(" ");
  1488. quote = ((g->defaults.find_first_of(" \t") != std::string::npos) && (g->defaults.find_first_of("\'\"") == std::string::npos));
  1489. if (quote)
  1490. out.append("\"");
  1491. out.append(g->defaults);
  1492. if (quote)
  1493. out.append("\"");
  1494. out.append("\n");
  1495. }
  1496. } else {
  1497. int n = g->args.size();
  1498. for(int j=0; j < n; ++j) {
  1499. out.append(*stringPtrs[i]);
  1500. out.append(" ");
  1501. m = g->args[j]->size();
  1502. for(int k=0; k < m; ++k) {
  1503. quote = ( (*g->args[j]->at(k)).find_first_of(" \t") != std::string::npos );
  1504. if (quote)
  1505. out.append("\"");
  1506. out.append(*g->args[j]->at(k));
  1507. if (quote)
  1508. out.append("\"");
  1509. if ((g->delim) && ((k+1) != m))
  1510. out.append(1,g->delim);
  1511. }
  1512. out.append("\n");
  1513. }
  1514. }
  1515. }
  1516. }
  1517. // Export the last args.
  1518. for(i=0; i < (long int)lastArgs.size(); ++i) {
  1519. quote = ( lastArgs[i]->find_first_of(" \t") != std::string::npos );
  1520. if (quote)
  1521. out.append("\"");
  1522. out.append(*lastArgs[i]);
  1523. if (quote)
  1524. out.append("\"");
  1525. out.append(" ");
  1526. }
  1527. std::ofstream file(filename);
  1528. if (!file.is_open())
  1529. return false;
  1530. file << out;
  1531. file.close();
  1532. return true;
  1533. };
  1534. /* ################################################################### */
  1535. // Does not overwrite current options.
  1536. // Returns true if file was read successfully.
  1537. // So if this is used before parsing CLI, then option values will reflect
  1538. // this file, but if used after parsing CLI, then values will contain
  1539. // both CLI values and file's values.
  1540. //
  1541. // Comment lines are allowed if prefixed with #.
  1542. // Strings should be quoted as usual.
  1543. bool ezOptionParser::importFile(const char * filename, char comment) {
  1544. std::ifstream file (filename, std::ios::in | std::ios::ate);
  1545. if (!file.is_open())
  1546. return false;
  1547. // Read entire file contents.
  1548. std::ifstream::pos_type size = file.tellg();
  1549. char * memblock = new char[(int)size+1]; // Add one for end of string.
  1550. file.seekg (0, std::ios::beg);
  1551. file.read (memblock, size);
  1552. memblock[size] = '\0';
  1553. file.close();
  1554. // Find comment lines.
  1555. std::list<std::string*> lines;
  1556. std::string memblockstring(memblock);
  1557. delete[] memblock;
  1558. SplitDelim(memblockstring, '\n', lines);
  1559. int i,j,n;
  1560. std::list<std::string*>::iterator iter;
  1561. std::vector<int> sq, dq; // Single and double quote indices.
  1562. std::vector<int>::iterator lo; // For searching quote indices.
  1563. size_t pos;
  1564. const char *str;
  1565. std::string *line;
  1566. // Find all single and double quotes to correctly handle comment tokens.
  1567. for(iter=lines.begin(); iter != lines.end(); ++iter) {
  1568. line = *iter;
  1569. str = line->c_str();
  1570. n = line->size();
  1571. sq.clear();
  1572. dq.clear();
  1573. if (n) {
  1574. // If first char is comment, then erase line and continue.
  1575. pos = line->find_first_not_of(" \t\r");
  1576. if ((pos==std::string::npos) || (line->at(pos)==comment)) {
  1577. line->erase();
  1578. continue;
  1579. } else {
  1580. // Erase whitespace prefix.
  1581. line->erase(0,pos);
  1582. n = line->size();
  1583. }
  1584. if (line->at(0)=='"')
  1585. dq.push_back(0);
  1586. if (line->at(0)=='\'')
  1587. sq.push_back(0);
  1588. } else { // Empty line.
  1589. continue;
  1590. }
  1591. for(i=1; i < n; ++i) {
  1592. if ( (str[i]=='"') && (str[i-1]!='\\') )
  1593. dq.push_back(i);
  1594. else if ( (str[i]=='\'') && (str[i-1]!='\\') )
  1595. sq.push_back(i);
  1596. }
  1597. // Scan for comments, and when found, check bounds of quotes.
  1598. // Start with second char because already checked first char.
  1599. for(i=1; i < n; ++i) {
  1600. if ( (line->at(i)==comment) && (line->at(i-1)!='\\') ) {
  1601. // If within open/close quote pair, then not real comment.
  1602. if (sq.size()) {
  1603. lo = std::lower_bound(sq.begin(), sq.end(), i);
  1604. // All start of strings will be even indices, closing quotes is odd indices.
  1605. j = (int)(lo-sq.begin());
  1606. if ( (j % 2) == 0) { // Even implies comment char not in quote pair.
  1607. // Erase from comment char to end of line.
  1608. line->erase(i);
  1609. break;
  1610. }
  1611. } else if (dq.size()) {
  1612. // Repeat tests for double quotes.
  1613. lo = std::lower_bound(dq.begin(), dq.end(), i);
  1614. j = (int)(lo-dq.begin());
  1615. if ( (j % 2) == 0) {
  1616. line->erase(i);
  1617. break;
  1618. }
  1619. } else {
  1620. // Not in quotes.
  1621. line->erase(i);
  1622. break;
  1623. }
  1624. }
  1625. }
  1626. }
  1627. std::string cmd;
  1628. // Convert list to string without newlines to simulate commandline.
  1629. for(iter=lines.begin(); iter != lines.end(); ++iter) {
  1630. if (! (*iter)->empty()) {
  1631. cmd.append(**iter);
  1632. cmd.append(" ");
  1633. }
  1634. }
  1635. // Now parse as if from command line.
  1636. int argc=0;
  1637. char** argv = CommandLineToArgvA((char*)cmd.c_str(), &argc);
  1638. // Parse.
  1639. parse(argc, (const char**)argv);
  1640. if (argv) free(argv);
  1641. for(iter=lines.begin(); iter != lines.end(); ++iter)
  1642. delete *iter;
  1643. return true;
  1644. };
  1645. /* ################################################################### */
  1646. int ezOptionParser::isSet(const char * name) {
  1647. std::string sname(name);
  1648. if (this->optionGroupIds.count(sname)) {
  1649. return this->groups[this->optionGroupIds[sname]]->isSet;
  1650. }
  1651. return 0;
  1652. };
  1653. /* ################################################################### */
  1654. int ezOptionParser::isSet(std::string & name) {
  1655. if (this->optionGroupIds.count(name)) {
  1656. return this->groups[this->optionGroupIds[name]]->isSet;
  1657. }
  1658. return 0;
  1659. };
  1660. /* ################################################################### */
  1661. OptionGroup * ezOptionParser::get(const char * name) {
  1662. if (optionGroupIds.count(name)) {
  1663. return groups[optionGroupIds[name]];
  1664. }
  1665. return 0;
  1666. };
  1667. /* ################################################################### */
  1668. void ezOptionParser::getUsage(std::string & usage, int width, Layout layout) {
  1669. usage.append(overview);
  1670. usage.append("\n\n");
  1671. usage.append("USAGE: ");
  1672. usage.append(syntax);
  1673. usage.append("\n\nOPTIONS:\n\n");
  1674. getUsageDescriptions(usage, width, layout);
  1675. if (!example.empty()) {
  1676. usage.append("EXAMPLES:\n\n");
  1677. usage.append(example);
  1678. }
  1679. if (!footer.empty()) {
  1680. usage.append(footer);
  1681. }
  1682. };
  1683. /* ################################################################### */
  1684. // Creates 2 column formatted help descriptions for each option flag.
  1685. void ezOptionParser::getUsageDescriptions(std::string & usage, int width, Layout layout) {
  1686. // Sort each flag list amongst each group.
  1687. int i;
  1688. // Store index of flag groups before sort for easy lookup later.
  1689. std::map<std::string*, int> stringPtrToIndexMap;
  1690. std::vector<std::string* > stringPtrs(groups.size());
  1691. for(i=0; i < (long int)groups.size(); ++i) {
  1692. std::sort(groups[i]->flags.begin(), groups[i]->flags.end(), CmpOptStringPtr);
  1693. stringPtrToIndexMap[groups[i]->flags[0]] = i;
  1694. stringPtrs[i] = groups[i]->flags[0];
  1695. }
  1696. size_t j, k;
  1697. std::string opts;
  1698. std::vector<std::string> sortedOpts;
  1699. // Sort first flag of each group with other groups.
  1700. std::sort(stringPtrs.begin(), stringPtrs.end(), CmpOptStringPtr);
  1701. for(i=0; i < (long int)groups.size(); ++i) {
  1702. //printf("DEBUG:%d: %d %d %s\n", __LINE__, i, stringPtrToIndexMap[stringPtrs[i]], stringPtrs[i]->c_str());
  1703. k = stringPtrToIndexMap[stringPtrs[i]];
  1704. opts.clear();
  1705. for(j=0; j < groups[k]->flags.size()-1; ++j) {
  1706. opts.append(*groups[k]->flags[j]);
  1707. opts.append(", ");
  1708. if ((long int)opts.size() > width)
  1709. opts.append("\n");
  1710. }
  1711. // The last flag. No need to append comma anymore.
  1712. opts.append( *groups[k]->flags[j] );
  1713. if (groups[k]->expectArgs) {
  1714. opts.append(" ARG");
  1715. if (groups[k]->delim) {
  1716. opts.append("1[");
  1717. opts.append(1, groups[k]->delim);
  1718. opts.append("ARGn]");
  1719. }
  1720. }
  1721. sortedOpts.push_back(opts);
  1722. }
  1723. // Each option group will use this to build multiline help description.
  1724. std::list<std::string*> desc;
  1725. // Number of whitespaces from start of line to description (interleave layout) or
  1726. // gap between flag names and description (align, stagger layouts).
  1727. int gutter = 3;
  1728. // Find longest opt flag string to set column start for help usage descriptions.
  1729. int maxlen=0;
  1730. if (layout == ALIGN) {
  1731. for(i=0; i < (long int)groups.size(); ++i) {
  1732. if (maxlen < (long int)sortedOpts[i].size())
  1733. maxlen = sortedOpts[i].size();
  1734. }
  1735. }
  1736. // The amount of space remaining on a line for help text after flags.
  1737. int helpwidth;
  1738. std::list<std::string*>::iterator cIter, insertionIter;
  1739. size_t pos;
  1740. for(i=0; i < (long int)groups.size(); ++i) {
  1741. k = stringPtrToIndexMap[stringPtrs[i]];
  1742. if (layout == STAGGER)
  1743. maxlen = sortedOpts[i].size();
  1744. int pad = gutter + maxlen;
  1745. helpwidth = width - pad;
  1746. // All the following split-fu could be optimized by just using substring (offset, length) tuples, but just to get it done, we'll do some not-too expensive string copying.
  1747. SplitDelim(groups[k]->help, '\n', desc);
  1748. // Split lines longer than allowable help width.
  1749. for(insertionIter=desc.begin(), cIter=insertionIter++;
  1750. cIter != desc.end();
  1751. cIter=insertionIter++) {
  1752. if ((long int)((*cIter)->size()) > helpwidth) {
  1753. // Get pointer to next string to insert new strings before it.
  1754. std::string *rem = *cIter;
  1755. // Remove this line and add back in pieces.
  1756. desc.erase(cIter);
  1757. // Loop until remaining string is short enough.
  1758. while ((long int)rem->size() > helpwidth) {
  1759. // Find whitespace to split before helpwidth.
  1760. if (rem->at(helpwidth) == ' ') {
  1761. // If word ends exactly at helpwidth, then split after it.
  1762. pos = helpwidth;
  1763. } else {
  1764. // Otherwise, split occurs midword, so find whitespace before this word.
  1765. pos = rem->rfind(" ", helpwidth);
  1766. }
  1767. // Insert split string.
  1768. desc.insert(insertionIter, new std::string(*rem, 0, pos));
  1769. // Now skip any whitespace to start new line.
  1770. pos = rem->find_first_not_of(' ', pos);
  1771. rem->erase(0, pos);
  1772. }
  1773. if (rem->size())
  1774. desc.insert(insertionIter, rem);
  1775. else
  1776. delete rem;
  1777. }
  1778. }
  1779. usage.append(sortedOpts[i]);
  1780. if (layout != INTERLEAVE)
  1781. // Add whitespace between option names and description.
  1782. usage.append(pad - sortedOpts[i].size(), ' ');
  1783. else {
  1784. usage.append("\n");
  1785. usage.append(gutter, ' ');
  1786. }
  1787. if (desc.size() > 0) { // Crash fix by Bruce Shankle.
  1788. // First line already padded above (before calling SplitDelim) after option flag names.
  1789. cIter = desc.begin();
  1790. usage.append(**cIter);
  1791. usage.append("\n");
  1792. // Now inject the pad for each line.
  1793. for(++cIter; cIter != desc.end(); ++cIter) {
  1794. usage.append(pad, ' ');
  1795. usage.append(**cIter);
  1796. usage.append("\n");
  1797. }
  1798. if (this->doublespace) usage.append("\n");
  1799. for(cIter=desc.begin(); cIter != desc.end(); ++cIter)
  1800. delete *cIter;
  1801. desc.clear();
  1802. }
  1803. }
  1804. };
  1805. /* ################################################################### */
  1806. bool ezOptionParser::gotExpected(std::vector<std::string> & badOptions) {
  1807. int i,j;
  1808. for(i=0; i < (long int)groups.size(); ++i) {
  1809. OptionGroup *g = groups[i];
  1810. // If was set, ensure number of args is correct.
  1811. if (g->isSet) {
  1812. if ((g->expectArgs != 0) && g->args.empty()) {
  1813. badOptions.push_back(*g->flags[0]);
  1814. continue;
  1815. }
  1816. for(j=0; j < (long int)g->args.size(); ++j) {
  1817. if ((g->expectArgs != -1) && (g->expectArgs != (long int)g->args[j]->size()))
  1818. badOptions.push_back(*g->flags[0]);
  1819. }
  1820. }
  1821. }
  1822. return badOptions.empty();
  1823. };
  1824. /* ################################################################### */
  1825. bool ezOptionParser::gotRequired(std::vector<std::string> & badOptions) {
  1826. int i;
  1827. for(i=0; i < (long int)groups.size(); ++i) {
  1828. OptionGroup *g = groups[i];
  1829. // Simple case when required but user never set it.
  1830. if (g->isRequired && (!g->isSet)) {
  1831. badOptions.push_back(*g->flags[0]);
  1832. continue;
  1833. }
  1834. }
  1835. return badOptions.empty();
  1836. };
  1837. /* ################################################################### */
  1838. bool ezOptionParser::gotValid(std::vector<std::string> & badOptions, std::vector<std::string> & badArgs) {
  1839. int groupid, validatorid;
  1840. std::map< int, int >::iterator it;
  1841. for(it = groupValidators.begin(); it != groupValidators.end(); ++it) {
  1842. groupid = it->first;
  1843. validatorid = it->second;
  1844. if (validatorid < 0) continue;
  1845. OptionGroup *g = groups[groupid];
  1846. ezOptionValidator *v = validators[validatorid];
  1847. bool nextgroup = false;
  1848. for (int i = 0; i < (long int)g->args.size(); ++i) {
  1849. if (nextgroup) break;
  1850. std::vector< std::string* > * args = g->args[i];
  1851. for (int j = 0; j < (long int)args->size(); ++j) {
  1852. if (!v->isValid(args->at(j))) {
  1853. badOptions.push_back(*g->flags[0]);
  1854. badArgs.push_back(*args->at(j));
  1855. nextgroup = true;
  1856. break;
  1857. }
  1858. }
  1859. }
  1860. }
  1861. return badOptions.empty();
  1862. };
  1863. /* ################################################################### */
  1864. void ezOptionParser::parse(int argc, const char * argv[]) {
  1865. if (argc < 1) return;
  1866. /*
  1867. std::map<std::string,int>::iterator it;
  1868. for ( it=optionGroupIds.begin() ; it != optionGroupIds.end(); it++ )
  1869. std::cout << (*it).first << " => " << (*it).second << std::endl;
  1870. */
  1871. int i, k, firstOptIndex=0, lastOptIndex=0;
  1872. std::string s;
  1873. OptionGroup *g;
  1874. for(i=0; i < argc; ++i) {
  1875. s = argv[i];
  1876. if (optionGroupIds.count(s))
  1877. break;
  1878. }
  1879. firstOptIndex = i;
  1880. if (firstOptIndex == argc) {
  1881. // No flags encountered, so set last args.
  1882. this->firstArgs.push_back(new std::string(argv[0]));
  1883. for(k=1; k < argc; ++k)
  1884. this->lastArgs.push_back(new std::string(argv[k]));
  1885. return;
  1886. }
  1887. // Store initial args before opts appear.
  1888. for(k=0; k < i; ++k) {
  1889. this->firstArgs.push_back(new std::string(argv[k]));
  1890. }
  1891. for(; i < argc; ++i) {
  1892. s = argv[i];
  1893. if (optionGroupIds.count(s)) {
  1894. k = optionGroupIds[s];
  1895. g = groups[k];
  1896. g->isSet = 1;
  1897. g->parseIndex.push_back(i);
  1898. if (g->expectArgs) {
  1899. // Read ahead to get args.
  1900. ++i;
  1901. if (i >= argc) return;
  1902. g->args.push_back(new std::vector<std::string*>);
  1903. SplitDelim(argv[i], g->delim, g->args.back());
  1904. }
  1905. lastOptIndex = i;
  1906. }
  1907. }
  1908. // Scan for unknown opts/arguments.
  1909. for(i=firstOptIndex; i <= lastOptIndex; ++i) {
  1910. s = argv[i];
  1911. if (optionGroupIds.count(s)) {
  1912. k = optionGroupIds[s];
  1913. g = groups[k];
  1914. if (g->expectArgs) {
  1915. // Read ahead for args and skip them.
  1916. ++i;
  1917. }
  1918. } else {
  1919. unknownArgs.push_back(new std::string(argv[i]));
  1920. }
  1921. }
  1922. if ( lastOptIndex >= (argc-1) ) return;
  1923. // Store final args without flags.
  1924. for(k=lastOptIndex + 1; k < argc; ++k) {
  1925. this->lastArgs.push_back(new std::string(argv[k]));
  1926. }
  1927. };
  1928. /* ################################################################### */
  1929. void ezOptionParser::prettyPrint(std::string & out) {
  1930. char tmp[256];
  1931. int i,j,k;
  1932. out += "First Args:\n";
  1933. for(i=0; i < (long int)firstArgs.size(); ++i) {
  1934. sprintf(tmp, "%d: %s\n", i+1, firstArgs[i]->c_str());
  1935. out += tmp;
  1936. }
  1937. // Sort the option flag names.
  1938. int n = groups.size();
  1939. std::vector<std::string* > stringPtrs(n);
  1940. for(i=0; i < n; ++i) {
  1941. stringPtrs[i] = groups[i]->flags[0];
  1942. }
  1943. // Sort first flag of each group with other groups.
  1944. std::sort(stringPtrs.begin(), stringPtrs.end(), CmpOptStringPtr);
  1945. out += "\nOptions:\n";
  1946. OptionGroup *g;
  1947. for(i=0; i < n; ++i) {
  1948. g = get(stringPtrs[i]->c_str());
  1949. out += "\n";
  1950. // The flag names:
  1951. for(j=0; j < (long int)g->flags.size()-1; ++j) {
  1952. sprintf(tmp, "%s, ", g->flags[j]->c_str());
  1953. out += tmp;
  1954. }
  1955. sprintf(tmp, "%s:\n", g->flags.back()->c_str());
  1956. out += tmp;
  1957. if (g->isSet) {
  1958. if (g->expectArgs) {
  1959. if (g->args.empty()) {
  1960. sprintf(tmp, "%s (default)\n", g->defaults.c_str());
  1961. out += tmp;
  1962. } else {
  1963. for(k=0; k < (long int)g->args.size(); ++k) {
  1964. for(j=0; j < (long int)g->args[k]->size()-1; ++j) {
  1965. sprintf(tmp, "%s%c", g->args[k]->at(j)->c_str(), g->delim);
  1966. out += tmp;
  1967. }
  1968. sprintf(tmp, "%s\n", g->args[k]->back()->c_str());
  1969. out += tmp;
  1970. }
  1971. }
  1972. } else { // Set but no args expected.
  1973. sprintf(tmp, "Set\n");
  1974. out += tmp;
  1975. }
  1976. } else {
  1977. sprintf(tmp, "Not set\n");
  1978. out += tmp;
  1979. }
  1980. }
  1981. out += "\nLast Args:\n";
  1982. for(i=0; i < (long int)lastArgs.size(); ++i) {
  1983. sprintf(tmp, "%d: %s\n", i+1, lastArgs[i]->c_str());
  1984. out += tmp;
  1985. }
  1986. out += "\nUnknown Args:\n";
  1987. for(i=0; i < (long int)unknownArgs.size(); ++i) {
  1988. sprintf(tmp, "%d: %s\n", i+1, unknownArgs[i]->c_str());
  1989. out += tmp;
  1990. }
  1991. };
  1992. }
  1993. /* ################################################################### */
  1994. #endif /* EZ_OPTION_PARSER_H */