C# / .NET – System.CommandLine: Making the command line case insensitive

Good evening

For 5 years, M$ has not been willing to solve this simple issue:
System.CommandLine: Consider optional case insensitive parsing #133

How can we create command line tools by using System.CommandLine has great usability for customers that just work?
It’s a shame that small tools expect users to remember in which case a parameter has to be passed.

Thanks a lot, kind regards,

Thomas

The answer is pretty simple.

Unfortunately, pure greed makes Microsoft more and more unbearable and instead of offering professional solutions to the customers, small topics like “Consider optional case insensitive parsing” are discussed for 5 years and a basic, central packages like System.CommandLine is kept in the beta stage for years instead of being professionally developed and finalized.

As it turns out, a Microsoft developer could have done this Job in about 60 lines of code by writing generic Middleware processor, as ScottArbeit showed here:
Scotts Comment and
Scotts example code in f#.

Here is a small example in c# which perfectly works: You can call the compiled App and all parameters are working as expected: --version, --VerSion, -v and -V

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class Program {
private static readonly bool CaseInsensitive = true; // Enable case-insensitive parsing
static async Task<int> Main(string[] args) {
var rootCommand2 = new RootCommand("Sample app for System.CommandLine");
// Create the CommandLineBuilder with and add the Middleware
var builder = new CommandLineBuilder(rootCommand2)
// Set option verb & shortcut
.UseVersionOption("--version", "-v")
.AddMiddleware(CaseInsensitiveMiddleware, MiddlewareOrder.ExceptionHandler)
.UseDefaults();
var parser = builder.Build();
return await parser.InvokeAsync(args);
}
public static void CaseInsensitiveMiddleware(InvocationContext context) {
if (!CaseInsensitive) return;
var commandOptions = context.ParseResult.CommandResult.Command.Options
.Concat(context.ParseResult.RootCommandResult.Command.Options);
var allAliases = commandOptions.SelectMany(option => option.Aliases);
string[] GetCorrectTokenCase(string[] tokens) {
var newTokens = new List<string>(tokens.Length);
for (int i = 0; i < tokens.Length; i++) {
var token = tokens[i];
var matchingAlias = allAliases.FirstOrDefault
(alias =>
alias.Equals(token, StringComparison.InvariantCultureIgnoreCase));
if (matchingAlias != null) {
newTokens.Add(matchingAlias);
continue;
}
if (i > 0) {
var previousToken = tokens[i - 1];
var matchingOption = commandOptions.FirstOrDefault
(option =>
option.Aliases.Contains(previousToken, StringComparer.InvariantCultureIgnoreCase));
if (matchingOption != null) {
var completions = matchingOption.GetCompletions()
.Select(completion => completion.InsertText)
.ToArray();
if (completions.Length > 0) {
var matchingCompletion = completions.FirstOrDefault
(completion =>
token.Equals(completion, StringComparison.InvariantCultureIgnoreCase));
newTokens.Add(matchingCompletion ?? token);
}
else {
newTokens.Add(token);
}
}
else {
newTokens.Add(token);
}
}
else {
newTokens.Add(token);
}
}
return newTokens.ToArray();
}
var tokens = context.ParseResult.Tokens.Select(token => token.Value).ToArray();
string[] newTokens;
if (tokens.Length == 0) {
newTokens = Array.Empty<string>();
}
else if (tokens.Length == 1) {
newTokens = new[] { tokens[0].ToLowerInvariant() };
}
else {
if (tokens[0].StartsWith("-")) {
newTokens = tokens;
}
else {
newTokens = new[] { tokens[0].ToLowerInvariant(), tokens[1].ToLowerInvariant() }
.Concat(GetCorrectTokenCase(tokens.Skip(2).ToArray()))
.ToArray();
}
}
context.ParseResult = context.Parser.Parse(newTokens);
}
}
</code>
<code>public class Program { private static readonly bool CaseInsensitive = true; // Enable case-insensitive parsing static async Task<int> Main(string[] args) { var rootCommand2 = new RootCommand("Sample app for System.CommandLine"); // Create the CommandLineBuilder with and add the Middleware var builder = new CommandLineBuilder(rootCommand2) // Set option verb & shortcut .UseVersionOption("--version", "-v") .AddMiddleware(CaseInsensitiveMiddleware, MiddlewareOrder.ExceptionHandler) .UseDefaults(); var parser = builder.Build(); return await parser.InvokeAsync(args); } public static void CaseInsensitiveMiddleware(InvocationContext context) { if (!CaseInsensitive) return; var commandOptions = context.ParseResult.CommandResult.Command.Options .Concat(context.ParseResult.RootCommandResult.Command.Options); var allAliases = commandOptions.SelectMany(option => option.Aliases); string[] GetCorrectTokenCase(string[] tokens) { var newTokens = new List<string>(tokens.Length); for (int i = 0; i < tokens.Length; i++) { var token = tokens[i]; var matchingAlias = allAliases.FirstOrDefault (alias => alias.Equals(token, StringComparison.InvariantCultureIgnoreCase)); if (matchingAlias != null) { newTokens.Add(matchingAlias); continue; } if (i > 0) { var previousToken = tokens[i - 1]; var matchingOption = commandOptions.FirstOrDefault (option => option.Aliases.Contains(previousToken, StringComparer.InvariantCultureIgnoreCase)); if (matchingOption != null) { var completions = matchingOption.GetCompletions() .Select(completion => completion.InsertText) .ToArray(); if (completions.Length > 0) { var matchingCompletion = completions.FirstOrDefault (completion => token.Equals(completion, StringComparison.InvariantCultureIgnoreCase)); newTokens.Add(matchingCompletion ?? token); } else { newTokens.Add(token); } } else { newTokens.Add(token); } } else { newTokens.Add(token); } } return newTokens.ToArray(); } var tokens = context.ParseResult.Tokens.Select(token => token.Value).ToArray(); string[] newTokens; if (tokens.Length == 0) { newTokens = Array.Empty<string>(); } else if (tokens.Length == 1) { newTokens = new[] { tokens[0].ToLowerInvariant() }; } else { if (tokens[0].StartsWith("-")) { newTokens = tokens; } else { newTokens = new[] { tokens[0].ToLowerInvariant(), tokens[1].ToLowerInvariant() } .Concat(GetCorrectTokenCase(tokens.Skip(2).ToArray())) .ToArray(); } } context.ParseResult = context.Parser.Parse(newTokens); } } </code>
public class Program {

   private static readonly bool CaseInsensitive = true; // Enable case-insensitive parsing

   static async Task<int> Main(string[] args) {

      var rootCommand2 = new RootCommand("Sample app for System.CommandLine");

      // Create the CommandLineBuilder with and add the Middleware
      var builder = new CommandLineBuilder(rootCommand2)
                    // Set option verb & shortcut
                   .UseVersionOption("--version", "-v")
                   .AddMiddleware(CaseInsensitiveMiddleware, MiddlewareOrder.ExceptionHandler)
                   .UseDefaults();

      var parser = builder.Build();
      return await parser.InvokeAsync(args);
   }

   public static void CaseInsensitiveMiddleware(InvocationContext context) {
      if (!CaseInsensitive) return;

      var commandOptions = context.ParseResult.CommandResult.Command.Options
                                  .Concat(context.ParseResult.RootCommandResult.Command.Options);

      var allAliases = commandOptions.SelectMany(option => option.Aliases);

      string[] GetCorrectTokenCase(string[] tokens) {
         var newTokens = new List<string>(tokens.Length);

         for (int i = 0; i < tokens.Length; i++) {
            var token = tokens[i];

            var matchingAlias = allAliases.FirstOrDefault
               (alias =>
                   alias.Equals(token, StringComparison.InvariantCultureIgnoreCase));

            if (matchingAlias != null) {
               newTokens.Add(matchingAlias);
               continue;
            }

            if (i > 0) {
               var previousToken = tokens[i - 1];

               var matchingOption = commandOptions.FirstOrDefault
                  (option =>
                      option.Aliases.Contains(previousToken, StringComparer.InvariantCultureIgnoreCase));

               if (matchingOption != null) {
                  var completions = matchingOption.GetCompletions()
                                                  .Select(completion => completion.InsertText)
                                                  .ToArray();

                  if (completions.Length > 0) {
                     var matchingCompletion = completions.FirstOrDefault
                        (completion =>
                            token.Equals(completion, StringComparison.InvariantCultureIgnoreCase));
                     newTokens.Add(matchingCompletion ?? token);
                  }
                  else {
                     newTokens.Add(token);
                  }
               }
               else {
                  newTokens.Add(token);
               }
            }
            else {
               newTokens.Add(token);
            }
         }

         return newTokens.ToArray();
      }

      var      tokens = context.ParseResult.Tokens.Select(token => token.Value).ToArray();
      string[] newTokens;

      if (tokens.Length == 0) {
         newTokens = Array.Empty<string>();
      }
      else if (tokens.Length == 1) {
         newTokens = new[] { tokens[0].ToLowerInvariant() };
      }
      else {
         if (tokens[0].StartsWith("-")) {
            newTokens = tokens;
         }
         else {
            newTokens = new[] { tokens[0].ToLowerInvariant(), tokens[1].ToLowerInvariant() }
                       .Concat(GetCorrectTokenCase(tokens.Skip(2).ToArray()))
                       .ToArray();
         }
      }

      context.ParseResult = context.Parser.Parse(newTokens);
   }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật