0

I have begun starting using this https://github.com/commandlineparser/commandline to pass the input parameters parsed to my application.

My problem here is that the input parameter passed is not required, meaning you can start the application without speciying them.

I have so far defined my command line options as such

   public class CommandLineOptions
    {
        [Option(longName: "client-id", Required = false, HelpText = "Id of the client")]
        public string ClientId { get; set; }

        [Option(longName: "pw", Required = false, HelpText = "pw.")]
        public string Password{ get; set; }
    }

and in my main I parse them like this

Access access= Parser.Default.ParseArguments<CommandLineOptions>(args)
                .MapResult(parsedFunc: (CommandLineOptions opts) => new Access(opts.ClientId, opts.Password),
                           notParsedFunc: (IEnumerable<Error> a) => new Access());

I want to use the parsedfunc: in case it is specified, and notParsedFunc: in case it is not specified.

but this always triggers the parsedFunc and since the value of both parameters are null, my inner method fails?

I've also tried changing the option to not required, this then throws an error in the console window that these parameter has not been specified, but triggers the correct method.

noob
  • 13
  • 3
  • Since advising to read the documentation is against site's rules... Based on names of parameters it looks like `nonParsedFunc` will only be called in case of errors (likely finding parameters you have not defined) and not when optional parameters are missing... – Alexei Levenkov Mar 11 '21 at 08:22

1 Answers1

0

From the documentation :

If parsing succeeds, you'll get a derived Parsed type that exposes an instance of T through its Value property.

If parsing fails, you'll get a derived NotParsed type with errors present in Errors sequence.

NotParsed is called when the parsing fail, but in you case the parsing success because empty password is allowed.

You need use Parsed and check manually if the argument is present :

Access access = Parser.Default.ParseArguments<CommandLineOptions>(args)
    .MapResult(
        opts => opts.Password == null ? new Access() : new Access(opts.ClientId, opts.Password),
        _ => null
    );
if(access == null)
{
    // Fail to create access
    // Close withe exit code 1
    Environment.Exit(1);
}
vernou
  • 6,818
  • 5
  • 30
  • 58