2011-10-13

Option Parsing: Case Sensitivity

By default, all option parsing is case-sensitive:

class Program
{
  private sealed class Options : OptionArgumentsBase
  {
    [Option("name", 'n')]
    public string Name { get; private set; }
  }

  static int Main(string[] args)
  {
    try
    {
      var options = OptionParser.Parse<Options>();
      Console.WriteLine("Name: " + options.Name);
      return 0;
    }
    catch (OptionParsingException ex)
    {
      Console.Error.WriteLine(ex.Message);
      return 2;
    }
    catch (Exception ex)
    {
      Console.Error.WriteLine(ex);
      return 1;
    }
  }
}
> CommandLineParsingTest.exe /name Bob
Name: Bob

> CommandLineParsingTest.exe /Name Bob
Unknown option  Name  in parameter  /Name

This is normal for Unix users, but Windows users expect case-insensitivity. You can pass your own StringComparer to the Parse method to support case-insensitivity:

class Program
{
  private sealed class Options : OptionArgumentsBase
  {
    [Option("name", 'n')]
    public string Name { get; private set; }
  }

  static int Main(string[] args)
  {
    try
    {
      var options = OptionParser.Parse<Options>(stringComparer:StringComparer.CurrentCultureIgnoreCase);
      Console.WriteLine("Name: " + options.Name);
      return 0;
    }
    catch (OptionParsingException ex)
    {
      Console.Error.WriteLine(ex.Message);
      return 2;
    }
    catch (Exception ex)
    {
      Console.Error.WriteLine(ex);
      return 1;
    }
  }
}
> CommandLineParsingTest.exe /name Bob
Name: Bob

> CommandLineParsingTest.exe /Name Bob
Name: Bob

2 comments:

  1. I'm really enjoying Nito.KitchenSink.OptionParsing :D

    Have you thought about adding an argument count and/or automatic help documentation?

    ReplyDelete
  2. I'm glad you're enjoying it! I think it's fun myself, but most people think command line parsing is just plain tedious. :)

    I'm not sure what you're asking for regarding the argument count - could you clarify?

    I did consider automatic help documentation, but I've decided not to implement it. There are several different styles, it would be fairly complex to do, and there's not much benefit.

    However, the error handling was carefully designed to distinguish usage errors from any other kinds, and I made an attempt to provide user-friendly usage error messages. I do recommend putting you Usage method into your options class, so there's less of a chance of it getting "stale":

    http://nitoprograms.blogspot.com/2011/06/option-parsing-error-handling.html

    ReplyDelete