summaryrefslogtreecommitdiffstats
path: root/shargs.hpp
blob: 317ab1e664767b23bf205dff105911cb0c5eb948 (plain) (blame)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#ifndef SHARGS_HPP
#define SHARGS_HPP 1

#include <string>
#include <vector>
#include <memory>
#include <optional>
#include <string_view>
#include <sstream>
#include <functional>

class OptionParser
{
private:
    using arg_iterator = std::vector<std::string_view>::iterator;
    using option_return = std::optional<arg_iterator>;
    using unknown_callback = std::function<void(std::string_view)>;

    struct Option {
        const std::string lform;
        const char sform;

        Option(const std::string &l, const char s) : lform(l), sform(s) {}

        /** Given an iterator to the arg after this, fetch arguments and stop
         * when another option switch is encountered.
         * When fetch fails, return the current it.
         * When fetch encounters the end, return nullopt.
         * @return Iterator to next argument
         * */
        virtual option_return parse(arg_iterator it, arg_iterator end) = 0;
    };

    template<typename T>
    struct TypedOption : public Option {
        T &flag;
        TypedOption(const std::string &l, const char s, T &f) :
            Option(l, s), flag(f) {}

         /** Given an iterator to the arg after this, fetch an argument or stop
         * when an option switch is encountered.
         * When fetch is stopped prematurely, return the current it.
         * When fetch encounters the end, return nullopt.
         * @return Iterator to next argument
         * */
        virtual option_return parse(arg_iterator it, arg_iterator end) {
            if(it == end) return std::nullopt;
            std::string_view itval = *it;

            if(itval[0] == '-') return it;

            std::stringstream flagstream;
            flagstream << itval;
            flagstream >> flag;
            return ++it;
        }
    };

    template<typename T>
    struct MultipleOption : public Option {
        std::vector<T> &args;
        MultipleOption(const std::string &l, const char s, std::vector<T> &a) :
            Option(l, s), args(a) {}

         /** Given an iterator to the arg after this, fetch multiple arguments
         * and stop when an option switch is encountered.
         * When fetch is stopped prematurely, return the current it.
         * When fetch encounters the end, return nullopt.
         * @return Iterator to next argument
         * */
        option_return parse(arg_iterator it, arg_iterator end)
        {
            if(it == end) return end;
            while(it != end && (*it)[0] != '-') {
                std::string_view itval = *it;
                std::stringstream argstream;
                T val;

                argstream << itval;
                argstream >> val;
                args.emplace_back(val);
                it++;
            }
            return it;
        }
    };

    template<typename T>
    struct FlagOption : public TypedOption<T> {
        const T set;
        FlagOption(const std::string &l, const char s, T &f, const T set) :
            TypedOption<T>(l, s, f), set(set) {}

         /** Given an iterator to the arg after this, set the flag and return it.
         * @return Iterator to next argument.
         * */
        option_return parse(arg_iterator it, arg_iterator end) 
        {
            this->flag = set;
            return it;
        }
    };

    std::vector<std::unique_ptr<Option>> m_options;
    unknown_callback m_unknown_callback;
public:

    /** Register an option that takes 1 naked argument.
     * @param longform Full name of the option. preceeded by '--'.
     * @param shortform Short name of the option. preceeded by '-'.
     * @param flag Variable to fill when option is encountered.
     * @return self for chaining.
     * */
    template<typename T>
    inline OptionParser &
    add_option_argument(const std::string &longform,
                        char shortform,
                        T &flag)
    {
        m_options.emplace_back(
                std::make_unique<TypedOption<T>>(longform, shortform, flag));
        return *this;
    }

    /** Register an option that sets a variable when encountered.
     * @param longform Full name of the option. preceeded by '--'.
     * @param shortform Short name of the option. preceeded by '-'.
     * @param flag Variable to fill when option is encountered.
     * @param set Value to fill into flag.
     * @return self for chaining.
     * */
    template<typename T>
    inline OptionParser &
    add_option_flag(const std::string &longform, 
                    char shortform, 
                    T &flag,
                    const T set)
    {
        m_options.emplace_back(
                std::make_unique<FlagOption<T>>(longform, shortform, flag, set));
        return *this;
    }

