-
Notifications
You must be signed in to change notification settings - Fork 417
Expand file tree
/
Copy pathHostConfigurationDirective.cs
More file actions
56 lines (49 loc) · 1.91 KB
/
HostConfigurationDirective.cs
File metadata and controls
56 lines (49 loc) · 1.91 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
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System.CommandLine.Parsing;
namespace System.CommandLine.Hosting;
public class HostConfigurationDirective() : Directive(Name)
{
public new const string Name = "config";
internal static void ConfigureHostBuilder(IHostBuilder hostBuilder)
{
var parseResult = hostBuilder.GetParseResult();
if (parseResult.Configuration.RootCommand is RootCommand rootCommand &&
rootCommand.Directives.FirstOrDefault(IsConfigDirective)
is Directive configDirective &&
parseResult.GetResult(configDirective)
is DirectiveResult configResult
)
{
var configKvps = configResult.Values.Select(GetKeyValuePair)
.ToList();
hostBuilder.ConfigureHostConfiguration(
(config) => config.AddInMemoryCollection(configKvps)
);
}
static bool IsConfigDirective(Directive directive) =>
string.Equals(directive.Name, Name, StringComparison.OrdinalIgnoreCase);
[Diagnostics.CodeAnalysis.SuppressMessage(
"Style",
"IDE0057: Use range operator",
Justification = ".NET Standard 2.0"
)]
static KeyValuePair<string, string?> GetKeyValuePair(string configDirective)
{
ReadOnlySpan<char> kvpSpan = configDirective.AsSpan();
int eqlIdx = kvpSpan.IndexOf('=');
string key;
string? value = default;
if (eqlIdx < 0)
key = kvpSpan.Trim().ToString();
else
{
key = kvpSpan.Slice(0, eqlIdx).Trim().ToString();
value = kvpSpan.Slice(eqlIdx + 1).Trim().ToString();
}
return new KeyValuePair<string, string?>(key, value);
}
}
}