summaryrefslogtreecommitdiffhomepage
path: root/programopts.cpp
blob: 81f1be95078517391d354f376dcfe138d939317e (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "programopts.h"

#include <algorithm>
#include <iterator>

using namespace std::string_literals;

namespace {
 struct PrefixCmp
 {
  bool operator()(const std::string& lhs, const std::string& rhs) const
  {
   return !(lhs.starts_with(rhs) || rhs.starts_with(lhs)) && lhs < rhs;
  }
 };
}

struct Reichwein::ProgramOpts::impl
{
 int m_argc;
 char** m_argv;
 std::string m_programName;
 std::vector<std::string> m_parameters;
 std::map<std::string, std::function<bool(const std::string&)>, PrefixCmp> m_option_prefixes;
};

Reichwein::ProgramOpts::ProgramOpts(int argc, char* argv[], std::map<std::string, std::function<bool(const std::string&)>>& option_prefixes):
 m_pimpl(std::make_unique<impl>())
{
 m_pimpl->m_argc = argc;
 m_pimpl->m_argv = argv;
 if (m_pimpl->m_argc >= 1)
  m_pimpl->m_programName = m_pimpl->m_argv[0];
 //std::copy(option_prefixes.begin(), option_prefixes.end(), std::inserter(m_pimpl->m_option_prefixes, std::next(m_pimpl->m_option_prefixes.begin())));
}

Reichwein::ProgramOpts::~ProgramOpts()
{
}

void Reichwein::ProgramOpts::process()
{
 for (int i = 1; i < m_pimpl->m_argc; i++) {
  std::string arg{ m_pimpl->m_argv[i] };
  if (arg.size() == 0)
   throw std::runtime_error("Empty option #"s + std::to_string(i));

  if (arg[0] != '-') { // non-option parameter
   m_pimpl->m_parameters.push_back(arg);
  } else {
   auto prefix_iterator = m_pimpl->m_option_prefixes.find(arg);
   if (prefix_iterator == m_pimpl->m_option_prefixes.end())
    throw std::runtime_error("Unknown option: "s + arg);
   auto& [prefix, f] = *prefix_iterator;
   std::string optional_parameter;
   bool parameter_provided{ false };

   if (prefix.size() < arg.size()) {
    optional_parameter = arg.substr(prefix.size());
   } else {
    if (i < m_pimpl->m_argc - 1)
     optional_parameter = m_pimpl->m_argv[i + 1];
    if (optional_parameter.size() > 0 && optional_parameter[0] == '-')
     optional_parameter = "";
    else
     parameter_provided = true;
   }
   bool parameter_consumed = f(optional_parameter); // call the function from the map
   if (parameter_provided && parameter_consumed)
    i++; // skip parameter
  }
 }
}

std::string Reichwein::ProgramOpts::programName()
{
 return m_pimpl->m_programName;
}

std::vector<std::string> Reichwein::ProgramOpts::nonOptionArguments()
{
 return m_pimpl->m_parameters;
}