util: split getopt error handling into utility function

This commit is contained in:
Jeremy Baxter 2024-06-25 17:00:02 +12:00
parent d8e267d5ba
commit 7a9866a4e2
2 changed files with 13 additions and 14 deletions

10
esv.d
View file

@ -20,7 +20,6 @@
module esv; module esv;
import std.algorithm : startsWith;
import std.conv : to, ConvException; import std.conv : to, ConvException;
import std.file : exists, mkdirRecurse, write, FileException; import std.file : exists, mkdirRecurse, write, FileException;
import std.format : format; import std.format : format;
@ -76,14 +75,7 @@ main(string[] args)
"V", &VFlag, "V", &VFlag,
); );
} catch (GetOptException e) { } catch (GetOptException e) {
string opt = extractFlag(e); handleOptError(e.msg);
enforceDie(!e.msg.startsWith("Unrecognized option"),
"unknown option " ~ opt);
enforceDie(!e.msg.startsWith("Missing value for argument"),
"missing argument for option " ~ opt);
die(e.msg); /* catch-all */
} }
if (VFlag) { if (VFlag) {

17
util.d
View file

@ -1,7 +1,6 @@
module util; module util;
import std.getopt : GetOptException; import std.stdio : File;
import std.stdio : File;
public @safe: public @safe:
@ -42,12 +41,20 @@ enforceDie(A...)(bool cond, string fmt, A a)
die(format(fmt, a)); die(format(fmt, a));
} }
string void
extractFlag(in GetOptException e) handleOptError(in string msg)
{ {
import std.algorithm : startsWith;
import std.regex : matchFirst; import std.regex : matchFirst;
return e.msg.matchFirst("-.")[0]; string opt = msg.matchFirst("-.")[0];
enforceDie(!msg.startsWith("Unrecognized option"),
"unknown option " ~ opt);
enforceDie(!msg.startsWith("Missing value for argument"),
"missing argument for option " ~ opt);
die(msg); /* catch-all */
} }
string string