Exception Thrown Rather than Error Message And Help When Command Has Both Custom Parser and Validator
まだ誰も着手していません。
評価
調査の方向性
提供された C# の再現コードから始め、カスタムパーサーと rootCmdArgs にアタッチされたバリデーターコールバック、および Parse(args)/InvokeAsync() のエントリーポイントに注目してください。両方のコールバックが存在する場合に、検証と変換がパーサーによって追加されたエラーをどのように処理するかを追跡してください。完了条件は、無効な --dats 入力が未処理の InvalidOperationException をスローするのではなく、パーサーエラーとコマンドヘルプを併せて報告することです。
索引モデルが issue の本文から書いたものです。
説明
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();
- 主要言語
- C#
- スター
- 3.7k
- フォーク
- 434
- 平均マージ
- 4時間 46分
- マージ済み PR(30日)
- 1
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートなし
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
dotnet/command-line-api のほかの issue
-
German localization is incomplete対応中かも @b-v-d-e-v が 8 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
dotnet/command-line-api#2852 ·
-
Incomplete French (fr) translation: RequiredOptionWasNotProvided not translated対応中かも @JPBlanc が 105 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 65/100
dotnet/command-line-api#2822 · コメント 1 件 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 62/100
dotnet/command-line-api#2792 · コメント 2 件 · リアクション 16 件 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 62/100
dotnet/command-line-api#2704 ·
-
GetCompletions should check exit code of invoked application対応中かも @baradgur が 1277 日前に担当しました。 オープンArea-Completions bug help wanted
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
dotnet/command-line-api#2137 · コメント 1 件 · リアクション 3 件 ·
dotnet/command-line-api の issue をすべて見る
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 62/100
PCL-Community/PCL-CE#3658 ·
メンテナーはふだん 1 日以内に返信
-
Deploy & Patch-issues opprettes ikke: create-pnd-issues.yml har feilet hver uke siden 2025-09-08オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 62/100
Altinn/altinn-auth#4359 ·
メンテナーはふだん 1 日以内に返信
-
アプリ: チャット 優先: 中 提案
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
yksr-melt/Meltype#243 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
bug core
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信
-
type/automation type/tech-debt
難易度 1/5 1時間未満 初心者へのやさしさ 72/100
メンテナーはふだん 1 日以内に返信