Skip to content

Commit

Permalink
优化命令行解析异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
nilaoda committed May 26, 2023
1 parent 791ece9 commit ae832e3
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions BBDown/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
using BBDown.Core.Fetcher;
using System.Text.Json.Serialization;
using System.CommandLine.Binding;
using System.CommandLine.Builder;

namespace BBDown
{
Expand Down Expand Up @@ -87,12 +88,30 @@ public static async Task<int> Main(params string[] args)
"https://github.com/nilaoda/BBDown/discussions\r\n");
Console.WriteLine();

var parser = new CommandLineBuilder(rootCommand)
.UseDefaults()
.UseExceptionHandler((ex, context) =>
{
LogError(ex.Message);
try { Console.CursorVisible = true; } catch { }
Thread.Sleep(3000);
}, 1)
.Build();

var newArgsList = new List<string>();
var commandLineResult = rootCommand.Parse(args);

//显式抛出异常
if (commandLineResult.Errors.Count > 0)
{
LogError(commandLineResult.Errors.First().Message);
return 1;
}

if (commandLineResult.CommandResult.Command.Name.ToLower() != Path.GetFileNameWithoutExtension(Environment.ProcessPath)!.ToLower())
{
newArgsList.Add(commandLineResult.CommandResult.Command.Name);
return await rootCommand.InvokeAsync(newArgsList.ToArray());
return await parser.InvokeAsync(newArgsList.ToArray());
}

foreach (var item in commandLineResult.CommandResult.Children)
Expand All @@ -112,7 +131,7 @@ public static async Task<int> Main(params string[] args)
//处理配置文件
BBDownConfigParser.HandleConfig(newArgsList, rootCommand);

return await rootCommand.InvokeAsync(newArgsList.ToArray());
return await parser.InvokeAsync(newArgsList.ToArray());
}

private static async Task DoWorkAsync(MyOption myOption)
Expand Down

0 comments on commit ae832e3

Please sign in to comment.