Repository navigation
Expand file tree
/
Copy pathargs.nx
More file actions
224 lines (207 loc) · 7.12 KB
/
Copy pathargs.nx
File metadata and controls
224 lines (207 loc) · 7.12 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
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
// std.args: command-line argument parsing, written in Nexium.
//
// `import std.args` then:
//
// var p = args.Parser.new(os.args())
// let verbose = p.flag("--verbose", "-v")
// let level = p.option("--level", "-l") orelse "info"
// let files = p.rest()
//
// Long options take `--name value` or `--name=value`; short ones `-n value`.
// Everything after `--` is positional. Unknown options stay in `rest()`
// so the caller can report them.
pub struct Parser {
argv: [][]u8
used: List(bool)
}
impl Parser {
/// Wrap `os.args()`; the program name in `argv[0]` is skipped.
pub fn new(argv: [][]u8) -> Parser {
var used = List(bool).with_capacity(argv.len)
for _ in argv { used.append(false) }
if used.len > 0 { used[0] = true }
return Parser{ .argv = argv, .used = used }
}
fn matches(self: *Self, i: usize, long: []u8, short: []u8) -> bool {
let a = self.argv[i]
return a == long or (short.len > 0 and a == short)
}
/// True when the flag is present (any number of times).
pub fn flag(self: *mut Self, long: []u8, short: []u8) -> bool {
var found = false
for a, i in self.argv {
if a == "--" { break }
if self.matches(i, long, short) {
self.used[i] = true
found = true
}
}
return found
}
/// How many times the flag appears (`-vvv` counts as three).
pub fn count(self: *mut Self, long: []u8, short: []u8) -> usize {
var n: usize = 0
for a, i in self.argv {
if a == "--" { break }
if self.matches(i, long, short) {
self.used[i] = true
n += 1
} else if short.len == 2 and a.len > 2 and a[0] == '-' and a[1] != '-' {
// stacked short flags: -vvv
var all = true
for c in a[1..] { if c != short[1] { all = false } }
if all {
self.used[i] = true
n += a.len - 1
}
}
}
return n
}
/// The value of `--name value`, `--name=value`, or `-n value`; the last one wins.
pub fn option(self: *mut Self, long: []u8, short: []u8) -> ?[]u8 {
var value: ?[]u8 = null
for a, i in self.argv {
if a == "--" { break }
if self.matches(i, long, short) {
self.used[i] = true
if i + 1 < self.argv.len {
self.used[i + 1] = true
value = self.argv[i + 1]
}
} else if a.len > long.len and a.starts_with(long) and a[long.len] == '=' {
self.used[i] = true
value = a[long.len + 1..]
}
}
return value
}
/// Every value of a repeatable option, in order.
pub fn options(self: *mut Self, long: []u8, short: []u8) -> List([]u8) {
var out = List([]u8).new()
for a, i in self.argv {
if a == "--" { break }
if self.matches(i, long, short) {
self.used[i] = true
if i + 1 < self.argv.len {
self.used[i + 1] = true
out.append(self.argv[i + 1])
}
} else if a.len > long.len and a.starts_with(long) and a[long.len] == '=' {
self.used[i] = true
out.append(a[long.len + 1..])
}
}
return out
}
/// An option parsed as an integer; `error.InvalidInput` when present but not a number.
pub fn int_option(self: *mut Self, long: []u8, short: []u8) -> !?i64 {
let raw = self.option(long, short) orelse return null
let v = raw.parse_int(i64) catch |e| return error.InvalidInput
return v
}
/// Arguments not consumed by any query, plus everything after `--`.
pub fn rest(self: *Self) -> List([]u8) {
var out = List([]u8).new()
var after_dashes = false
for a, i in self.argv {
if after_dashes {
out.append(a)
} else if a == "--" {
after_dashes = true
} else if !self.used[i] {
out.append(a)
}
}
return out
}
/// Unconsumed arguments that look like options: the ones the program did not ask for.
pub fn unknown_options(self: *Self) -> List([]u8) {
var out = List([]u8).new()
for a, i in self.argv {
if a == "--" { break }
if !self.used[i] and a.len > 1 and a[0] == '-' { out.append(a) }
}
return out
}
}
/// Render a usage line and option table from (flags, description) rows.
pub fn usage(program: []u8, summary: []u8, rows: [][]u8) -> String {
var out = String.new()
out.append("usage: ")
out.append(program)
out.append(" ")
out.append(summary)
out.append("\n")
var i: usize = 0
while i + 1 < rows.len {
out.append(" ")
out.append(rows[i])
for _ in rows[i].len..22 { out.push_byte(' ') }
out.append(rows[i + 1])
out.append("\n")
i += 2
}
return out
}
/// The environment as a map, from `os.environ()`.
pub fn env_map() -> Map(String, String) {
var m = Map(String, String).new()
for entry in os.environ() {
var i: usize = 0
while i < entry.len and entry[i] != '=' { i += 1 }
if i == 0 or i >= entry.len { continue }
m.put(String.from(entry[0..i]), String.from(entry[i + 1..entry.len]))
}
return m
}
test "env map" {
let m = env_map()
expect(m.len > 0)
}
test "flags and options" {
let argv = ["prog", "-v", "--level", "debug", "--name=nx", "in.txt", "-v", "--", "-x"]
var p = Parser.new(argv[..])
expect(p.flag("--verbose", "-v"))
expect(!p.flag("--quiet", "-q"))
expect_eq(p.option("--level", "-l") orelse "none", "debug")
expect_eq(p.option("--name", "-n") orelse "none", "nx")
expect(p.option("--missing", "") == null)
let rest = p.rest()
expect_eq(rest.len, 2)
expect_eq(rest[0], "in.txt")
expect_eq(rest[1], "-x")
}
test "counts and repeats" {
let argv = ["prog", "-vvv", "-I", "a", "-I", "b", "--include=c"]
var p = Parser.new(argv[..])
expect_eq(p.count("--verbose", "-v"), 3)
let incs = p.options("--include", "-I")
expect_eq(incs.len, 3)
expect_eq(incs[2], "c")
expect_eq(p.rest().len, 0)
}
test "integers and unknowns" {
let argv = ["prog", "--jobs", "8", "--bad", "--depth=x"]
var p = Parser.new(argv[..])
let jobs = try p.int_option("--jobs", "-j")
expect_eq(jobs orelse 0, 8)
let none = try p.int_option("--none", "")
expect(none == null)
var bad = false
_ = p.int_option("--depth", "-d") catch |e| {
bad = true
null
}
expect(bad)
let unk = p.unknown_options()
expect_eq(unk.len, 1)
expect_eq(unk[0], "--bad")
}
test "usage text" {
let rows = ["-v, --verbose", "say more", "-l, --level L", "log level"]
let u = usage("tool", "[options] FILE", rows[..])
expect(u.starts_with("usage: tool [options] FILE\n"))
expect(u.find(" -v, --verbose") != null)
expect(u.find("log level\n") != null)
}