Debian Codegraph @

getopt/getopts.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use errors;
5 use fmt;
6 use io;
7 use os;
8 use strings;
9
10 // The result of parsing the set of command line arguments, including any
11 // options specified and the list of non-option arguments. If a subcommand
12 // is present in the help passed to [[parse]], then there will be no args.
13 export type command = struct {
14 opts: [](rune, str),
15 subcmd: (void | (str, *command)),
16 args: []str,
17 help: []help,
18 };
19
20 // Help text providing a short, one-line summary of the command; or providing
21 // the name of an argument.
22 export type cmd_help = str;
23
24 // Help text for a flag, formatted as "-a: help text".
25 export type flag_help = (rune, str);
26
27 // Help text for a parameter, formatted as "-a param: help text" where "param"
28 // is the first string and "help text" is the second string.
29 export type parameter_help = (rune, str, str);
30
31 // Definition of a named subcommand.
32 export type subcmd_help = (str, []help);
33
34 // Help text for a command or option. [[cmd_help]], [[flag_help]], and
35 // [[parameter_help]] compose such that the following []help:
36 //
37 // [
38 // "foo bars in order",
39 // ('a', "a help text"),
40 // ('b', "b help text"),
41 // ('c', "cflag", "c help text"),
42 // ('d', "dflag", "d help text"),
43 // "files...",
44 // ]
45 //
46 // will produce this help text:
47 //
48 // foo: foo bars in order
49 //
50 // Usage: foo [-ab] [-c <cflag>] [-d <dflag>] files...
51 //
52 // -a: a help text
53 // -b: b help text
54 // -c <cflag>: c help text
55 // -d <dflag>: d help text
56 export type help = (cmd_help | flag_help | parameter_help | subcmd_help);
57
58 export type requires_arg = rune;
59 export type unknown_option = rune;
60 export type unknown_subcmd = str;
61 export type error = !(
62 str, []help,
63 (requires_arg | unknown_option | unknown_subcmd),
64 );
65
66 // Converts a parsing error into a human-friendly string. The result may be
67 // statically allocated.
68 export fn strerror(err: error) str = {
69 static let buf: [1024]u8 = [0...];
70 match (err.2) {
71 case let r: requires_arg =>
72 return fmt::bsprintf(buf, "{}: option -{} requires an argument",
73 err.0, r: rune)!;
74 case let r: unknown_option =>
75 return fmt::bsprintf(buf, "{}: unrecognized option: -{}",
76 err.0, r: rune)!;
77 case let s: unknown_subcmd =>
78 return fmt::bsprintf(buf, "{}: unrecognized subcommand: {}",
79 err.0, s: str)!;
80 };
81 };
82
83 // A wrapper for [[tryparse]] in which if an error occurs, details are printed
84 // to [[os::stderr]] (as in [[printusage]]), and [[os::exit]] is called with
85 // [[os::status::FAILURE]].
86 export fn parse(args: []str, help: help...) command = {
87 match (tryparse(args, help...)) {
88 case let c: command => return c;
89 case let e: error =>
90 fmt::errorln(strerror(e))!;
91 if (e.2 is unknown_subcmd) {
92 printsubcmds(os::stderr, e.1)!;
93 fmt::errorln()!;
94 };
95 printusage(os::stderr, e.0, e.1)!;
96 os::exit(os::status::FAILURE);
97 case nomem =>
98 fmt::errorln(errors::strerror(nomem))!;
99 os::exit(os::status::FAILURE);
100 };
101 };
102
103 // Parses command line arguments and returns a [[command]], or an [[error]]
104 // if an error occurs. The argument list must include the command name as
105 // the first item; [[os::args]] fulfills this criteria.
106 export fn tryparse(args: []str, help: help...) (command | error | nomem) = {
107 let ok = false;
108
109 let opts: [](rune, str) = [];
110 defer if (!ok) free(opts);
111
112 let i = 1z;
113 for :arg (i < len(args); i += 1) {
114 const arg = args[i];
115 if (len(arg) == 0 || arg == "-"
116 || !strings::hasprefix(arg, "-")) {
117 break;
118 };
119 if (arg == "--") {
120 i += 1;
121 break;
122 };
123
124 let iter = strings::iter(arg);
125 assert(strings::next(&iter) as rune == '-');
126 for (let r => strings::next(&iter)) {
127 let found = false;
128 for (let j = 0z; j < len(help); j += 1) match (help[j]) {
129 case let f: flag_help =>
130 if (r == f.0) {
131 append(opts, (r, ""))?;
132 found = true;
133 break;
134 };
135 case let p: parameter_help =>
136 if (r == p.0) {
137 let value = strings::iterstr(&iter);
138 if (len(value) == 0) {
139 if (i == len(args) - 1) {
140 return (args[0], help, r: requires_arg): error;
141 };
142 i += 1;
143 append(opts, (r, args[i]))?;
144 } else {
145 append(opts, (r, value))?;
146 };
147 continue :arg;
148 };
149 case =>
150 continue;
151 };
152 if (found) continue;
153 if (r =='h') {
154 printhelp(os::stdout, args[0], help)!;
155 os::exit(os::status::SUCCESS);
156 };
157 return (args[0], help, r: unknown_option): error;
158 };
159 };
160 let subcmd: (void | (str, *command)) = void;
161 defer if (!ok && subcmd is (str, *command))
162 free((subcmd as (str, *command)).1);
163
164 if (i < len(args)) {
165 let expects_subcmd = false;
166 for (let j = 0z; j < len(help); j += 1) match (help[j]) {
167 case let s: subcmd_help =>
168 expects_subcmd = true;
169 if (s.0 == args[i]) match (tryparse(args[i..], s.1...)) {
170 case let c: command =>
171 subcmd = (s.0, alloc(c)?);
172 case let e: error =>
173 return e;
174 };
175 case => continue;
176 };
177 if (expects_subcmd && subcmd is void) {
178 return (args[0], help, args[i]: unknown_subcmd): error;
179 };
180 };
181
182 ok = true;
183 return command {
184 opts = opts,
185 subcmd = subcmd,
186 args = if (subcmd is void) args[i..] else [],
187 help = help,
188 };
189 };
190
191 // Frees resources associated with the return value of [[parse]].
192 export fn finish(cmd: *command) void = {
193 free(cmd.opts);
194 match (cmd.subcmd) {
195 case void => void;
196 case let s: (str, *command) =>
197 finish(s.1);
198 free(s.1);
199 };
200 };
201
202 // Prints command usage to the provided stream.
203 export fn printusage(
204 out: io::handle,
205 name: str,
206 help: []help
207 ) (void | io::error) = {
208 let h = contains_h(help);
209 let z = _printusage(io::empty, name, false, h, help)?;
210 _printusage(out, name, if (z > 72) true else false, h, help)?;
211 };
212
213 fn _printusage(
214 out: io::handle,
215 name: str,
216 indent: bool,
217 contains_h: bool,
218 help: []help,
219 ) (size | io::error) = {
220 let z = fmt::fprint(out, "Usage:", name)?;
221
222 let started_flags = false;
223 if (!contains_h) {
224 z += fmt::fprint(out, " [-h")?;
225 started_flags = true;
226 };
227 for (let h .. help) {
228 match (h) {
229 case let h: flag_help =>
230 if (!started_flags) {
231 z += fmt::fprint(out, " [-")?;
232 started_flags = true;
233 };
234 z += fmt::fprint(out, h.0)?;
235 case => void;
236 };
237 };
238 if (started_flags) {
239 z += fmt::fprint(out, "]")?;
240 };
241
242 for (let h .. help) {
243 match (h) {
244 case let h: parameter_help =>
245 if (indent) {
246 z += fmt::fprintf(out, "\n\t")?;
247 };
248 z += fmt::fprintf(out, " [-{} <{}>]", h.0, h.1)?;
249 case => void;
250 };
251 };
252
253 let first_arg = true;
254 for (let i = 1z; i < len(help); i += 1) if (help[i] is cmd_help) {
255 if (first_arg) {
256 if (indent) {
257 z += fmt::fprintf(out, "\n\t")?;
258 };
259 first_arg = false;
260 };
261 z += fmt::fprintf(out, " {}", help[i] as cmd_help: str)?;
262 };
263
264 return z + fmt::fprint(out, "\n")?;
265 };
266
267 fn contains_h(help: []help) bool = {
268 for (let h .. help) {
269 const r = match (h) {
270 case let h: flag_help => yield h.0;
271 case let h: parameter_help => yield h.0;
272 case => continue;
273 };
274 if (r == 'h') {
275 return true;
276 };
277 };
278 return false;
279 };
280
281 // Prints command help to the provided stream.
282 export fn printhelp(
283 out: io::handle,
284 name: str,
285 help: []help
286 ) (void | io::error) = {
287 if (len(help) == 0) {
288 return;
289 };
290
291 if (help[0] is cmd_help) {
292 fmt::fprintfln(out, "{}: {}\n", name, help[0] as cmd_help: str)?;
293 };
294
295 let contains_h = contains_h(help);
296 let z = _printusage(io::empty, name, false, contains_h, help)?;
297 _printusage(out, name, if (z > 72) true else false, contains_h, help)?;
298
299 fmt::fprint(out, "\n")?;
300 if (!contains_h) {
301 fmt::fprintln(out, "-h: print this help text")?;
302 };
303 for (let h .. help) {
304 match (h) {
305 case let f: flag_help =>
306 fmt::fprintfln(out, "-{}: {}", f.0, f.1)?;
307 case let p: parameter_help =>
308 fmt::fprintfln(out, "-{} <{}>: {}", p.0, p.1, p.2)?;
309 case => void;
310 };
311 };
312
313 printsubcmds(out, help)?;
314 };
315
316 fn printsubcmds(out: io::handle, help: []help) (void | io::error) = {
317 let first = true;
318 for (let h .. help) {
319 match (h) {
320 case let s: subcmd_help =>
321 // Only print this if there are subcommands to show
322 if (first) {
323 fmt::fprintln(out, "\nSubcommands:")?;
324 first = false;
325 };
326 if (len(s.1) == 0 || !(s.1[0] is cmd_help)) {
327 fmt::fprintfln(out, " {}", s.0)?;
328 } else {
329 fmt::fprintfln(out, " {}: {}", s.0,
330 s.1[0] as cmd_help: str)?;
331 };
332 case => void;
333 };
334 };
335 };
336
337 @test fn parse() void = {
338 let args: []str = ["cat", "-v", "a.out"];
339 let cat = parse(args,
340 "concatenate files",
341 ('v', "cause Rob Pike to make a USENIX presentation"),
342 "files...",
343 );
344 defer finish(&cat);
345 assert(len(cat.args) == 1 && cat.args[0] == "a.out");
346 assert(len(cat.opts) == 1 && cat.opts[0].0 == 'v' && cat.opts[0].1 == "");
347
348 args = ["ls", "-Fahs", "--", "-j"];
349 let ls = parse(args,
350 "list files",
351 ('F', "Do some stuff"),
352 ('h', "Do some other stuff"),
353 ('s', "Do a third type of stuff"),
354 ('a', "Do a fourth type of stuff"),
355 "files...",
356 );
357 defer finish(&ls);
358 assert(len(ls.args) == 1 && ls.args[0] == "-j");
359 assert(len(ls.opts) == 4);
360 assert(ls.opts[0].0 == 'F' && ls.opts[0].1 == "");
361 assert(ls.opts[1].0 == 'a' && ls.opts[1].1 == "");
362 assert(ls.opts[2].0 == 'h' && ls.opts[2].1 == "");
363 assert(ls.opts[3].0 == 's' && ls.opts[3].1 == "");
364
365 args = ["sed", "-e", "s/C++//g", "-f/tmp/turing.sed", "-"];
366 let sed = parse(args,
367 "edit streams",
368 ('e', "script", "Add the editing commands specified by the "
369 "script option to the end of the script of editing "
370 "commands"),
371 ('f', "script_file", "Add the editing commands in the file "
372 "script_file to the end of the script of editing "
373 "commands"),
374 "files...",
375 );
376 defer finish(&sed);
377 assert(len(sed.args) == 1 && sed.args[0] == "-");
378 assert(len(sed.opts) == 2);
379 assert(sed.opts[0].0 == 'e' && sed.opts[0].1 == "s/C++//g");
380 assert(sed.opts[1].0 == 'f' && sed.opts[1].1 == "/tmp/turing.sed");
381 };