    /** Register an option that takes multiple naked arguments
     * @param longform Full name of the option. preceeded by '--'.
     * @param shortform Short name of the option. preceeded by '-'.
     * @param flag Vector fill with naked argumens.
     * @return self for chaining.
     * */
    template<typename T>
    inline OptionParser &
    add_option_multiple(const std::string &longform,
                        char shortform,
                        std::vector<T> &args)
    {
        m_options.emplace_back(
                std::make_unique<MultipleOption<T>>(longform, shortform, args));
        return *this;
    }

    /** Add a callback function when parser encounters a flagged argument without
     * a known option.
     * @param func Callback to call.
     * */
    inline void
    on_unknown(unknown_callback func)
    {
        m_unknown_callback = func;
    }

    /** Loop through argv, isolating any naked args and parsing those with an
     * option switch ('-' or '--').
     * If the args list is empty, it will return an empty vector.
     * @param argc Number of arguments passed to the program (provided by main)
     * @param argv NULL-terminated array of string pointers. (provided by main)
     * @return Vector of all arguments which were not eaten by options.
     * */
    std::vector<std::string> parse(int argc, char **argv)
    {
        /* Convert argc, argv into vector of string_view. */
        if(argc <= 1) return std::vector<std::string>();
        std::vector<std::string_view> args(argc - 1);
        for(size_t i = 1; i < argc; i++) {
            args[i - 1] = std::string_view(argv[i]);
        }

        /* Fetch iterator for looping through passed values */
        arg_iterator argit = args.begin();

        /* We want to notify the program if the user input any naked values or
         * passed arguments we don't know. */
        std::vector<std::string> naked;
        std::vector<std::string_view> unknown;

        while(argit != args.end()) {
            std::vector<std::vector<std::unique_ptr<Option>>::iterator> to_parse;
            std::string_view arg = *argit;
            if(arg[0] != '-') {
                naked.emplace_back(arg);
                argit++;
                continue;
            }

            auto optionsit = m_options.begin();
            if(arg[1] == '-') {
                /* Look through longform names. */
                arg.remove_prefix(2);
                for(; optionsit != m_options.end(); optionsit++) {
                    if((*optionsit)->lform.empty()) continue;
                    if((*optionsit)->lform == arg) {
                        to_parse.emplace_back(optionsit);
                        break;
                    }
                }
                if(optionsit == m_options.end()) {
                    unknown.emplace_back(*argit);
                }
            }else{
                /* Look through shortform names.
                 * The user should be able to pass as many shortform args
                 * in one switch as they want. */
                arg.remove_prefix(1);
                for(size_t c = 0; c < arg.size(); c++) {

                    /* If the argument is unknown, add it to the unknown list. */
                    bool valid = false;
                    /* Shortform names have arbitrary flags, so we search
                     * through each character. */
                    for(optionsit = m_options.begin(); 
                        optionsit != m_options.end();
                        optionsit++) {
                        /* Shortform name matches, add opt to to_parse. */
                        if(arg[c] == (*optionsit)->sform) {
                            valid = true;
                            to_parse.emplace_back(optionsit);
                            break;
                        }
                    }

                    if(!valid) {
                        unknown.emplace_back((*argit).substr(c + 1, 1));
                    }
                }
            }

            /* Parse all options in to_parse. */
            argit = argit + 1;
            for(auto it = to_parse.begin(); it != to_parse.end(); it++) {
                auto parse_ret = (*(*it))->parse(argit, args.end());
                /* Parsing encountered args.end()*/
                if(parse_ret == std::nullopt) {
                    return naked;
                }
                argit = parse_ret.value();
            }
        }

        /* Go through all unknown args */
        if(m_unknown_callback) {
            for(auto it : unknown) {
                m_unknown_callback(it);
            }
        }

        return naked;
    }
};

#endif