aboutsummaryrefslogtreecommitdiffstats
path: root/src/cmd/getopt.cpp
blob: 48d30b2f2ec4aea8442b307d7448ad3d5d77e84a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* (C) 2009 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "getopt.h"
#include <iostream>

void OptionParser::parse(char* argv[])
   {
   std::vector<std::string> args;
   for(int j = 1; argv[j]; j++)
      args.push_back(argv[j]);

   for(size_t j = 0; j != args.size(); j++)
      {
      std::string arg = args[j];

      if(arg == "help" || arg == "--help" || arg == "-h")
         return help(std::cout, argv[0]);

      if(arg.size() > 2 && arg[0] == '-' && arg[1] == '-')
         {
         const std::string opt_name = arg.substr(0, arg.find('='));

         arg = arg.substr(2);

         std::string::size_type mark = arg.find('=');
         OptionFlag opt = find_option(arg.substr(0, mark));

         if(opt.takes_arg())
            {
            if(mark == std::string::npos)
               throw std::runtime_error("Option " + opt_name +
                                        " requires an argument");

            std::string name = arg.substr(0, mark);
            std::string value = arg.substr(mark+1);

            options[name] = value;
            }
         else
            {
            if(mark != std::string::npos)
               throw std::runtime_error("Option " + opt_name +
                                        " does not take an argument");

            options[arg] = "";
            }
         }
      else
         leftover.push_back(arg);
      }
   }