|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Microsoft.Extensions.Configuration; |
| 7 | + |
| 8 | +namespace J4JSoftware.CommandLine |
| 9 | +{ |
| 10 | + public static class ConfigurationExtensions |
| 11 | + { |
| 12 | + public static J4JConfigurationSource AddMapping( |
| 13 | + this J4JConfigurationSource src, |
| 14 | + string optionKey, |
| 15 | + string configKey ) |
| 16 | + { |
| 17 | + var option = src.BindingTarget |
| 18 | + .Options |
| 19 | + .FirstOrDefault( x => x.Keys.Any( |
| 20 | + k => k.Equals( optionKey, StringComparison.OrdinalIgnoreCase ) ) ); |
| 21 | + |
| 22 | + if( option == null ) |
| 23 | + return src; |
| 24 | + |
| 25 | + if( src.ConfigurationMap.ContainsKey( optionKey ) ) |
| 26 | + src.ConfigurationMap[ optionKey ] = configKey; |
| 27 | + else src.ConfigurationMap.Add( optionKey, configKey ); |
| 28 | + |
| 29 | + return src; |
| 30 | + } |
| 31 | + |
| 32 | + public static J4JConfigurationSource UsingArguments( this J4JConfigurationSource src, string[] args ) |
| 33 | + { |
| 34 | + src.Arguments = args; |
| 35 | + |
| 36 | + return src; |
| 37 | + } |
| 38 | + |
| 39 | + public class J4JConfigurationSource : IConfigurationSource |
| 40 | + { |
| 41 | + private string[]? _args; |
| 42 | + |
| 43 | + public J4JConfigurationSource( IBindingTarget bindingTgt ) |
| 44 | + { |
| 45 | + BindingTarget = bindingTgt; |
| 46 | + } |
| 47 | + |
| 48 | + public IBindingTarget BindingTarget { get; } |
| 49 | + internal Dictionary<string, string> ConfigurationMap { get; } = new Dictionary<string, string>(); |
| 50 | + |
| 51 | + public string[] Arguments |
| 52 | + { |
| 53 | + get => _args ?? Environment.GetCommandLineArgs(); |
| 54 | + internal set => _args = value; |
| 55 | + } |
| 56 | + |
| 57 | + public IConfigurationProvider Build( IConfigurationBuilder builder ) |
| 58 | + { |
| 59 | + return new J4JConfigurationProvider( this ); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public class J4JConfigurationProvider : ConfigurationProvider |
| 64 | + { |
| 65 | + public J4JConfigurationProvider( J4JConfigurationSource source ) |
| 66 | + { |
| 67 | + Source = source; |
| 68 | + } |
| 69 | + |
| 70 | + public J4JConfigurationSource Source { get; } |
| 71 | + |
| 72 | + public override void Load() |
| 73 | + { |
| 74 | + var allocations = Source.BindingTarget.AllocateCommandLineArguments( Source.Arguments ); |
| 75 | + |
| 76 | + foreach( var option in Source.BindingTarget.Options ) |
| 77 | + { |
| 78 | + foreach( var key in option.Keys ) |
| 79 | + { |
| 80 | + |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments