summaryrefslogtreecommitdiff
path: root/src/parameters_parser.cc
blob: 233f6a3fccdefc2698e208e2e9568b134898521d (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
85
86
87
88
89
#include "parameters_parser.hh"

namespace Kakoune
{

ParametersParser::ParametersParser(const ParameterList& params,
                                   std::unordered_map<String, bool> options)
    : m_params(params),
      m_options(std::move(options))
{
    bool only_pos = false;
    for (size_t i = 0; i < params.size(); ++i)
    {
        if (params[i] == "--")
            only_pos = true;
        else if (not only_pos and params[i][0] == '-')
        {
            auto it = m_options.find(params[i].substr(1_byte));
            if (it == m_options.end())
                throw unknown_option(params[i]);

            if (it->second)
            {
                ++i;
                if (i == params.size() or params[i][0] == '-')
                   throw missing_option_value(params[i]);
            }
        }
        else
            m_positional_indices.push_back(i);
    }
}

bool ParametersParser::has_option(const String& name) const
{
    assert(m_options.find(name) != m_options.end());
    for (auto& param : m_params)
    {
        if (param[0] == '-' and param.substr(1_byte) == name)
            return true;

        if (param == "--")
            break;
    }
    return false;
}

const String& ParametersParser::option_value(const String& name) const
{
#ifdef KAK_DEBUG
    auto it = m_options.find(name);
    assert(it != m_options.end());
    assert(it->second == true);
#endif

    for (size_t i = 0; i < m_params.size(); ++i)
    {
        if (m_params[i][0] == '-' and m_params[i].substr(1_byte) == name)
            return m_params[i+1];

        if (m_params[i] == "--")
            break;
    }
    static String empty;
    return empty;
}

size_t ParametersParser::positional_count() const
{
    return m_positional_indices.size();
}

const String& ParametersParser::operator[] (size_t index) const
{
    assert(index < positional_count());
    return m_params[m_positional_indices[index]];
}

ParametersParser::iterator ParametersParser::begin() const
{
    return iterator(*this, 0);
}

ParametersParser::iterator ParametersParser::end() const
{
    return iterator(*this, m_positional_indices.size());
}

}