summaryrefslogtreecommitdiff
path: root/src/args.cc
blob: 17949414c4de6b9f5af0d46cddd6b89c7b5ee86f (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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#include "args.hh"

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <format>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

namespace {

std::string kEmpty;

class OptionImpl : public Args::OptionArgument {
 public:
  enum Type : uint8_t {
    NoArgument,
    RequiredArgument,
    OptionalArgument,
  };

  OptionImpl(Type type, char shortname, std::string longname, std::string arg,
             std::string help)
      : type(type),
        shortname(shortname),
        longname(std::move(longname)),
        arg(std::move(arg)),
        help(std::move(help)) {}

  const Type type;
  const char shortname;
  const std::string longname;
  const std::string arg;
  const std::string help;

  [[nodiscard]] bool is_set() const override { return is_set_; }

  [[nodiscard]] bool has_argument() const override {
    return value_.has_value();
  }

  [[nodiscard]] const std::string& argument() const override {
    if (value_.has_value())
      return value_.value();
    assert(false);
    return kEmpty;
  }

  void clear() {
    is_set_ = false;
    value_.reset();
  }

  void set_argument(std::string value) {
    assert(type == Type::RequiredArgument || type == Type::OptionalArgument);
    is_set_ = true;
    value_ = std::move(value);
  }

  void set_no_argument() {
    assert(type == Type::NoArgument || type == Type::OptionalArgument);
    is_set_ = true;
    value_.reset();
  }

 private:
  bool is_set_{false};
  std::optional<std::string> value_;
};

class ArgsImpl : public Args {
 public:
  explicit ArgsImpl(std::string prgname) : prgname_(std::move(prgname)) {}

  std::shared_ptr<Option> option(char shortname, std::string longname,
                                 std::string help) override {
    auto opt = std::make_shared<OptionImpl>(
        OptionImpl::Type::NoArgument, shortname, std::move(longname),
        /* arg */ std::string(), std::move(help));
    add(opt);
    return opt;
  }

  std::shared_ptr<OptionArgument> option_argument(char shortname,
                                                  std::string longname,
                                                  std::string arg,
                                                  std::string help,
                                                  bool required) override {
    auto opt = std::make_shared<OptionImpl>(
        required ? OptionImpl::Type::RequiredArgument
                 : OptionImpl::Type::OptionalArgument,
        shortname, std::move(longname), std::move(arg), std::move(help));
    add(opt);
    return opt;
  }

  bool run(int argc, char** argv,
           std::vector<std::string_view>* arguments = nullptr) override {
    last_error_.clear();
    for (auto& opt : options_) {
      opt->clear();
    }

    std::string_view prgname;
    if (prgname_.empty()) {
      if (argc > 0)
        prgname = argv[0];
    } else {
      prgname = prgname_;
    }

    for (int a = 1; a < argc; ++a) {
      assert(argv[a]);
      if (argv[a][0] == '-' && argv[a][1] != '\0') {
        if (argv[a][1] == '-') {
          // long option
          size_t eq = 2;
          while (argv[a][eq] != '=' && argv[a][eq] != '\0')
            ++eq;
          size_t end = eq;
          while (argv[a][end] != '\0')
            ++end;

          if (end == 2) {
            // "--", no more options signal
            if (arguments) {
              for (++a; a < argc; ++a)
                arguments->emplace_back(argv[a]);
            }
            break;
          }

          auto name = std::string_view(argv[a] + 2, eq - 2);
          auto it = long_.find(name);
          if (it == long_.end()) {
            last_error_ =
                std::format("{}: unrecognized option '--{}'", prgname, name);
            return false;
          }
          auto& opt = options_[it->second];

          if (eq < end) {
            // long option with argument after equal sign
            switch (opt->type) {
              case OptionImpl::Type::NoArgument:
                last_error_ =
                    std::format("{}: option '--{}' doesn't allow an argument",
                                prgname, name);
                return false;
              case OptionImpl::Type::RequiredArgument:
              case OptionImpl::Type::OptionalArgument:
                opt->set_argument(
                    std::string(argv[a] + eq + 1, end - (eq + 1)));
                break;
            }
          } else {
            switch (opt->type) {
              case OptionImpl::Type::NoArgument:
              case OptionImpl::Type::OptionalArgument:
                opt->set_no_argument();
                break;
              case OptionImpl::Type::RequiredArgument:
                if (++a >= argc) {
                  last_error_ = std::format(
                      "{}: option '--{}' requires an argument", prgname, name);
                  return false;
                }
                opt->set_argument(argv[a]);
                break;
            }
          }
        } else {
          // short options
          char* current = argv[a] + 1;
          for (; *current; ++current) {
            auto it = short_.find(*current);
            if (it == short_.end()) {
              last_error_ =
                  std::format("{}: invalid option -- '{}'", prgname, *current);
              return false;
            }

            auto& opt = options_[it->second];
            switch (opt->type) {
              case OptionImpl::Type::NoArgument:
              case OptionImpl::Type::OptionalArgument:
                opt->set_no_argument();
                break;
              case OptionImpl::Type::RequiredArgument:
                if (++a >= argc) {
                  last_error_ =
                      std::format("{}: option requires an argument -- '{}'",
                                  prgname, *current);
                  return false;
                }
                opt->set_argument(argv[a]);
                break;
            }
          }
        }
      } else {
        if (arguments)
          arguments->emplace_back(argv[a]);
      }
    }
    return true;
  }

  void print_error(std::ostream& out) const override {
    if (last_error_.empty())
      return;

    out << last_error_ << '\n';
  }

  void print_help(std::ostream& out, uint32_t width = 79) const override {
    if (options_.empty())
      return;

    uint32_t indent = 0;
    const uint32_t max_need = width / 2;
    std::vector<uint32_t> option_need;
    for (auto const& opt : options_) {
      uint32_t need;
      if (opt->longname.empty()) {
        need = 4;  // -O
        switch (opt->type) {
          case OptionImpl::Type::NoArgument:
          case OptionImpl::Type::OptionalArgument:
            break;
          case OptionImpl::Type::RequiredArgument:
            need += 1 + (opt->arg.empty() ? 3 : opt->arg.size());
            break;
        }
      } else {
        need = 8 + opt->longname.size();  // -O, --option
        switch (opt->type) {
          case OptionImpl::Type::NoArgument:
            break;
          case OptionImpl::Type::RequiredArgument:
            // =ARG
            need += 1 + (opt->arg.empty() ? 3 : opt->arg.size());
            break;
          case OptionImpl::Type::OptionalArgument:
            // [=ARG]
            need += 3 + (opt->arg.empty() ? 3 : opt->arg.size());
            break;
        }
      }
      need += 2;  // margin

      option_need.emplace_back(need);
      if (need <= max_need) {
        indent = std::max(indent, need);
      }
    }

    print_wrap(out, width, /* indent */ 0,
               "Mandatory arguments to long options"
               " are mandatory for short options too.");
    auto need_it = option_need.begin();
    for (auto const& opt : options_) {
      if (opt->longname.empty()) {
        out << "  -" << opt->shortname;
        switch (opt->type) {
          case OptionImpl::Type::NoArgument:
          case OptionImpl::Type::OptionalArgument:
            break;
          case OptionImpl::Type::RequiredArgument:
            out << " " << (opt->arg.empty() ? "ARG" : opt->arg);
            break;
        }
      } else {
        if (opt->shortname != '\0') {
          out << "  -" << opt->shortname << ", --";
        } else {
          out << "      --";
        }
        out << opt->longname;
        switch (opt->type) {
          case OptionImpl::Type::NoArgument:
            break;
          case OptionImpl::Type::RequiredArgument:
            out << "=" << (opt->arg.empty() ? "ARG" : opt->arg);
            break;
          case OptionImpl::Type::OptionalArgument:
            out << "=[" << (opt->arg.empty() ? "ARG" : opt->arg) << ']';
            break;
        }
      }

      auto need = *need_it++;
      if (need > max_need) {
        out << '\n';
        if (!opt->help.empty()) {
          print_wrap(out, width, 0, opt->help);
        }
      } else {
        if (opt->help.empty()) {
          out << '\n';
        } else {
          out << "  ";  // add margin, already included in need
          while (need++ < indent)
            out << ' ';
          print_wrap(out, width, indent, opt->help);
        }
      }
    }
  }

 private:
  void add(std::shared_ptr<OptionImpl> opt) {
    if (opt->shortname == '\0' && opt->longname.empty()) {
      assert(false);
    } else {
      auto idx = options_.size();
      if (opt->shortname != '\0')
        short_.emplace(opt->shortname, idx);
      if (!opt->longname.empty())
        long_.emplace(opt->longname, idx);
    }
    options_.emplace_back(std::move(opt));
  }

  static inline bool is_whitespace(char c) { return c == ' ' || c == '\t'; }

  static void print_wrap(std::ostream& out, uint32_t width, uint32_t indent,
                         const std::string& str) {
    if (indent + str.size() <= width) {
      out << str << '\n';
      return;
    }
    if (width <= indent || indent + 10 > width) {
      out << '\n';
      out << str << '\n';
      return;
    }
    const std::string indent_str(indent, ' ');
    const uint32_t avail = width - indent;
    size_t offset = 0;
    while (offset + avail < str.size()) {
      uint32_t i = avail;
      while (i > 0 && !is_whitespace(str[offset + i]))
        --i;
      if (i == 0) {
        out << str.substr(offset, avail - 1);
        out << "-\n";
        offset += avail - 1;
      } else {
        out << str.substr(offset, i);
        out << '\n';
        offset += i;
      }
      out << indent_str;
    }
    out << str.substr(offset);
    out << '\n';
  }

  const std::string prgname_;
  std::vector<std::shared_ptr<OptionImpl>> options_;
  std::map<char, size_t> short_;
  std::map<std::string_view, size_t> long_;
  std::string last_error_;
};

}  // namespace

std::shared_ptr<Args::Option> Args::option(std::string longname,
                                           std::string help) {
  return option(/* shortname */ '\0', std::move(longname), std::move(help));
}

std::shared_ptr<Args::OptionArgument> Args::option_argument(
    std::string longname, std::string arg, std::string help, bool required) {
  return option_argument(/* shortname */ '\0', std::move(longname),
                         std::move(arg), std::move(help), required);
}

std::unique_ptr<Args> Args::create(std::string prgname) {
  return std::make_unique<ArgsImpl>(std::move(prgname));
}