www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Recovering options to getopt after a GetOptException is raised


I'm a bit puzzled by the behavior of this code:

import std.getopt;
import std.stdio;

void main(string[] args){
     string val;
     GetoptResult opts;
         opts = getopt(args, std.getopt.config.required, "val", 
"value you need to specify", &val);
     }catch(GetOptException e){
         writeln("You idiot. You had to give these options:");

Expected result:
:) programName --without --correct --argument
    You idiot. You had to give these options:
    --val value you need to specify

Actual result:
:) programName --without --correct --argument
    You idiot. You had to give these options:

It seems that the exception is thrown as soon as a missing option 
is encountered. It would be nice if getopt would populate 
GetoptResult.options before it threw the exception, because it 
would make the above code work smoothly. Alternatively, 
GetOptException could get a field containing the documentation 
that was provided in the call to getopt:

catch(GetOptException e){
     writefln("You idiot. You didn't provide the required %s 
argument (%s)", e.optionName, e.optionDocumentation);

If there is a way to handle this cleanly, I'd appreciate it. As 
it is, std.getopt.config.required seems like it's not very useful 
because it emits a rather unhelpful error message (containing 
only the name of the missing option) and I can't see a way to 
print a more useful message without checking all the options in 
my own code.

Oct 07 2015