-
Notifications
You must be signed in to change notification settings - Fork 292
Display A Help Screen
Mapping a method with HelpOptionAttribute will allow the parser to display a help screen when parsing rule are violated.
class Options
{
[Option("p", "person-to-greet", Required=true, HelpText="The person to greet.")]
public string PersonToGreet { get; set; }
[HelpOption]
public string GetUsage()
{
return "Please read user manual!" + Environment.NewLine;
}
}
In this sample the -p|--person-to-great
option is mandatory. Omitting it will cause the parser to display the string returned by Options::GetUsage()
.
When mapping a method with HelpOption the are only few constraint to respect. The method must be an instance method, it have to return a string and accept no parameters. The name can be the one that you prefer.
The CommandLine.Text namespace contains helper types to make easy the render of the help screen.
class Options
{
[Option("p", "person-to-greet", Required=true, HelpText="The person to greet.")]
public string PersonToGreet { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText {
Heading = new HeadingInfo("<<app title>>", "<<app version>>"),
Copyright = new CopyrightInfo("<<app author>>", 2012),
AdditionalNewLineAfterOption = true,
AddDashesToOption = true
};
help.AddPreOptionsLine("<<license details here.>>");
help.AddPreOptionsLine("Usage: app -pSomeone");
help.AddOptions(this);
return help;
}
}
In this example the method creates an HelpText instance, it uses secondary helper types to specify heading and copyright informations and sets some preferences.
Then it simply add text as a StringBuilder and with a single call (AddOptions) renders the options block. Every option attribute (except ValueList) inherits from BaseOptionAttribute and this type has a property named HelpText. And precisely the value of this property is used by AddOptions method.
Parsing errors like badly formatted values or missing required options can be captured as generic list of ParsingError type. Access this data requires that your target class inherits from the abstract CommandLineOptionsBase.
class Options : CommandLineOptionsBase
{
}
This will let you access the protected member LastPostParsingState defined as PostParsingState. It follows complete object model.
public sealed class PostParsingState
{
public List<ParsingError> Errors { get; }
}
public class ParsingError
{
public BadOptionInfo BadOption { get; }
public bool ViolatesRequired { get; }
public bool ViolatesFormat { get; }
public bool ViolatesMutualExclusiveness { get; }
}
public sealed class BadOptionInfo
{
public string ShortName { get; }
public string LongName { get; }
}
[TO BE CONTINUED...]