-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSetDefaultsFromConfigMiddleware.cs
81 lines (70 loc) · 2.85 KB
/
SetDefaultsFromConfigMiddleware.cs
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
using CommandDotNet;
using CommandDotNet.Execution;
using Jira2AzureDevOps.Logic.Framework;
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
namespace Jira2AzureDevOps.Console.Framework
{
public static class SetDefaultsFromConfigMiddleware
{
public static AppRunner UseAppSettingsForOptionDefaults(this AppRunner appRunner,
NameValueCollection nameValue = null)
{
// run before help command so help will display the updated defaults
return appRunner.Configure(c =>
{
var config = new Config
{
AppSettings = nameValue ?? ConfigurationManager.AppSettings
};
c.Services.Set(config);
// run before help so the default values can be displayed in the help text
c.UseMiddleware(SetDefaultsFromAppSettings, MiddlewareStages.PostParseInputPreBindValues, -1);
});
}
private static Task<int> SetDefaultsFromAppSettings(CommandContext context, ExecutionDelegate next)
{
if (context.ParseResult.ParseError != null)
{
return next(context);
}
var config = context.AppConfig.Services.Get<Config>();
var command = context.ParseResult.TargetCommand;
var options = command.Options.Union(command.Parent?.Options ?? Enumerable.Empty<Option>());
string GetLongNameSetting(Option option) =>
!option.LongName.IsNullOrWhiteSpace() ? config.AppSettings[$"--{option.LongName}"] : null;
string GetShortNameSetting(Option option) =>
option.ShortName.HasValue ? config.AppSettings[$"-{option.ShortName}"] : null;
foreach (var option in options)
{
string value = GetLongNameSetting(option) ?? GetShortNameSetting(option);
if (value != null)
{
if (option.Arity.AllowsZeroOrMore())
{
option.DefaultValue = value
.Split(",")
.Select(v => ConvertToDefault(option, v))
.ToList();
}
else
{
option.DefaultValue = ConvertToDefault(option, value);
}
}
}
return next(context);
}
private static object ConvertToDefault(Option option, string value) =>
option.TypeInfo.UnderlyingType.IsAssignableFrom(typeof(Password))
? (object)new Password(value)
: value;
private class Config
{
public NameValueCollection AppSettings { get; set; }
}
}
}