www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - getopt helpWanted

reply "novice2" <sorry noem.ail> writes:
Hello.

Help me please to understand, how to show usage help to user, who 
enter wrong options?
For example, user not provided required filename.
I want to show error message, and program usage help text.
But likely getopt don't provide help text until valid options 
will be parsed.

Reduced code:
///////////////
import std.stdio: writefln;
import std.getopt;

void main (string[] args)
{
   string fname;
   GetoptResult helpInfo;

   try
   {
     helpInfo = getopt(
       args,
       std.getopt.config.required, "file|f", "File name", &fname);

     writefln("Options parsed: fname=%s", fname);
   }
   catch(Exception e)
   {
     writefln("\nERROR: %s", e.msg);
     defaultGetoptPrinter("Program usage:", helpInfo.options);
   }
}
///////////////

Output:
ERROR: Required option file|fwas not supplied
Program usage:
Apr 29 2015
next sibling parent reply "Brian Schott" <briancschott gmail.com> writes:
What you're trying to do is currently impossible. I filed a bug 
(https://issues.dlang.org/show_bug.cgi?id=14525) because what 
you're trying to do really should be possible.

import std.stdio : writefln;
import std.getopt;

void main(string[] args)
{
     string fname;
     try
     {
         getopt(args, std.getopt.config.required, "file|f", "File 
name", &fname);
         writefln("Options parsed: fname=%s", fname);
     }
     catch (GetOptException e)
     {
         writefln("\nERROR: %s", e.msg);
         auto p = ["placeholder"];
         auto r = getopt(p, "file|f", "File name", &fname);
         defaultGetoptPrinter("Program usage:", r.options);
     }
}
Apr 29 2015
parent "novice2" <sorryno em.ail> writes:
Thank you, Brian!
Apr 29 2015
prev sibling parent "wobbles" <grogan.colin gmail.com> writes:
On Wednesday, 29 April 2015 at 22:02:29 UTC, novice2 wrote:
 Hello.

 Help me please to understand, how to show usage help to user, 
 who enter wrong options?
 For example, user not provided required filename.
 I want to show error message, and program usage help text.
 But likely getopt don't provide help text until valid options 
 will be parsed.

 Reduced code:
 ///////////////
 import std.stdio: writefln;
 import std.getopt;

 void main (string[] args)
 {
   string fname;
   GetoptResult helpInfo;

   try
   {
     helpInfo = getopt(
       args,
       std.getopt.config.required, "file|f", "File name", 
 &fname);

     writefln("Options parsed: fname=%s", fname);
   }
   catch(Exception e)
   {
     writefln("\nERROR: %s", e.msg);
     defaultGetoptPrinter("Program usage:", helpInfo.options);
   }
 }
 ///////////////

 Output:
 ERROR: Required option file|fwas not supplied
 Program usage:
Also, I suggest you look at docopt: http://code.dlang.org/packages/docopt It makes the whole parsing of CLI arguments very nice and easy.
Apr 30 2015