Hacktoberfest 2026: những issue maintainer đã đánh dấu cho tháng Mười, đang mở và phù hợp người mới. Xem issue Hacktoberfest

Exception Thrown Rather than Error Message And Help When Command Has Both Custom Parser and Validator

Đang mở
#2,699 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
45/100
Loại issue
Lỗi
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Đình trệ
Công nghệ
csharp
Lĩnh vực
cli

Hướng nghiên cứu

Bắt đầu với bản tái hiện C# được cung cấp, tập trung vào parser tùy chỉnh và các callback của validator được gắn vào rootCmdArgs, cùng với các điểm vào Parse(args)/InvokeAsync(). Theo dõi cách quá trình validation và conversion xử lý lỗi do parser thêm vào khi cả hai callback đều hiện diện. Được xem là hoàn tất khi đầu vào --dats không hợp lệ báo cáo lỗi của parser cùng với phần trợ giúp của command thay vì ném ra một InvalidOperationException chưa được xử lý.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

In the code below, running (with SDK 10.0.100-rc.1.25451.107)

dotnet run ./TestOne.cs 12 23 34 --dats ab bc cd 

Leads to an exception being thrown

Unhandled exception. System.InvalidOperationException: Argument "--dats" is not two characters long     
   at System.CommandLine.Binding.ArgumentConverter.GetValueOrDefault[T](ArgumentConversionResult result)
   at System.CommandLine.Parsing.ArgumentResult.GetValueOrDefault[T]()
   at Program.<>c.<<Main>$>b__0_3(ArgumentResult argRes) in [HIDDEN]\TestOne.cs:line 52
   at System.CommandLine.Parsing.ArgumentResult.ValidateAndConvert(Boolean useValidators)
   at System.CommandLine.Parsing.ArgumentResult.GetArgumentConversionResult()
   at System.CommandLine.Parsing.CommandResult.ValidateArgumentsAndAddDefaultResults(Boolean completeValidation)
   at System.CommandLine.Parsing.CommandResult.Validate(Boolean isInnermostCommand)
   at System.CommandLine.Parsing.ParseOperation.ValidateAndAddDefaultResults()
   at System.CommandLine.Parsing.ParseOperation.Parse()
   at System.CommandLine.Parsing.CommandLineParser.Parse(Command command, IReadOnlyList`1 arguments, String rawInput, ParserConfiguration configuration)
   at System.CommandLine.Parsing.CommandLineParser.Parse(Command command, IReadOnlyList`1 args, ParserConfiguration configuration)
   at System.CommandLine.Command.Parse(IReadOnlyList`1 args, ParserConfiguration configuration)
   at Program.<Main>$(String[] args) in [HIDDEN]\TestOne.cs:line 71
   at Program.<Main>(String[] args)

Rather than the expected, and more helpful:

Argument "--dats" is not two characters long

Description:
  Test app for System.CommandLine

Usage:
  TestOne <TestOne>... [options]

Arguments:
  <TestOne>  Root command arguments. One or more pairs of characters separated by space

Options:
  --data <data>   Option data items
  -?, -h, --help  Show help and usage information
  --version       Show version information

I noticed this when typo'ing the command line in a rather more complex project.

The problem seems to be that the validator triggers the parser, so there is nothing to check for errors reported by the parser. Without the custom parser the expected error & help is reported.


#:package [email protected]
#nullable enable
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Diagnostics;

string[] ParseArguments(ArgumentResult argRes) {
    List<string> res = new();
    foreach (var a in argRes.Tokens) {
        var s = a.Value;
        if (s.Length != 2) {
            argRes.AddError($"Argument \"{s}\" is not two characters long");
        } else {
            res.Add(s);
        }
    }
    return res.ToArray();
}

void ValidateArguments(string[] rawValues, Action<string> reportError) {
    if (rawValues.Length == 0) {
        reportError("No arguments provided");
        return;
    }

    foreach (var rawValue in rawValues) {
        if (rawValue.Length != 2) {
            reportError($"Argument \"{rawValue}\" is not two characters long");
        } else if (rawValue[0] >= rawValue[1]) {
            reportError($"In argument \"{rawValue}\" the first letter does not precede, in Unicode code point order, the second");
        }
    }
}

var dataOption = new Option<string[]>("--data") {
    Description = "Option data items",
    Arity = ArgumentArity.OneOrMore,
    Required = false,
    AllowMultipleArgumentsPerToken = true
};
dataOption.Validators.Add(optRes => {
    var args = optRes.GetValueOrDefault<string[]>();
    ValidateArguments(args, msg => optRes.AddError(msg));
});

var rootCmdArgs = new Argument<string[]>("TestOne") {
    Description = "Root command arguments. One or more pairs of characters separated by space",
    Arity = ArgumentArity.OneOrMore
};
rootCmdArgs.CustomParser = ParseArguments;
rootCmdArgs.Validators.Add(argRes => {
    var args = argRes.GetValueOrDefault<string[]>();
    ValidateArguments(args, msg => argRes.AddError(msg));
});

var rootCmd = new RootCommand("Test app for System.CommandLine") {
    dataOption,
    rootCmdArgs
};
rootCmd.SetAction(parseResult => {
    var args = parseResult.GetValue(rootCmdArgs);
    var dataArgs = parseResult.GetValue(dataOption);
    Debug.Assert(args is not null);
    Debug.Assert(dataArgs is not null);
    Console.WriteLine("Root command");
    Console.WriteLine($"   args: {String.Join(", ", args.Select(a => $"\"{a}\""))}");
    Console.WriteLine($"   data: {String.Join(", ", dataArgs.Select(a => $"\"{a}\""))}");
});

var parse = rootCmd.Parse(args);
await parse.InvokeAsync();
Ngôn ngữ chính
C#
Star
3.7k
Fork
434
Merge trung bình
4 giờ 46 phút
Pull request đã merge (30 ngày)
1

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của dotnet/command-line-api

Tất cả issue của dotnet/command-line-api

Issue tương tự

Thêm issue về C#

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.