-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandRunner.cs
More file actions
90 lines (83 loc) · 3.27 KB
/
CommandRunner.cs
File metadata and controls
90 lines (83 loc) · 3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using CommandLine;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace RuangDeveloper.AspNetCore.Command
{
/// <summary>
/// Represents the options for the command.
/// </summary>
public class Options
{
/// <summary>
/// Gets or sets the command.
/// </summary>
[Option("command", Required = true, HelpText = "Command to execute")]
public string? Command { get; set; }
/// <summary>
/// Gets or sets the arguments for the command.
/// </summary>
[Option("args", Required = false, HelpText = "Arguments for the command")]
public IEnumerable<string>? Args { get; set; }
}
/// <summary>
/// Command runner.
/// </summary>
public static class CommandRunner
{
/// <summary>
/// Runs the host with the commands.
/// </summary>
/// <param name="host"></param>
/// <param name="args"></param>
public static void RunWithCommands(this IHost host, string[] args)
{
if (args.Length >= 1)
{
var commandConfiguration = host.Services.GetRequiredService<CommandConfiguration>();
var commandServices = host.Services.GetServices<ICommand>();
var commandIndex = args[0] == "run" ? 1 : 0;
var commandCall = args[commandIndex];
if (commandCall.Equals(commandConfiguration.CommandCallIdentifier))
{
// Get all arguments after the "command" index
var commandArgs = new List<string>();
for (var i = commandIndex; i < args.Length; i++)
{
commandArgs.Add(args[i]);
}
Parser.Default.ParseArguments<Options>(args)
.WithParsed(options =>
{
try
{
var command = commandServices.FirstOrDefault(t => t.Name == options.Command);
if (command != null)
{
var arguments = new List<string>();
if (options.Args != null)
{
arguments.AddRange(options.Args);
}
command.Execute([.. arguments]);
command.ExecuteAsync([.. arguments]).Wait();
return;
}
else
{
Console.WriteLine($"Command '{options.Command}' not found.");
return;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return;
}
});
return;
}
}
host.Run();
}
}
}