opt2.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. #include "opt2.h"
  2. #include <util/generic/hash.h>
  3. #include <util/generic/utility.h>
  4. #include <util/generic/yexception.h>
  5. #include <util/str_stl.h>
  6. #include <stdio.h>
  7. #include <errno.h>
  8. #include <ctype.h>
  9. void Opt2::Clear() {
  10. Specs.clear();
  11. memset(SpecsMap, 0, sizeof(SpecsMap));
  12. Pos.clear();
  13. }
  14. void Opt2::Init(int argc, char* const* argv, const char* optspec, IntRange free_args_num, const char* long_alias) {
  15. Clear();
  16. Argc = argc;
  17. Argv = argv;
  18. HasErrors = false, BadPosCount = false, UnknownOption = 0, OptionMissingArg = 0;
  19. UnknownLongOption = nullptr;
  20. OptionWrongArg = 0, RequiredOptionMissing = 0;
  21. EatArgv(optspec, long_alias);
  22. MinArgs = Min<int>(free_args_num.Left, free_args_num.Right);
  23. MaxArgs = Max<int>(free_args_num.Left, free_args_num.Right);
  24. if (!HasErrors && MinArgs != -1 && ((int)Pos.size() < MinArgs || (int)Pos.size() > MaxArgs))
  25. BadPosCount = HasErrors = true;
  26. }
  27. void Opt2::EatArgv(const char* optspec, const char* long_alias) {
  28. // some flags
  29. bool require_order = false;
  30. if (*optspec == '+') {
  31. require_order = true;
  32. optspec++;
  33. }
  34. if (*optspec == '-')
  35. ythrow yexception() << "Flag '-' can not be used in Opt2's optspec";
  36. // step 1 - parse optspec
  37. for (const char* s = optspec; *s; s++) {
  38. if (SpecsMap[(ui8)*s])
  39. ythrow yexception() << "Symbol '" << *s << "' is met twice in Opt2's optspec";
  40. if (*s == '?' || *s == '-')
  41. ythrow yexception() << "Opt2: Symbol '" << *s << "' can not be used in optspec because it is reserved";
  42. Specs.push_back(Opt2Param());
  43. SpecsMap[(ui8)*s] = (ui8)Specs.size(); // actual index + 1
  44. Specs.back().opt = *s;
  45. if (s[1] == ':') {
  46. Specs.back().HasArg = true;
  47. if (s[2] == ':')
  48. ythrow yexception() << "Opt2 does not accept optional parameters (e.g. \"a::\") in optspec";
  49. s++;
  50. }
  51. }
  52. // long_alias has a form "long-name1=A,long-name2=B", etc.
  53. // This implementation is limited to aliasing a single long option
  54. // with single short option (extend it if you really need).
  55. THashMap<const char*, char> long2short;
  56. long2short["help"] = '?';
  57. long_alias = long_alias ? long_alias : "";
  58. alias_copy = long_alias;
  59. for (char* s = alias_copy.begin(); s && *s;) {
  60. char* eq = strchr(s, '=');
  61. char* comma = strchr(s, ',');
  62. if (comma)
  63. *comma = 0;
  64. if (!eq || (comma && comma < eq))
  65. ythrow yexception() << "Opt2, long_alias: '=' is expected after " << s;
  66. *eq++ = 0;
  67. if (!*eq || eq[1])
  68. ythrow yexception() << "Opt2, long_alias: single letter must be assigned to " << s;
  69. if (!SpecsMap[(ui8)*eq])
  70. ythrow yexception() << "Opt2, long_alias: trying to assign unknown option '" << *eq << "' to " << s;
  71. Opt2Param& p = Specs[SpecsMap[(ui8)*eq] - 1];
  72. // If several long options aliased to some letter, only last one is shown in usage
  73. p.LongOptName = s;
  74. if (long2short.find(s) != long2short.end())
  75. ythrow yexception() << "Opt2, long_alias: " << s << " specified twice";
  76. long2short[s] = *eq;
  77. s = comma ? comma + 1 : nullptr;
  78. }
  79. if (Argc < 1) {
  80. HasErrors = true;
  81. return;
  82. }
  83. // step 2 - parse argv
  84. int ind = 1;
  85. for (; ind != Argc; ind++) {
  86. if (*Argv[ind] != '-') {
  87. if (require_order) // everything now goes to Pos
  88. break;
  89. Pos.push_back(Argv[ind]);
  90. continue;
  91. }
  92. const char* s = Argv[ind] + 1;
  93. if (*s == '-') {
  94. if (!*++s) { // `--' terminates the list of options
  95. ind++;
  96. break;
  97. }
  98. // long option always spans one argv (--switch or --option-name=value)
  99. const char* eq = strchr(s, '=');
  100. TString lname(s, eq ? (size_t)(eq - s) : (size_t)strlen(s));
  101. THashMap<const char*, char>::iterator i = long2short.find(lname.data());
  102. if (i == long2short.end()) {
  103. UnknownLongOption = strdup(lname.data()); // free'd in AutoUsage()
  104. HasErrors = true;
  105. return;
  106. }
  107. if (i->second == '?') {
  108. UnknownOption = '?';
  109. HasErrors = true;
  110. continue;
  111. }
  112. Opt2Param& p = Specs[SpecsMap[(ui8)i->second] - 1];
  113. p.IsFound = true;
  114. if (p.HasArg && !eq) {
  115. HasErrors = true;
  116. OptionMissingArg = p.opt; // short option, indeed
  117. return;
  118. }
  119. if (!p.HasArg && eq) {
  120. HasErrors = true;
  121. OptionWrongArg = p.opt; // short option, indeed
  122. return;
  123. }
  124. if (eq)
  125. p.ActualValue.push_back(eq + 1);
  126. continue;
  127. }
  128. for (; *s; s++) {
  129. if (!SpecsMap[(ui8)*s]) {
  130. UnknownOption = *s;
  131. HasErrors = true;
  132. if (*s == '?')
  133. continue;
  134. return;
  135. }
  136. Opt2Param& p = Specs[SpecsMap[(ui8)*s] - 1];
  137. p.IsFound = true;
  138. if (p.HasArg) {
  139. if (s[1])
  140. p.ActualValue.push_back(s + 1);
  141. else {
  142. ind++;
  143. if (ind == Argc) {
  144. HasErrors = true;
  145. OptionMissingArg = *s;
  146. p.IsFound = false;
  147. return;
  148. }
  149. p.ActualValue.push_back(Argv[ind]);
  150. }
  151. break;
  152. }
  153. }
  154. }
  155. for (; ind != Argc; ind++)
  156. Pos.push_back(Argv[ind]);
  157. }
  158. Opt2Param& Opt2::GetInternal(char opt, const char* defValue, const char* helpUsage, bool requred) {
  159. if (!SpecsMap[(ui8)opt])
  160. ythrow yexception() << "Unspecified option character '" << opt << "' asked from Opt2::Get";
  161. Opt2Param& p = Specs[SpecsMap[(ui8)opt] - 1];
  162. p.DefValue = defValue;
  163. p.HelpUsage = helpUsage;
  164. p.IsRequired = requred;
  165. if (!p.IsFound && requred && !HasErrors) {
  166. RequiredOptionMissing = opt;
  167. HasErrors = true;
  168. }
  169. return p;
  170. }
  171. // For options with parameters
  172. const char* Opt2::Arg(char opt, const char* help, const char* def, bool required) {
  173. Opt2Param& p = GetInternal(opt, def, help, required);
  174. if (!p.HasArg)
  175. ythrow yexception() << "Opt2::Arg called for '" << opt << "' which is an option without argument";
  176. return p.IsFound ? p.ActualValue.empty() ? nullptr : p.ActualValue.back() : def;
  177. }
  178. // For options with parameters
  179. const char* Opt2::Arg(char opt, const char* help, TString def, bool required) {
  180. Opt2Param& p = GetInternal(opt, nullptr, help, required);
  181. if (!p.HasArg)
  182. ythrow yexception() << "Opt2::Arg called for '" << opt << "' which is an option without argument";
  183. p.DefValueStr = def;
  184. p.DefValue = p.DefValueStr.begin();
  185. return p.IsFound ? p.ActualValue.empty() ? nullptr : p.ActualValue.back() : p.DefValue;
  186. }
  187. // Options with parameters that can be specified several times
  188. const TVector<const char*>& Opt2::MArg(char opt, const char* help) {
  189. Opt2Param& p = GetInternal(opt, nullptr, help, false);
  190. p.MultipleUse = true;
  191. if (!p.HasArg)
  192. ythrow yexception() << "Opt2::Arg called for '" << opt << "' which is an option without argument";
  193. return p.ActualValue;
  194. }
  195. /// For options w/o parameters
  196. bool Opt2::Has(char opt, const char* help) {
  197. Opt2Param& p = GetInternal(opt, nullptr, help, false);
  198. if (p.HasArg)
  199. ythrow yexception() << "Opt2::Has called for '" << opt << "' which is an option with argument";
  200. return p.IsFound;
  201. }
  202. // Get() + strtol, may set up HasErrors
  203. long Opt2::Int(char opt, const char* help, long def, bool required) {
  204. Opt2Param& p = GetInternal(opt, (char*)(uintptr_t)def, help, required);
  205. if (!p.HasArg)
  206. ythrow yexception() << "Opt2::Int called for '" << opt << "' which is an option without argument";
  207. p.IsNumeric = true;
  208. if (!p.IsFound || p.ActualValue.empty() || !p.ActualValue.back())
  209. return def;
  210. char* e;
  211. long rv = strtol(p.ActualValue.back(), &e, 10);
  212. if (e == p.ActualValue.back() || *e) {
  213. OptionWrongArg = opt;
  214. HasErrors = true;
  215. }
  216. return rv;
  217. }
  218. // Get() + strtoul, may set up HasErrors
  219. unsigned long Opt2::UInt(char opt, const char* help, unsigned long def, bool required) {
  220. Opt2Param& p = GetInternal(opt, (char*)(uintptr_t)def, help, required);
  221. if (!p.HasArg)
  222. ythrow yexception() << "Opt2::UInt called for '" << opt << "' which is an option without argument";
  223. p.IsNumeric = true;
  224. if (!p.IsFound || p.ActualValue.empty() || !p.ActualValue.back())
  225. return def;
  226. char* e;
  227. unsigned long rv = strtoul(p.ActualValue.back(), &e, 10);
  228. if (e == p.ActualValue.back() || *e) {
  229. OptionWrongArg = opt;
  230. HasErrors = true;
  231. }
  232. return rv;
  233. }
  234. // Add user defined error message and set error flag
  235. void Opt2::AddError(const char* message) {
  236. HasErrors = true;
  237. if (message)
  238. UserErrorMessages.push_back(message);
  239. }
  240. int Opt2::AutoUsage(const char* free_arg_names) {
  241. if (!HasErrors)
  242. return 0;
  243. FILE* where = UnknownOption == '?' ? stdout : stderr;
  244. char req_str[256], nreq_str[256];
  245. int req = 0, nreq = 0;
  246. for (int n = 0; n < (int)Specs.size(); n++)
  247. if (Specs[n].IsRequired)
  248. req_str[req++] = Specs[n].opt;
  249. else
  250. nreq_str[nreq++] = Specs[n].opt;
  251. req_str[req] = 0, nreq_str[nreq] = 0;
  252. const char* prog = strrchr(Argv[0], LOCSLASH_C);
  253. prog = prog ? prog + 1 : Argv[0];
  254. fprintf(where, "Usage: %s%s%s%s%s%s%s%s\n", prog, req ? " -" : "", req_str,
  255. nreq ? " [-" : "", nreq_str, nreq ? "]" : "",
  256. free_arg_names && *free_arg_names ? " " : "", free_arg_names);
  257. for (auto& spec : Specs) {
  258. const char* hlp = !spec.HelpUsage.empty() ? spec.HelpUsage.data() : spec.HasArg ? "<arg>" : "";
  259. if (!spec.HasArg || spec.IsRequired)
  260. fprintf(where, " -%c %s\n", spec.opt, hlp);
  261. else if (!spec.IsNumeric)
  262. fprintf(where, " -%c %s [Default: %s]\n", spec.opt, hlp, spec.DefValue);
  263. else
  264. fprintf(where, " -%c %s [Def.val: %li]\n", spec.opt, hlp, (long)(uintptr_t)spec.DefValue);
  265. if (spec.LongOptName)
  266. fprintf(where, " --%s%s - same as -%c\n", spec.LongOptName, spec.HasArg ? "=<argument>" : "", spec.opt);
  267. }
  268. if (OptionMissingArg)
  269. fprintf(where, " *** Option '%c' is missing required argument\n", OptionMissingArg);
  270. if (OptionWrongArg)
  271. fprintf(where, " *** Incorrect argument for option '%c'\n", OptionWrongArg);
  272. if (UnknownOption && UnknownOption != '?')
  273. fprintf(where, " *** Unknown option '%c'\n", UnknownOption);
  274. if (UnknownLongOption) {
  275. fprintf(where, " *** Unknown long option '%s'\n", UnknownLongOption);
  276. free(UnknownLongOption);
  277. UnknownLongOption = nullptr;
  278. }
  279. if (RequiredOptionMissing)
  280. fprintf(where, " *** Required option '%c' missing\n", RequiredOptionMissing);
  281. if (BadPosCount && MinArgs != MaxArgs)
  282. fprintf(where, " *** %i free argument(s) supplied, expected %i to %i\n", (int)Pos.size(), MinArgs, MaxArgs);
  283. if (BadPosCount && MinArgs == MaxArgs)
  284. fprintf(where, " *** %i free argument(s) supplied, expected %i\n", (int)Pos.size(), MinArgs);
  285. for (const auto& userErrorMessage : UserErrorMessages)
  286. fprintf(where, " *** %s\n", userErrorMessage.data());
  287. return UnknownOption == '?' ? 1 : 2;
  288. }
  289. void Opt2::AutoUsageErr(const char* free_arg_names) {
  290. if (AutoUsage(free_arg_names))
  291. exit(1);
  292. }
  293. #ifdef OPT2_TEST
  294. // TODO: convert it to unittest
  295. bool opt2_ut_fail = false, opt_ut_verbose = false;
  296. const char* ut_optspec;
  297. int ut_real(TString args, bool err_exp, const char* A_exp, int b_exp, bool a_exp, const char* p1_exp, const char* p2_exp) {
  298. char* argv[32];
  299. int argc = sf(' ', argv, args.begin());
  300. Opt2 opt(argc, argv, ut_optspec, 2, "option-1=A,option-2=a,");
  301. const char* A = opt.Arg('A', "<qqq> - blah");
  302. int b = opt.Int('b', "<rrr> - blah", 2);
  303. bool a = opt.Has('a', "- blah");
  304. /*const char *C = */ opt.Arg('C', "<ccc> - blah", 0);
  305. if (opt_ut_verbose)
  306. opt.AutoUsage("");
  307. if (opt.HasErrors != err_exp)
  308. return 1;
  309. if (err_exp)
  310. return false;
  311. if (!A && A_exp || A && !A_exp || A && A_exp && strcmp(A, A_exp))
  312. return 2;
  313. if (b != b_exp)
  314. return 3;
  315. if (a != a_exp)
  316. return 4;
  317. if (strcmp(opt.Pos[0], p1_exp))
  318. return 5;
  319. if (strcmp(opt.Pos[1], p2_exp))
  320. return 6;
  321. return false;
  322. }
  323. void ut(const char* args, bool err_exp, const char* A_exp, int b_exp, bool a_exp, const char* p1_exp, const char* p2_exp) {
  324. if (opt_ut_verbose)
  325. fprintf(stderr, "Testing: %s\n", args);
  326. if (int rv = ut_real(args, err_exp, A_exp, b_exp, a_exp, p1_exp, p2_exp)) {
  327. opt2_ut_fail = true;
  328. fprintf(stderr, "Test %i failed for: %s\n", rv, args);
  329. } else {
  330. if (opt_ut_verbose)
  331. fprintf(stderr, "OK\n");
  332. }
  333. }
  334. int main(int argc, char* argv[]) {
  335. Opt2 opt(argc, argv, "v", 0);
  336. opt_ut_verbose = opt.Has('v', "- some verboseness");
  337. opt.AutoUsageErr("");
  338. ut_optspec = "A:ab:C:";
  339. ut("prog -A argA -a -b 22 -C argC Pos1 Pos2", false, "argA", 22, true, "Pos1", "Pos2");
  340. ut("prog Pos1 -A argA -a -C argC Pos2", false, "argA", 2, true, "Pos1", "Pos2");
  341. ut("prog -A argA Pos1 -b22 Pos2 -C argC", false, "argA", 22, false, "Pos1", "Pos2");
  342. ut("prog -A argA Pos1 -b 22 Pos2 -C", true, "argA", 22, false, "Pos1", "Pos2");
  343. ut("prog -A argA -a -b 22 -C Pos1 Pos2", true, "argA", 22, true, "Pos1", "Pos2");
  344. ut("prog -A argA -a -b two -C argC Pos1 Pos2", true, "argA", 2, true, "Pos1", "Pos2");
  345. ut("prog -a -b 22 -C argC Pos1 Pos2", true, "argA", 22, true, "Pos1", "Pos2");
  346. ut("prog Pos1 --option-1=argA -a -C argC Pos2", false, "argA", 2, true, "Pos1", "Pos2");
  347. ut("prog Pos1 -A argA --option-1 -a -C argC Pos2", true, "argA", 2, true, "Pos1", "Pos2");
  348. ut("prog -A argA --option-2 -b -22 -C argC Pos1 Pos2", false, "argA", -22, true, "Pos1", "Pos2");
  349. ut("prog -A argA --option-2 -b -22 -- -C argC", false, "argA", -22, true, "-C", "argC");
  350. ut("prog -A argA --option-2=1 -b -22 -C argC Pos1 Pos2", true, "argA", -22, true, "Pos1", "Pos2");
  351. ut_optspec = "+A:ab:C:";
  352. ut("prog -A argA --option-2 v1 -C", false, "argA", 2, true, "v1", "-C");
  353. ut("prog -A argA --option-2 v1 -C argC", true, "argA", 2, true, "v1", "-C");
  354. if (!opt2_ut_fail)
  355. fprintf(stderr, "All OK\n");
  356. return opt2_ut_fail;
  357. }
  358. #endif // OPT2_TEST