├── .gitignore ├── CommandLineParser.DependencyInjection.Tests ├── CommandLineParser.DependencyInjection.Tests.csproj ├── CommandLineParserDiTests.cs ├── ExecuteOptions │ ├── ExecuteAskOptions.cs │ ├── ExecuteAskOptionsAsync.cs │ ├── ExecuteParsingFailure.cs │ └── ExecuteParsingFailureAsync.cs ├── Options │ ├── AskOptions.cs │ └── AskOptionsAsync.cs └── Services │ └── DoYouLikeService.cs ├── CommandLineParser.DependencyInjection.sln ├── CommandLineParser.DependencyInjection ├── AsyncHelper.cs ├── CommandLineParser.DependencyInjection.csproj ├── CommandLineParser.cs ├── Exceptions │ └── NoExecuteCommandLineServiceFoundException.cs ├── Extensions │ ├── ServiceCollectionExtensions.cs │ └── TaskExtensions.cs └── Interfaces │ ├── ICommandLineOptions.cs │ ├── ICommandLineParser.cs │ ├── IExecuteCommandLineOptions.cs │ ├── IExecuteCommandLineOptionsAsync.cs │ ├── IExecuteParsingFailure.cs │ └── IExecuteParsingFailureAsync.cs ├── QuickStart ├── Program.cs └── QuickStart.csproj ├── license.txt └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | project.fragment.lock.json 46 | artifacts/ 47 | 48 | *_i.c 49 | *_p.c 50 | *_i.h 51 | *.ilk 52 | *.meta 53 | *.obj 54 | *.pch 55 | *.pdb 56 | *.pgc 57 | *.pgd 58 | *.rsp 59 | *.sbr 60 | *.tlb 61 | *.tli 62 | *.tlh 63 | *.tmp 64 | *.tmp_proj 65 | *.log 66 | *.vspscc 67 | *.vssscc 68 | .builds 69 | *.pidb 70 | *.svclog 71 | *.scc 72 | 73 | # Chutzpah Test files 74 | _Chutzpah* 75 | 76 | # Visual C++ cache files 77 | ipch/ 78 | *.aps 79 | *.ncb 80 | *.opendb 81 | *.opensdf 82 | *.sdf 83 | *.cachefile 84 | *.VC.db 85 | *.VC.VC.opendb 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | # TODO: Comment the next line if you want to checkin your web deploy settings 145 | # but database connection strings (with potential passwords) will be unencrypted 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 150 | # checkin your Azure Web App publish settings, but sensitive information contained 151 | # in these scripts will be unencrypted 152 | PublishScripts/ 153 | 154 | # NuGet Packages 155 | *.nupkg 156 | # The packages folder can be ignored because of Package Restore 157 | **/packages/* 158 | # except build/, which is used as an MSBuild target. 159 | !**/packages/build/ 160 | # Uncomment if necessary however generally it will be regenerated when needed 161 | #!**/packages/repositories.config 162 | # NuGet v3's project.json files produces more ignoreable files 163 | *.nuget.props 164 | *.nuget.targets 165 | 166 | # Microsoft Azure Build Output 167 | csx/ 168 | *.build.csdef 169 | 170 | # Microsoft Azure Emulator 171 | ecf/ 172 | rcf/ 173 | 174 | # Windows Store app package directories and files 175 | AppPackages/ 176 | BundleArtifacts/ 177 | Package.StoreAssociation.xml 178 | _pkginfo.txt 179 | 180 | # Visual Studio cache files 181 | # files ending in .cache can be ignored 182 | *.[Cc]ache 183 | # but keep track of directories ending in .cache 184 | !*.[Cc]ache/ 185 | 186 | # Others 187 | ClientBin/ 188 | ~$* 189 | *~ 190 | *.dbmdl 191 | *.dbproj.schemaview 192 | *.jfm 193 | *.pfx 194 | *.publishsettings 195 | node_modules/ 196 | orleans.codegen.cs 197 | 198 | # Since there are multiple workflows, uncomment next line to ignore bower_components 199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 200 | #bower_components/ 201 | 202 | # RIA/Silverlight projects 203 | Generated_Code/ 204 | 205 | # Backup & report files from converting an old project file 206 | # to a newer Visual Studio version. Backup files are not needed, 207 | # because we have git ;-) 208 | _UpgradeReport_Files/ 209 | Backup*/ 210 | UpgradeLog*.XML 211 | UpgradeLog*.htm 212 | 213 | # SQL Server files 214 | *.mdf 215 | *.ldf 216 | 217 | # Business Intelligence projects 218 | *.rdl.data 219 | *.bim.layout 220 | *.bim_*.settings 221 | 222 | # Microsoft Fakes 223 | FakesAssemblies/ 224 | 225 | # GhostDoc plugin setting file 226 | *.GhostDoc.xml 227 | 228 | # Node.js Tools for Visual Studio 229 | .ntvs_analysis.dat 230 | 231 | # Visual Studio 6 build log 232 | *.plg 233 | 234 | # Visual Studio 6 workspace options file 235 | *.opt 236 | 237 | # Visual Studio LightSwitch build output 238 | **/*.HTMLClient/GeneratedArtifacts 239 | **/*.DesktopClient/GeneratedArtifacts 240 | **/*.DesktopClient/ModelManifest.xml 241 | **/*.Server/GeneratedArtifacts 242 | **/*.Server/ModelManifest.xml 243 | _Pvt_Extensions 244 | 245 | # Paket dependency manager 246 | .paket/paket.exe 247 | paket-files/ 248 | 249 | # FAKE - F# Make 250 | .fake/ 251 | 252 | # JetBrains Rider 253 | .idea/ 254 | *.sln.iml 255 | 256 | # CodeRush 257 | .cr/ 258 | 259 | # Python Tools for Visual Studio (PTVS) 260 | __pycache__/ 261 | *.pyc -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/CommandLineParser.DependencyInjection.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net5.0 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/CommandLineParserDiTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Threading.Tasks; 5 | using CommandLineParser.DependencyInjection.Interfaces; 6 | using CommandLineParser.DependencyInjection.Tests.Services; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using Xunit; 9 | 10 | namespace CommandLineParser.DependencyInjection.Tests 11 | { 12 | public class CommandLineParserDiTests 13 | { 14 | protected IServiceProvider ServiceProvider { get; set; } 15 | 16 | public CommandLineParserDiTests() 17 | { 18 | var collection = new ServiceCollection() 19 | .AddCommandLineParser(typeof(CommandLineParserDiTests).Assembly) 20 | .AddSingleton() 21 | ; 22 | ServiceProvider = collection.BuildServiceProvider(); 23 | } 24 | 25 | [Fact] 26 | public void AskOptionsExecutionTest() 27 | { 28 | var service = ServiceProvider.GetRequiredService>(); 29 | Assert.Equal("I do not like them, Sam I Am! I do not like Green Eggs and Ham.", service.ParseArguments(new[] { "ask", "Green Eggs and Ham" })); 30 | Assert.Equal("Yes, I do like Green Eggs and Ham! Thank you, Thank you Sam I Am!", service.ParseArguments(new[] { "ask", "Green Eggs and Ham", "--like", "true" })); 31 | Assert.Equal("I do not like them, Sam I Am! I do not like ASYNC Green Eggs and Ham.", service.ParseArguments(new[] { "askAsync", "Green Eggs and Ham" })); 32 | Assert.Equal("Yes, I do like ASYNC Green Eggs and Ham! Thank you, Thank you Sam I Am!", service.ParseArguments(new[] { "askAsync", "Green Eggs and Ham", "--like", "true" })); 33 | } 34 | 35 | [Fact] 36 | public async Task AskOptionsExecutionAsyncTest() 37 | { 38 | var service = ServiceProvider.GetRequiredService>(); 39 | Assert.Equal("I do not like them, Sam I Am! I do not like Green Eggs and Ham.", await service.ParseArgumentsAsync(new[] { "ask", "Green Eggs and Ham" })); 40 | Assert.Equal("Yes, I do like Green Eggs and Ham! Thank you, Thank you Sam I Am!", await service.ParseArgumentsAsync(new[] { "ask", "Green Eggs and Ham", "--like", "true" })); 41 | Assert.Equal("I do not like them, Sam I Am! I do not like ASYNC Green Eggs and Ham.", await service.ParseArgumentsAsync(new[] { "askAsync", "Green Eggs and Ham" })); 42 | Assert.Equal("Yes, I do like ASYNC Green Eggs and Ham! Thank you, Thank you Sam I Am!", await service.ParseArgumentsAsync(new[] { "askAsync", "Green Eggs and Ham", "--like", "true" })); 43 | } 44 | 45 | [Fact] 46 | public void OptionsExecutionFailureTest() 47 | { 48 | var service = ServiceProvider.GetRequiredService>(); 49 | Assert.Equal("Unable to parse \"-filename testfile.txt\".", service.ParseArguments(new[] { "-filename", "testfile.txt" })); 50 | } 51 | 52 | [Fact] 53 | public async Task OptionsExecutionFailureAsyncTest() 54 | { 55 | var service = ServiceProvider.GetRequiredService>(); 56 | Assert.Equal("Unable to parse \"-filename testfile.txt\" ASYNC.", await service.ParseArgumentsAsync(new[] { "-filename", "testfile.txt" })); 57 | } 58 | 59 | [Fact] 60 | public void HelpTests() 61 | { 62 | var name = Assembly.GetEntryAssembly().GetCustomAttribute()?.Title ?? Assembly.GetCallingAssembly().GetName().Name; 63 | var version = Assembly.GetEntryAssembly().GetCustomAttribute()?.InformationalVersion ?? Assembly.GetCallingAssembly().GetName().Version.ToString(); 64 | var service = ServiceProvider.GetRequiredService>(); 65 | using (var writer = new StringWriter()) 66 | { 67 | service.ParseArguments(new string[0], o => o.HelpWriter = writer); 68 | Assert.Equal($"{name} {version}\r\nCopyright (C) 2024 JetBrains s.r.o.\r\n\r\nERROR(S):\r\n No verb selected.\r\n\r\n ask Ask a question.\r\n\r\n askAsync Ask a question ASYNC.\r\n\r\n help Display more information on a specific command.\r\n\r\n version Display version information.\r\n\r\n", writer.ToString()); 69 | } 70 | using (var writer = new StringWriter()) 71 | { 72 | service.ParseArguments(new [] {"ask", "--help"}, o => o.HelpWriter = writer); 73 | Assert.Equal($"{name} {version}\r\nCopyright (C) 2024 JetBrains s.r.o.\r\nUSAGE:\r\nDo you like green eggs and ham?:\r\n CommandLineParserDiTests ask --like \"Green Eggs and Ham?\"\r\n\r\n --like (Default: false) Should we like this?\r\n\r\n --help Display this help screen.\r\n\r\n --version Display version information.\r\n\r\n value pos. 0 Required. What do we like?\r\n\r\n", writer.ToString()); 74 | } 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/ExecuteOptions/ExecuteAskOptions.cs: -------------------------------------------------------------------------------- 1 | using CommandLineParser.DependencyInjection.Interfaces; 2 | using CommandLineParser.DependencyInjection.Tests.Options; 3 | using CommandLineParser.DependencyInjection.Tests.Services; 4 | 5 | namespace CommandLineParser.DependencyInjection.Tests.ExecuteOptions 6 | { 7 | class ExecuteAskOptions : IExecuteCommandLineOptions 8 | { 9 | private readonly DoYouLikeService _doYouLikeService; 10 | 11 | public ExecuteAskOptions(DoYouLikeService doYouLikeService) 12 | { 13 | _doYouLikeService = doYouLikeService; 14 | } 15 | 16 | #region Implementation of IExecuteCommandLineOptions 17 | 18 | /// 19 | /// Execute Command Synchronously. 20 | /// 21 | /// Command Line Options 22 | /// Result 23 | public string Execute(AskOptions options) 24 | { 25 | return _doYouLikeService.DoILikeThis(options.DoYouLike, options.Like, false); 26 | } 27 | 28 | #endregion 29 | } 30 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/ExecuteOptions/ExecuteAskOptionsAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using CommandLineParser.DependencyInjection.Interfaces; 3 | using CommandLineParser.DependencyInjection.Tests.Options; 4 | using CommandLineParser.DependencyInjection.Tests.Services; 5 | 6 | namespace CommandLineParser.DependencyInjection.Tests.ExecuteOptions 7 | { 8 | class ExecuteAskOptionsAsync : IExecuteCommandLineOptionsAsync 9 | { 10 | private readonly DoYouLikeService _doYouLikeService; 11 | 12 | public ExecuteAskOptionsAsync(DoYouLikeService doYouLikeService) 13 | { 14 | _doYouLikeService = doYouLikeService; 15 | } 16 | 17 | #region Implementation of IExecuteCommandLineOptionsAsync 18 | 19 | /// 20 | /// Execute Command Asynchronously. 21 | /// 22 | /// Command Line Options 23 | /// Result 24 | public Task ExecuteAsync(AskOptionsAsync options) 25 | { 26 | return Task.FromResult(_doYouLikeService.DoILikeThis(options.DoYouLike, options.Like, true)); 27 | } 28 | 29 | #endregion 30 | } 31 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/ExecuteOptions/ExecuteParsingFailure.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CommandLine; 3 | using CommandLineParser.DependencyInjection.Interfaces; 4 | 5 | namespace CommandLineParser.DependencyInjection.Tests.ExecuteOptions 6 | { 7 | class ExecuteParsingFailure : IExecuteParsingFailure 8 | { 9 | #region Implementation of IExecuteParsingFailure 10 | 11 | /// 12 | /// Execute Command Synchronously. 13 | /// 14 | /// Arguments that were passed into the parser. 15 | /// Errors as reported from the parser. 16 | /// Result 17 | public string Execute(string[] args, IEnumerable errors) => $"Unable to parse \"{string.Join(' ', args)}\"."; 18 | #endregion 19 | } 20 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/ExecuteOptions/ExecuteParsingFailureAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using CommandLine; 4 | using CommandLineParser.DependencyInjection.Interfaces; 5 | 6 | namespace CommandLineParser.DependencyInjection.Tests.ExecuteOptions 7 | { 8 | class ExecuteParsingFailureAsync : IExecuteParsingFailureAsync 9 | { 10 | #region Implementation of IExecuteParsingFailureAsync 11 | 12 | /// 13 | /// Execute Command Asynchronously. 14 | /// 15 | /// Arguments that were passed into the parser. 16 | /// Errors as reported from the parser. 17 | /// Result 18 | public Task ExecuteAsync(string[] args, IEnumerable errors) => Task.FromResult($"Unable to parse \"{string.Join(' ', args)}\" ASYNC."); 19 | 20 | #endregion 21 | } 22 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/Options/AskOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CommandLine; 3 | using CommandLine.Text; 4 | using CommandLineParser.DependencyInjection.Interfaces; 5 | 6 | namespace CommandLineParser.DependencyInjection.Tests.Options 7 | { 8 | [Verb("ask", HelpText = "Ask a question.")] 9 | class AskOptions : ICommandLineOptions 10 | { 11 | [Option("like", Required = false, Default = false, HelpText = "Should we like this?")] 12 | public bool Like { get; set; } 13 | 14 | [Value(0, Required = true, HelpText = "What do we like?")] 15 | public string DoYouLike { get; set; } 16 | 17 | [Usage(ApplicationAlias = "CommandLineParserDiTests")] 18 | public static IEnumerable Examples => 19 | new List() { 20 | new Example("Do you like green eggs and ham?", new AskOptions { DoYouLike = "Green Eggs and Ham?", Like = true }) 21 | }; 22 | } 23 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/Options/AskOptionsAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CommandLine; 3 | using CommandLine.Text; 4 | using CommandLineParser.DependencyInjection.Interfaces; 5 | 6 | namespace CommandLineParser.DependencyInjection.Tests.Options 7 | { 8 | [Verb("askAsync", HelpText = "Ask a question ASYNC.")] 9 | class AskOptionsAsync : ICommandLineOptions 10 | { 11 | [Option("like", Required = false, Default = false, HelpText = "Should we like this?")] 12 | public bool Like { get; set; } 13 | 14 | [Value(0, Required = true, HelpText = "What do we like?")] 15 | public string DoYouLike { get; set; } 16 | 17 | [Usage(ApplicationAlias = "CommandLineParserDiTests")] 18 | public static IEnumerable Examples => 19 | new List() { 20 | new Example("Do you like green eggs and ham?", new AskOptions { DoYouLike = "Green Eggs and Ham?", Like = true }) 21 | }; 22 | } 23 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.Tests/Services/DoYouLikeService.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace CommandLineParser.DependencyInjection.Tests.Services 3 | { 4 | class DoYouLikeService 5 | { 6 | public string DoILikeThis(string thing, bool like, bool async) => 7 | async 8 | ? like 9 | ? $"Yes, I do like ASYNC {thing}! Thank you, Thank you Sam I Am!" 10 | : $"I do not like them, Sam I Am! I do not like ASYNC {thing}." 11 | : like 12 | ? $"Yes, I do like {thing}! Thank you, Thank you Sam I Am!" 13 | : $"I do not like them, Sam I Am! I do not like {thing}."; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.10.35027.167 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommandLineParser.DependencyInjection", "CommandLineParser.DependencyInjection\CommandLineParser.DependencyInjection.csproj", "{7B3F7B26-B85B-4D35-BD5E-A2FAE8375008}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CommandLineParser.DependencyInjection.Tests", "CommandLineParser.DependencyInjection.Tests\CommandLineParser.DependencyInjection.Tests.csproj", "{72B442E6-654D-4CC9-9995-0F10B86B686A}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A7353A99-C73A-4750-B658-4823E3FF3A63}" 11 | ProjectSection(SolutionItems) = preProject 12 | license.txt = license.txt 13 | readme.md = readme.md 14 | EndProjectSection 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QuickStart", "QuickStart\QuickStart.csproj", "{18B8EC8C-D181-4057-9160-C0A8E6B8E3EE}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {7B3F7B26-B85B-4D35-BD5E-A2FAE8375008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {7B3F7B26-B85B-4D35-BD5E-A2FAE8375008}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {7B3F7B26-B85B-4D35-BD5E-A2FAE8375008}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {7B3F7B26-B85B-4D35-BD5E-A2FAE8375008}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {72B442E6-654D-4CC9-9995-0F10B86B686A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {72B442E6-654D-4CC9-9995-0F10B86B686A}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {72B442E6-654D-4CC9-9995-0F10B86B686A}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {72B442E6-654D-4CC9-9995-0F10B86B686A}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {18B8EC8C-D181-4057-9160-C0A8E6B8E3EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {18B8EC8C-D181-4057-9160-C0A8E6B8E3EE}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {18B8EC8C-D181-4057-9160-C0A8E6B8E3EE}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {18B8EC8C-D181-4057-9160-C0A8E6B8E3EE}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | GlobalSection(SolutionProperties) = preSolution 38 | HideSolutionNode = FALSE 39 | EndGlobalSection 40 | GlobalSection(ExtensibilityGlobals) = postSolution 41 | SolutionGuid = {55911917-AEF0-4E83-BCA4-6C31A8A4DF72} 42 | EndGlobalSection 43 | EndGlobal 44 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/AsyncHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | 5 | namespace CommandLineParser.DependencyInjection 6 | { 7 | /// 8 | /// Async Helper to run Async Task's Synchronously. 9 | /// 10 | public static class AsyncHelper 11 | { 12 | private static readonly TaskFactory TaskFactory = new 13 | TaskFactory(CancellationToken.None, 14 | TaskCreationOptions.None, 15 | TaskContinuationOptions.None, 16 | TaskScheduler.Default); 17 | 18 | /// 19 | /// Run an Async task Synchronously and return the result. 20 | /// 21 | /// Result Type 22 | /// Async Task 23 | /// Async Task's Result 24 | public static TResult RunSync(Func> func) 25 | { 26 | return TaskFactory 27 | .StartNew(func) 28 | .Unwrap() 29 | .GetAwaiter() 30 | .GetResult(); 31 | } 32 | 33 | /// 34 | /// Run an Async task Synchronously. 35 | /// 36 | /// Async Task 37 | public static void RunSync(Func func) 38 | { 39 | TaskFactory 40 | .StartNew(func) 41 | .Unwrap() 42 | .GetAwaiter() 43 | .GetResult(); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/CommandLineParser.DependencyInjection.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | Microsoft Dependency Injection extensions for CommandLineParser (https://github.com/commandlineparser/commandline) 6 | Added support for Async parsing/execution. 7 | CommandLineParser.DependencyInjection 8 | CommandLineParser.DependencyInjection 9 | True 10 | 1.1.1 11 | False 12 | CommandLineParser.DependencyInjection 13 | CommandLineParser.DependencyInjection 14 | readme.md 15 | license.txt 16 | Jaron Horst 17 | https://github.com/JaronrH/CommandLineParser.DependencyInjection 18 | https://github.com/JaronrH/CommandLineParser.DependencyInjection 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/CommandLineParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Threading.Tasks; 6 | using CommandLine; 7 | using CommandLineParser.DependencyInjection.Exceptions; 8 | using CommandLineParser.DependencyInjection.Extensions; 9 | using CommandLineParser.DependencyInjection.Interfaces; 10 | using Microsoft.Extensions.DependencyInjection; 11 | 12 | namespace CommandLineParser.DependencyInjection 13 | { 14 | public class CommandLineParser : ICommandLineParser 15 | { 16 | private static readonly Type ExecuteCommandLineOptionsInterfaceType = typeof(IExecuteCommandLineOptions<,>); 17 | private static readonly Type ExecuteCommandLineOptionsAsyncInterfaceType = typeof(IExecuteCommandLineOptionsAsync<,>); 18 | private readonly Type[] _commandLineOptionTypes; 19 | private readonly IServiceProvider _serviceProvider; 20 | 21 | public CommandLineParser(IEnumerable commandLineOptions, IServiceProvider serviceProvider) 22 | { 23 | _commandLineOptionTypes = commandLineOptions.Select(i => i.GetType()).ToArray(); 24 | _serviceProvider = serviceProvider; 25 | } 26 | 27 | #region Implementation of ICommandLineParser 28 | 29 | /// 30 | /// Parse Command Line Arguments using . 31 | /// 32 | /// Command Line Arguments. 33 | /// Optional Parser Configuration Action. 34 | /// Default Result to return when parser was unable to parse out options. 35 | /// Fall back to and/or implementations an run them synchronously when synchronous version are not available? 36 | /// Result [code]. 37 | public TResult ParseArguments(string[] args, Action configuration = null, TResult defaultResult = default, 38 | bool allowAsyncImplementations = true) 39 | { 40 | // Create Parser 41 | using var parser = configuration == null 42 | ? new Parser() 43 | : new Parser(configuration); 44 | 45 | // Execute Parser 46 | var result = _commandLineOptionTypes.Count() == 1 && _commandLineOptionTypes.All(i => !i.GetCustomAttributes().Any()) 47 | ? parser.ParseArguments(() => Activator.CreateInstance(_commandLineOptionTypes.First()), args) 48 | : parser.ParseArguments(args, _commandLineOptionTypes); 49 | 50 | // Parser Execute successfully? 51 | if (result.Tag == ParserResultType.Parsed) 52 | { 53 | // Get Parsed Value 54 | var parsed = result as Parsed; 55 | 56 | // Look for Sync Types to execute 57 | var type = 58 | ExecuteCommandLineOptionsInterfaceType.MakeGenericType(result.TypeInfo.Current, 59 | typeof(TResult)); 60 | var methodType = type.GetMethod("Execute"); 61 | var executingService = _serviceProvider.GetService(type); 62 | if (executingService != null && parsed != null) 63 | return (TResult)methodType.Invoke(executingService, new[] { parsed.Value }); 64 | 65 | // Look for Async? 66 | if (allowAsyncImplementations) 67 | { 68 | type = 69 | ExecuteCommandLineOptionsAsyncInterfaceType.MakeGenericType(result.TypeInfo.Current, 70 | typeof(TResult)); 71 | methodType = type.GetMethod("ExecuteAsync"); 72 | executingService = _serviceProvider.GetService(type); 73 | if (executingService != null && parsed != null) 74 | return AsyncHelper.RunSync(async () => await methodType.InvokeAsync(executingService, new[] { parsed.Value })); 75 | } 76 | 77 | // Throw exception if Parser ran but no service was found to handle the results. 78 | throw new NoExecuteCommandLineServiceFoundException(result.TypeInfo.Current, typeof(TResult), true, 79 | allowAsyncImplementations); 80 | } 81 | 82 | // ...Parser failed? 83 | var service = _serviceProvider.GetService>(); 84 | var serviceAsync = _serviceProvider.GetService>(); 85 | return service == null 86 | ? serviceAsync == null || !allowAsyncImplementations 87 | ? defaultResult 88 | : AsyncHelper.RunSync(async () => await serviceAsync.ExecuteAsync(args, (result as NotParsed)?.Errors ?? Enumerable.Empty())) 89 | : service.Execute(args, (result as NotParsed)?.Errors ?? Enumerable.Empty()); 90 | } 91 | 92 | /// 93 | /// Parse Command Line Arguments using . 94 | /// 95 | /// Command Line Arguments. 96 | /// Optional Parser Configuration Action. 97 | /// Default Result to return when parser was unable to parse out options. 98 | /// Fall back to and/or implementations asynchronous version are not available? 99 | /// Result [code]. 100 | public async Task ParseArgumentsAsync(string[] args, Action configuration = null, TResult defaultResult = default, 101 | bool allowSyncImplementations = true) 102 | { 103 | // Create Parser 104 | using var parser = configuration == null 105 | ? new Parser() 106 | : new Parser(configuration); 107 | 108 | // Execute Parser 109 | var result = _commandLineOptionTypes.Count() == 1 && _commandLineOptionTypes.All(i => !i.GetCustomAttributes().Any()) 110 | ? parser.ParseArguments(() => Activator.CreateInstance(_commandLineOptionTypes.First()), args) 111 | : parser.ParseArguments(args, _commandLineOptionTypes); 112 | 113 | // Parser Execute successfully? 114 | if (result.Tag == ParserResultType.Parsed) 115 | { 116 | // Get Parsed Value 117 | var parsed = result as Parsed; 118 | 119 | // Look for Sync Types to execute 120 | var type = 121 | ExecuteCommandLineOptionsAsyncInterfaceType.MakeGenericType(result.TypeInfo.Current, 122 | typeof(TResult)); 123 | var methodType = type.GetMethod("ExecuteAsync"); 124 | var executingService = _serviceProvider.GetService(type); 125 | if (executingService != null && parsed != null) 126 | return await methodType.InvokeAsync(executingService, new[] { parsed.Value }); 127 | 128 | // Look for Async? 129 | if (allowSyncImplementations) 130 | { 131 | type = 132 | ExecuteCommandLineOptionsInterfaceType.MakeGenericType(result.TypeInfo.Current, 133 | typeof(TResult)); 134 | methodType = type.GetMethod("Execute"); 135 | executingService = _serviceProvider.GetService(type); 136 | if (executingService != null && parsed != null) 137 | return (TResult)methodType.Invoke(executingService, new[] { parsed.Value }); 138 | } 139 | 140 | // Throw exception if Parser ran but no service was found to handle the results. 141 | throw new NoExecuteCommandLineServiceFoundException(result.TypeInfo.Current, typeof(TResult), true, 142 | allowSyncImplementations); 143 | } 144 | 145 | // ...Parser failed? 146 | var serviceAsync = _serviceProvider.GetService>(); 147 | var service = _serviceProvider.GetService>(); 148 | return serviceAsync == null 149 | ? service == null || !allowSyncImplementations 150 | ? defaultResult 151 | : service.Execute(args, (result as NotParsed)?.Errors ?? Enumerable.Empty()) 152 | : await serviceAsync.ExecuteAsync(args, (result as NotParsed)?.Errors ?? Enumerable.Empty()); 153 | } 154 | 155 | #endregion 156 | } 157 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Exceptions/NoExecuteCommandLineServiceFoundException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace CommandLineParser.DependencyInjection.Exceptions 4 | { 5 | /// 6 | /// Exception thrown when the Command Line Parser was able to get the Options but there was no service found to handle it. 7 | /// 8 | public class NoExecuteCommandLineServiceFoundException : Exception 9 | { 10 | /// 11 | /// Create new Exception 12 | /// 13 | /// Options Type 14 | /// Result Type 15 | /// Was run synchronously? 16 | /// Was the sync/async allowed to fallback to async/sync? 17 | public NoExecuteCommandLineServiceFoundException(Type optionsType, Type resultType, bool isSynchronous, bool allowFallback) 18 | { 19 | OptionsType = optionsType; 20 | ResultType = resultType; 21 | IsSynchronous = isSynchronous; 22 | AllowFallback = allowFallback; 23 | } 24 | 25 | /// 26 | /// Options Type 27 | /// 28 | public Type OptionsType { get; } 29 | 30 | /// 31 | /// Result Type 32 | /// 33 | public Type ResultType { get; } 34 | 35 | /// 36 | /// Was run synchronously? 37 | /// 38 | public bool IsSynchronous { get; } 39 | 40 | /// 41 | /// Was the sync/async allowed to fallback to async/sync? 42 | /// 43 | public bool AllowFallback { get; } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Extensions/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Reflection; 3 | using CommandLineParser.DependencyInjection.Interfaces; 4 | 5 | // ReSharper disable once CheckNamespace 6 | namespace Microsoft.Extensions.DependencyInjection 7 | { 8 | public static class ServiceCollectionExtensions 9 | { 10 | /// 11 | /// Add Command Line Parser Extensions. 12 | /// 13 | /// Service Collection to add service to. 14 | /// Assemblies to scan for , , and . 15 | public static IServiceCollection AddCommandLineParser(this IServiceCollection services, 16 | params Assembly[] assemblies) 17 | { 18 | var executeCommandLineOptionsInterface = typeof(IExecuteCommandLineOptions<,>); 19 | var executeParsingFailureInterface = typeof(IExecuteParsingFailure<>); 20 | var executeCommandLineOptionsAsyncInterface = typeof(IExecuteCommandLineOptionsAsync<,>); 21 | var executeParsingFailureAsyncInterface = typeof(IExecuteParsingFailureAsync<>); 22 | return services 23 | .Scan(a => a 24 | .FromAssemblies(assemblies) 25 | .AddClasses(i => i.AssignableTo()) 26 | .As() 27 | ) 28 | .Scan(a => a 29 | .FromAssemblies(assemblies) 30 | .AddClasses(i => i.AssignableTo(executeCommandLineOptionsInterface)) 31 | .As(t => t.GetInterfaces().Where(i => i.IsConstructedGenericType && executeCommandLineOptionsInterface.IsAssignableFrom(i.GetGenericTypeDefinition()))) 32 | ) 33 | .Scan(a => a 34 | .FromAssemblies(assemblies) 35 | .AddClasses(i => i.AssignableTo(executeCommandLineOptionsAsyncInterface)) 36 | .As(t => t.GetInterfaces().Where(i => i.IsConstructedGenericType && executeCommandLineOptionsAsyncInterface.IsAssignableFrom(i.GetGenericTypeDefinition()))) 37 | ) 38 | .Scan(a => a 39 | .FromAssemblies(assemblies) 40 | .AddClasses(i => i.AssignableTo(executeParsingFailureInterface)) 41 | .As(t => t.GetInterfaces().Where(i => i.IsConstructedGenericType && executeParsingFailureInterface.IsAssignableFrom(i.GetGenericTypeDefinition()))) 42 | ) 43 | .Scan(a => a 44 | .FromAssemblies(assemblies) 45 | .AddClasses(i => i.AssignableTo(executeParsingFailureAsyncInterface)) 46 | .As(t => t.GetInterfaces().Where(i => i.IsConstructedGenericType && executeParsingFailureAsyncInterface.IsAssignableFrom(i.GetGenericTypeDefinition()))) 47 | ) 48 | .AddSingleton(typeof(ICommandLineParser<>), typeof(CommandLineParser.DependencyInjection.CommandLineParser<>)) 49 | ; 50 | ; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Extensions/TaskExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Threading.Tasks; 3 | 4 | namespace CommandLineParser.DependencyInjection.Extensions 5 | { 6 | public static class TaskExtensions 7 | { 8 | public static async Task InvokeAsync(this MethodInfo @this, object obj, params object[] parameters) 9 | { 10 | var awaitable = (Task)@this.Invoke(obj, parameters); 11 | await awaitable; 12 | return awaitable.GetAwaiter().GetResult(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Interfaces/ICommandLineOptions.cs: -------------------------------------------------------------------------------- 1 | namespace CommandLineParser.DependencyInjection.Interfaces 2 | { 3 | /// 4 | /// Command Line Interface. 5 | /// 6 | public interface ICommandLineOptions { } 7 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Interfaces/ICommandLineParser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using CommandLine; 4 | 5 | namespace CommandLineParser.DependencyInjection.Interfaces 6 | { 7 | /// 8 | /// Wrapper for the which leverages to get the Options () 9 | /// and execute either the corresponding or . 10 | /// 11 | /// All services are Singleton's and should only be registered once in the DI container. , while resolved, are not 12 | /// used from DI but rather just used to get the types from DI to register in the parser. 13 | /// 14 | /// 15 | public interface ICommandLineParser 16 | { 17 | /// 18 | /// Parse Command Line Arguments using . 19 | /// 20 | /// Command Line Arguments. 21 | /// Optional Parser Configuration Action. 22 | /// Default Result to return when parser was unable to parse out options. 23 | /// Fall back to and/or implementations an run them synchronously when synchronous version are not available? 24 | /// Result [code]. 25 | TResult ParseArguments(string[] args, Action configuration = null, TResult defaultResult = default, bool allowAsyncImplementations = true); 26 | 27 | /// 28 | /// Parse Command Line Arguments using . 29 | /// 30 | /// Command Line Arguments. 31 | /// Optional Parser Configuration Action. 32 | /// Default Result to return when parser was unable to parse out options. 33 | /// Fall back to and/or implementations asynchronous version are not available? 34 | /// Result [code]. 35 | Task ParseArgumentsAsync(string[] args, Action configuration = null, TResult defaultResult = default, bool allowSyncImplementations = true); 36 | 37 | /// 38 | /// Parse Command Line Arguments using . 39 | /// 40 | /// Command Line Arguments. 41 | /// Default Result to return when parser was unable to parse out options. 42 | /// Fall back to and/or implementations an run them synchronously when synchronous version are not available? 43 | /// Result [code]. 44 | TResult ParseArguments(string[] args, TResult defaultResult, bool allowAsyncImplementations = true) => 45 | ParseArguments(args, null, defaultResult, allowAsyncImplementations); 46 | 47 | /// 48 | /// Parse Command Line Arguments using . 49 | /// 50 | /// Command Line Arguments. 51 | /// Default Result to return when parser was unable to parse out options. 52 | /// Fall back to and/or implementations asynchronous version are not available? 53 | /// Result [code]. 54 | Task ParseArgumentsAsync(string[] args, TResult defaultResult, 55 | bool allowSyncImplementations = true) => 56 | ParseArgumentsAsync(args, null, defaultResult, allowSyncImplementations); 57 | } 58 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Interfaces/IExecuteCommandLineOptions.cs: -------------------------------------------------------------------------------- 1 | namespace CommandLineParser.DependencyInjection.Interfaces 2 | { 3 | /// 4 | /// Execute Command Line Synchronously. 5 | /// 6 | /// Command Line Options this executor handles. 7 | /// Results 8 | public interface IExecuteCommandLineOptions where TCommandLineOptions : ICommandLineOptions 9 | { 10 | /// 11 | /// Execute Command Synchronously. 12 | /// 13 | /// Command Line Options 14 | /// Result 15 | TResult Execute(TCommandLineOptions options); 16 | } 17 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Interfaces/IExecuteCommandLineOptionsAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace CommandLineParser.DependencyInjection.Interfaces 4 | { 5 | /// 6 | /// Execute Command Line Asynchronously. 7 | /// 8 | /// Command Line Options this executor handles. 9 | /// Results 10 | public interface IExecuteCommandLineOptionsAsync where TCommandLineOptions : ICommandLineOptions 11 | { 12 | /// 13 | /// Execute Command Asynchronously. 14 | /// 15 | /// Command Line Options 16 | /// Result 17 | Task ExecuteAsync(TCommandLineOptions options); 18 | } 19 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Interfaces/IExecuteParsingFailure.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using CommandLine; 3 | 4 | namespace CommandLineParser.DependencyInjection.Interfaces 5 | { 6 | /// 7 | /// Synchronously Execute on Parsing Failure. 8 | /// 9 | /// Results 10 | public interface IExecuteParsingFailure 11 | { 12 | /// 13 | /// Execute Command Synchronously. 14 | /// 15 | /// Arguments that were passed into the parser. 16 | /// Errors as reported from the parser. 17 | /// Result 18 | TResult Execute(string[] args, IEnumerable errors); 19 | } 20 | } -------------------------------------------------------------------------------- /CommandLineParser.DependencyInjection/Interfaces/IExecuteParsingFailureAsync.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using CommandLine; 4 | 5 | namespace CommandLineParser.DependencyInjection.Interfaces 6 | { 7 | /// 8 | /// Asynchronously Execute on Parsing Failure. 9 | /// 10 | /// Results 11 | public interface IExecuteParsingFailureAsync 12 | { 13 | /// 14 | /// Execute Command Asynchronously. 15 | /// 16 | /// Arguments that were passed into the parser. 17 | /// Errors as reported from the parser. 18 | /// Result 19 | Task ExecuteAsync(string[] args, IEnumerable errors); 20 | } 21 | } -------------------------------------------------------------------------------- /QuickStart/Program.cs: -------------------------------------------------------------------------------- 1 | using CommandLine; 2 | using CommandLineParser.DependencyInjection.Interfaces; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging; 5 | 6 | new ServiceCollection() // Create Service Collection 7 | .AddCommandLineParser(typeof(Options).Assembly) // Add CommandLineParser registrations to DI 8 | .AddLogging(c => c.AddConsole()) // Add Console Logging 9 | .BuildServiceProvider() // Build Service Provider 10 | .GetRequiredService>() // Get Parser Service 11 | .ParseArguments(args, -1) // Call Parser with Arguments (Options and ExecuteOptions will be loaded from DI as needed) 12 | ; 13 | 14 | public class Options: ICommandLineOptions 15 | { 16 | [Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")] 17 | public bool Verbose { get; set; } 18 | } 19 | 20 | public class ExecuteOptions(ILogger log) : IExecuteCommandLineOptions 21 | { 22 | #region Implementation of IExecuteCommandLineOptions 23 | 24 | /// 25 | /// Execute Command Synchronously. 26 | /// 27 | /// Command Line Options 28 | /// Result 29 | public int Execute(Options options) 30 | { 31 | if (options.Verbose) 32 | { 33 | log.LogInformation($"Verbose output enabled. Current Arguments: -v {options.Verbose}"); 34 | log.LogWarning("Quick Start Example! App is in Verbose mode!"); 35 | } 36 | else 37 | { 38 | log.LogInformation($"Current Arguments: -v {options.Verbose}"); 39 | log.LogInformation("Quick Start Example!"); 40 | } 41 | 42 | return 0; 43 | } 44 | 45 | #endregion 46 | } -------------------------------------------------------------------------------- /QuickStart/QuickStart.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024, Jaron Horst 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # CommandLineParser.DependencyInjection 2 | 3 | This is a simple wrapper around the amazing [commandlineparser/commandline](https://github.com/commandlineparser/commandline) library which adds support for Microsoft's DI with help from [Scrutor](https://github.com/khellang/Scrutor). This is done by allow the following interfaces to be implemented which DI will find and user for executing the commandlineparser. 4 | 5 | |Interface|Description | 6 | |--|--| 7 | |ICommandLineOptions | This is an empty interface that is used solely for DI to find options! Make a class with [Options](https://github.com/commandlineparser/commandline/wiki/Option-Attribute) just like the CommandLineParser library instructs! | 8 | |ICommandLineParser< TResult >| This is the DI Service you will use to access the [Parser](https://github.com/commandlineparser/commandline/wiki/Getting-Started) and execute the relevant DI Service for IExecuteCommandLineOptions/IExecuteCommandLineOptionsAsync. It has the ability to run both synchronously or asynchronously. | 9 | |IExecuteCommandLineOptions| Interface that implements Execute(options) synchronously with the Parser's Command Line Options. | 10 | |IExecuteCommandLineOptionsAsync| Interface that implements ExecuteAsync(options) asynchronously with the Parser's Command Line Options. | 11 | |IExecuteParsingFailure| If no Options/Handler found, this is called synchronously with the executed arguments array and parser errors to handle the inability to handle the command line input arguments. | 12 | |IExecuteParsingFailureAsync< TResult >|If no Options/Handler found, this is called asynchronously with the executed arguments array and parser errors to handle the inability to handle the command line input arguments. | 13 | 14 | ## Example 15 | 16 | Here is an example of the QuickStart from [commandlineparser/commandline](https://github.com/commandlineparser/commandline) implemented using DI. In this case though, we're writing to Microsoft's Logging ILogger that is getting injected using DI instead of writing directly to console! 17 | 18 | ``` 19 | using CommandLine; 20 | using CommandLineParser.DependencyInjection.Interfaces; 21 | using Microsoft.Extensions.DependencyInjection; 22 | using Microsoft.Extensions.Logging; 23 | 24 | new ServiceCollection() // Create Service Collection 25 | .AddCommandLineParser(typeof(Options).Assembly) // Add CommandLineParser registrations to DI 26 | .AddLogging(c => c.AddConsole()) // Add Console Logging 27 | .BuildServiceProvider() // Build Service Provider 28 | .GetRequiredService>() // Get Parser Service 29 | .ParseArguments(args, -1) // Call Parser with Arguments (Options and ExecuteOptions will be loaded from DI as needed) 30 | ; 31 | 32 | public class Options: ICommandLineOptions 33 | { 34 | [Option('v', "verbose", Required = false, HelpText = "Set output to verbose messages.")] 35 | public bool Verbose { get; set; } 36 | } 37 | 38 | public class ExecuteOptions(ILogger log) : IExecuteCommandLineOptions 39 | { 40 | #region Implementation of IExecuteCommandLineOptions 41 | 42 | /// 43 | /// Execute Command Synchronously. 44 | /// 45 | /// Command Line Options 46 | /// Result 47 | public int Execute(Options options) 48 | { 49 | if (options.Verbose) 50 | { 51 | log.LogInformation($"Verbose output enabled. Current Arguments: -v {options.Verbose}"); 52 | log.LogWarning("Quick Start Example! App is in Verbose mode!"); 53 | } 54 | else 55 | { 56 | log.LogInformation($"Current Arguments: -v {options.Verbose}"); 57 | log.LogInformation("Quick Start Example!"); 58 | } 59 | 60 | return 0; 61 | } 62 | 63 | #endregion 64 | } 65 | ``` 66 | 67 | 68 | ### Unit Tests 69 | 70 | ***See the Test's project for example.*** 71 | 72 | The Tests project has 3 folders: 73 | - Options: These are the CommandLineOptions, exactly how the [commandlineparser/commandline](https://github.com/commandlineparser/commandline) library defines them, with the ICommandLineOptions interface added for DI discovering. *The only difference is that one is used for calling async instead of sync in tests.* 74 | - ExecuteAskOptions: These are both Sync and Async dummy implementations of services that handle the AskOptions as well as handle Parsing failures. 75 | - Services: Dummy service that returns a string based on the arguments provided. 76 | 77 | --------------------------------------------------------------------------------