Skip to content

Add ability to parse command line switches without a value #36024

Open
@jdmallen

Description

@jdmallen

Is your feature request related to a problem? Please describe.

Supplying just a switch as a command line argument is ignored...

.\myProgram.exe --help

...unless a value was also supplied.

.\myProgram.exe --help=true
.\myProgram.exe --help true

Describe the solution you'd like

I suggest changing the CommandLineConfigurationProvider to provide a default value of "true" if a value is omitted. It both ensures the key is included in the Configuration for consumption in the app, and allows for it to be more easily bound to an IOptions object as a bool, if desired.

Describe alternatives you've considered

I considered supplying just an empty string or null object for the configuration value, but that seemed a bit less clear. Switches are generally treated as "true if present," so I went with that approach.

Additional context

I did create a branch and implement the change in my fork. Sorry the diff is a mess-- I'm not sure why things aren't lining up. There wasn't nearly as much changed as it's showing. Here's a summary of the code changes:

  • removed the outer using (var enumerator)... scope, reducing the indentation of its original contents (this is probably why diff is freaking out)
  • replaced the while with the for loop
  • changed/added a couple variables to capture the current and next args
  • added a section to handle the missing value
  • modified the test for no value provided to instead check for its value being assigned as "true"

The rest is the same. I can confirm it works as expected. Since this change requires looking ahead to know if the next arg following a space is a value for the current arg OR the next argument key, which simple enumeration cannot provide, I changed it to a for loop. This seemed the cleanest way to allow for looking ahead (i.e. providing indexed access).

One caveat is that this pulls Linq into the usings to convert the IEnumerable<string> Args to a string[] array using the System.Linq.ToArray<T>() command. This is probably not ideal and I am open to alternatives to keep this speedy and appropriate for the repo.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions