-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc_args.cpp
More file actions
79 lines (68 loc) · 2.15 KB
/
Copy pathc_args.cpp
File metadata and controls
79 lines (68 loc) · 2.15 KB
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
#include <vector>
#include <iostream>
std::ostream &
operator<< (std::ostream & s, const std::vector<std::string> & v){
for (int i=0; i<v.size(); i++) s << (i>0? ", ":"") << v[i];
return s;
}
#include "c_args.h"
#include "inc/err.h"
Opt
get_position_args(const std::vector<std::string>::const_iterator & b,
const std::vector<std::string>::const_iterator & e,
const std::vector<std::string> & arg_list){
// Parse position arguments
Opt opts;
auto arg = b;
for (auto const & key:arg_list){
if (arg==e)
throw Err() << "Position argument is missing (expected: " << arg_list << ")";
opts[key] = *arg;
++arg;
}
return opts;
}
Opt
get_key_val_args(const std::vector<std::string>::const_iterator & b,
const std::vector<std::string>::const_iterator & e,
const std::vector<std::string> & arg_list){
// Extract default values of key-value arguments
Opt opts;
for (auto const & a:arg_list){
// parse key=value
auto n = a.find('=', 0);
if (n == std::string::npos)
throw Err() << "Can't find key=value pair in arg_list: " << a;
auto key = a.substr(0,n);
auto val = a.substr(n+1);
opts[key] = val;
}
// Parse key-value arguments
for (auto arg=b; arg!=e; ++arg){
// parse key=value
auto n = arg->find('=', 0);
if (n == std::string::npos)
throw Err() << "Can't find key=value pair: " << *arg;
auto key = arg->substr(0,n);
auto val = arg->substr(n+1);
// replace existing value in opts
if (opts.count(key)==0)
throw Err() << "Unknown parameter: " << key << " (known parameters with defaults: " << arg_list << ")";
opts[key] = val;
}
return opts;
}
// get a single argument (first entry)
std::string
get_key_val(const std::vector<std::string>::const_iterator & b,
const std::vector<std::string>::const_iterator & e,
const std::string & key, const std::string & def){
for (auto arg=b; arg!=e; ++arg){
// parse key=value
auto n = arg->find('=', 0);
if (n == std::string::npos) continue;
if (key != arg->substr(0,n)) continue;
return arg->substr(n+1);
}
return def;
}