├── .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