diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 883f073..65fab51 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,16 +3,22 @@ # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# name: "CodeQL" on: push: - branches: [master] + branches: [ master ] pull_request: # The branches below must be a subset of the branches above - branches: [master] + branches: [ master ] schedule: - - cron: '0 19 * * 5' + - cron: '24 8 * * 6' jobs: analyze: @@ -22,24 +28,14 @@ jobs: strategy: fail-fast: false matrix: - # Override automatic language detection by changing the below list - # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] - language: ['csharp'] - # Learn more... - # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + language: [ 'csharp' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - name: Checkout repository uses: actions/checkout@v2 - with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 - - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL @@ -47,7 +43,7 @@ jobs: with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. + # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main diff --git a/.github/workflows/dotnet-core.yml b/.github/workflows/dotnet-core.yml index 347cb80..31962c3 100644 --- a/.github/workflows/dotnet-core.yml +++ b/.github/workflows/dotnet-core.yml @@ -16,10 +16,22 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: 3.1.301 + dotnet-version: 5.0.408 + - name: Clean + run: dotnet clean -c Release - name: Install dependencies run: dotnet restore - name: Build run: dotnet build --configuration Release --no-restore - name: Test run: dotnet test --no-restore --verbosity normal + - name: Upload Release Build Artifacts + uses: actions/upload-artifact@v2.2.3 + with: + name: Release Build + path: /home/runner/work/CommandLineParser.Core/CommandLineParser.Core/CommandLineParser/bin/Release/**/* + - name: Upload Release Build Artifacts + uses: actions/upload-artifact@v2.2.3 + with: + name: Release Build Extensions + path: /home/runner/work/CommandLineParser.Core/CommandLineParser.Core/Extensions/FluentValidationsExtensions/bin/Release/**/* diff --git a/CommandLineParser.Tests/BasicDITests.cs b/CommandLineParser.Tests/BasicDITests.cs index d5f18cb..606bd6b 100644 --- a/CommandLineParser.Tests/BasicDITests.cs +++ b/CommandLineParser.Tests/BasicDITests.cs @@ -23,7 +23,9 @@ public void CommandLineParserUsesInjectedServiceCorrectly() Services.AddSingleton(mockedService.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.RegisterCommand(); @@ -41,7 +43,9 @@ public void CommandLineParserServiceResolvesCorrectly() Services.AddSingleton(mockedService); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var resolved = parser.Services.GetRequiredService(); diff --git a/CommandLineParser.Tests/Command/CommandDiscoveryTests.cs b/CommandLineParser.Tests/Command/CommandDiscoveryTests.cs index 45e5855..7ab0697 100644 --- a/CommandLineParser.Tests/Command/CommandDiscoveryTests.cs +++ b/CommandLineParser.Tests/Command/CommandDiscoveryTests.cs @@ -41,7 +41,9 @@ public void DiscoverCommandFromAssemblyContainsCorrectTypes() [Fact] public void DiscoveredCommandsAreRegisteredCorrectly() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.DiscoverCommands(Assembly.GetExecutingAssembly()); @@ -64,7 +66,8 @@ public async Task CommandDiscoveryWithInjectedServices() Services.AddSingleton(envMock.Object); Services.AddSingleton(myServiceMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.DiscoverCommands(Assembly.GetExecutingAssembly()); @@ -83,7 +86,8 @@ public async Task NonGenericCommandCanBeDiscovered() Services.AddSingleton(argResolverMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.DiscoverCommands(typeof(NonGenericDiscoverableCommand).Assembly); @@ -110,7 +114,7 @@ public class ValidCommand2 : Command { } - public class MyCommandWithInjectionsOptions + public class MyCommandWithInjectionsOptions { } diff --git a/CommandLineParser.Tests/Command/CommandInModelTests.cs b/CommandLineParser.Tests/Command/CommandInModelTests.cs index 4823e52..c6ec68c 100644 --- a/CommandLineParser.Tests/Command/CommandInModelTests.cs +++ b/CommandLineParser.Tests/Command/CommandInModelTests.cs @@ -2,6 +2,7 @@ using MatthiWare.CommandLine.Core.Attributes; using Xunit; using Xunit.Abstractions; +using Microsoft.Extensions.DependencyInjection; namespace MatthiWare.CommandLine.Tests.Command { @@ -13,10 +14,13 @@ public CommandInModelTests(ITestOutputHelper testOutputHelper) : base(testOutput #region FindCommandsInModel - [Fact] + [Fact(Timeout = 1000)] public void FindCommandsInModel() { - var parser = new CommandLineParser(Services); + Services.AddLogging(); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); Assert.Equal(3, parser.Commands.Count); } @@ -65,7 +69,9 @@ public override void OnConfigure(ICommandConfigurationBuilder builder) [Fact] public void FindCommandsInCommandModel() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.RegisterCommand(); diff --git a/CommandLineParser.Tests/Command/MultipleCommandTests.cs b/CommandLineParser.Tests/Command/MultipleCommandTests.cs index aceabaf..9e77d21 100644 --- a/CommandLineParser.Tests/Command/MultipleCommandTests.cs +++ b/CommandLineParser.Tests/Command/MultipleCommandTests.cs @@ -16,7 +16,9 @@ public MultipleCommandTests(ITestOutputHelper testOutputHelper) : base(testOutpu [InlineData(new string[] { }, false)] public void NonRequiredCommandShouldNotSetResultInErrorStateWhenRequiredOptionsAreMissing(string[] args, bool _) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand() .Name("cmd1") diff --git a/CommandLineParser.Tests/Command/SubCommandTests.cs b/CommandLineParser.Tests/Command/SubCommandTests.cs index 6d03442..903c890 100644 --- a/CommandLineParser.Tests/Command/SubCommandTests.cs +++ b/CommandLineParser.Tests/Command/SubCommandTests.cs @@ -27,7 +27,8 @@ public async Task TestSubCommandWorksCorrectlyInModelAsync(bool autoExecute, str Services.AddSingleton(new MainCommand(lock1, autoExecute, bla, i, n)); Services.AddSingleton(new SubCommand(lock2, autoExecute, bla, i, n)); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var result = await parser.ParseAsync(new[] { "main", "-b", bla, "sub", "-i", i.ToString(), "-n", n.ToString() }); diff --git a/CommandLineParser.Tests/CommandLineModelTests.cs b/CommandLineParser.Tests/CommandLineModelTests.cs index 65aec58..39bde96 100644 --- a/CommandLineParser.Tests/CommandLineModelTests.cs +++ b/CommandLineParser.Tests/CommandLineModelTests.cs @@ -14,7 +14,8 @@ public CommandLineModelTests(ITestOutputHelper testOutputHelper) : base(testOutp [Fact] public void TestBasicModel() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); Assert.Equal(1, parser.Options.Count); @@ -36,7 +37,8 @@ public void TestBasicModel() [Fact] public void TestBasicModelWithOverwritingUsingFluentApi() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(_ => _.Message) .Required(false) diff --git a/CommandLineParser.Tests/CommandLineParser.Tests.csproj b/CommandLineParser.Tests/CommandLineParser.Tests.csproj index c4c5263..26dda0a 100644 --- a/CommandLineParser.Tests/CommandLineParser.Tests.csproj +++ b/CommandLineParser.Tests/CommandLineParser.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp3.1 + net5.0 false @@ -11,15 +11,15 @@ - + all runtime; build; native; contentfiles; analyzers - - - - - + + + + + all runtime; build; native; contentfiles; analyzers diff --git a/CommandLineParser.Tests/CommandLineParserTests.cs b/CommandLineParser.Tests/CommandLineParserTests.cs index a0b8cbb..50d51b4 100644 --- a/CommandLineParser.Tests/CommandLineParserTests.cs +++ b/CommandLineParser.Tests/CommandLineParserTests.cs @@ -30,13 +30,24 @@ public override void OnConfigure(ICommandConfigurationBuilder builder) } } + [Fact] + public void NullOptionsAreNotAllowed() + { + Assert.Throws(() => new CommandLineParser((CommandLineParserOptions)null)); + Assert.Throws(() => new CommandLineParser((CommandLineParserOptions)null, (IServiceProvider)null)); + Assert.Throws(() => new CommandLineParser((CommandLineParserOptions)null, (IServiceProvider)null)); + Assert.Throws(() => new CommandLineParser((CommandLineParserOptions)null, (IServiceProvider)null)); + } + [Fact] public void OrderAttributeWorks() { var from = @"path/from/file"; var to = @"path/to/file"; - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { from, to }); @@ -52,7 +63,9 @@ public void OrderAttributeWorks2() var from = @"path/from/file"; var to = @"path/to/file"; - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { "-r", "5", from, to }); @@ -68,7 +81,9 @@ public void OrderAttributeInCommandWorks() var from = @"path/from/file"; var to = @"path/to/file"; - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand().Name("cmd").Required().OnExecuting((o, model) => { @@ -87,7 +102,9 @@ public void OrderedOptions_With_Named_Option_Between_Does_Not_work() var from = @"path/from/file"; var to = @"path/to/file"; - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { from, "-r", "5", to }); @@ -103,7 +120,9 @@ public void OrderedOptions_With_Named_Option_Between_Does_Not_work2() var from = 5; var to = 10; - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { from.ToString(), "oops", to.ToString() }); @@ -121,7 +140,9 @@ public void StopProcessingWorks() StopParsingAfter = "--" }; - var parser = new CommandLineParser(options, Services); + Services.AddCommandLineParser(options); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { "10", "20", "--", "some random stuff", "nothing to see here", "yadi yadi yadi", "-r", "10" }); @@ -145,6 +166,7 @@ public void InvalidOptionsThrowException(string shortOption, string longOption) }; Assert.Throws(() => new CommandLineParser(options, Services)); + Assert.Throws(() => new CommandLineParser(options, Services)); } [Theory] @@ -154,7 +176,8 @@ public void CommandLineParserParsesCorrectOptionsWithPostfix(bool useShort) { var query = $"{(useShort ? "-" : "--")}p=some text"; - var parser = new CommandLineParser(); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(p => p.Message).Name("p", "p").Required(); @@ -170,7 +193,9 @@ public void CommandLineParserUsesCorrectOptions() { var opt = new CommandLineParserOptions(); - var parser = new CommandLineParser(opt, Services); + Services.AddCommandLineParser(opt); + + var parser = ResolveParser(); Assert.Equal(opt, parser.ParserOptions); } @@ -192,7 +217,9 @@ public void CommandLineParserUsesContainerCorrectly(bool generic) Services.AddSingleton(commandMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); if (generic) { @@ -227,7 +254,9 @@ public async Task CommandLineParserUsesContainerCorrectlyAsync(bool generic) Services.AddSingleton(commandMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); if (generic) { @@ -248,7 +277,9 @@ public async Task CommandLineParserUsesContainerCorrectlyAsync(bool generic) [Fact] public void AutoExecuteCommandsWithExceptionDoesntCrashTheParser() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var ex = new Exception("uh-oh"); @@ -268,7 +299,9 @@ public void AutoExecuteCommandsWithExceptionDoesntCrashTheParser() [Fact] public async Task AutoExecuteCommandsWithExceptionDoesntCrashTheParserAsync() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var ex = new Exception("uh-oh"); @@ -292,7 +325,8 @@ public async Task AutoExecuteCommandsWithExceptionDoesntCrashTheParserAsync() [Fact] public void ParseTests() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(opt => opt.Option1) .Name("o") @@ -316,7 +350,8 @@ public void ParseTests() [InlineData(new[] { "-e" }, true, default(EnumOption))] public void ParseEnumInArguments(string[] args, bool hasErrors, EnumOption enumOption) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(opt => opt.EnumOption) .Name("e") @@ -381,7 +416,8 @@ void Test() private void TestParsingWithDefaults(string[] args, T defaultValue, T result1, T result2, T result3) { - var parser = new CommandLineParser>(Services); + Services.AddCommandLineParser>(); + var parser = ResolveParser>(); parser.Configure(opt => opt.Option1) .Name("1") @@ -412,7 +448,8 @@ public async Task ParseWithCommandTestsAsync() { var wait = new ManualResetEvent(false); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(opt => opt.Option1) .Name("o") @@ -457,7 +494,8 @@ public async Task ParseWithCommandTestsAsync() [InlineData(new[] { "-m", "message1", "add", "-m", "message2" }, "message1", "message2")] public void ParseCommandTests(string[] args, string result1, string result2) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var wait = new ManualResetEvent(false); parser.AddCommand() @@ -493,7 +531,8 @@ public void ParseCommandTests(string[] args, string result1, string result2) [InlineData(new[] { "-m", "message1", "add", "-m", "message2" }, "message1", "message2")] public async Task ParseCommandTestsAsync(string[] args, string result1, string result2) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var wait = new ManualResetEvent(false); parser.AddCommand() @@ -532,7 +571,8 @@ public async Task ParseCommandTestsAsync(string[] args, string result1, string r [InlineData(new string[] { "-x", "false" }, false)] public void BoolResolverSpecialCaseParsesCorrectly(string[] args, bool expected) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(opt => opt.Option2) .Name("x", "xsomething") @@ -552,7 +592,8 @@ public void BoolResolverSpecialCaseParsesCorrectly(string[] args, bool expected) [InlineData(new string[] { "command", "-v" }, true)] public void BoolResolverSpecialCaseParsesCorrectlyWithDefaultValueAndNotBeingSpecified(string[] args, bool expected) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.AddCommand().Name("command"); @@ -574,7 +615,8 @@ private class Model_Issue_35 [Fact] public void ConfigureTests() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(opt => opt.Option1) .Name("o", "opt") @@ -608,7 +650,8 @@ public void ConfigureTests() [InlineData(new string[] { "--message", "test" }, "testtransformed", false)] public void TransformationWorksAsExpected(string[] args, string expected, bool errors) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(a => a.Message) .Name("m", "message") @@ -629,7 +672,8 @@ public void TransformationWorksAsExpected(string[] args, string expected, bool e [InlineData(new string[] { "--int", "10" }, 20, false)] public void TransformationWorksAsExpectedForInts(string[] args, int expected, bool errors) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Configure(a => a.SomeInt) .Name("i", "int") @@ -652,7 +696,9 @@ public void TransformationWorksAsExpectedForCommandOptions(string[] args, int ex { int outcome = -1; - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var cmd = parser.AddCommand() .Name("cmd") @@ -679,7 +725,8 @@ public void TransformationWorksAsExpectedForCommandOptions(string[] args, int ex [InlineData(new string[] { "cmd", "--string", "test", "-s2", "test" }, "test", false)] public void CustomTypeWithStringTryParseGetsParsedCorrectly(string[] args, string expected, bool errors) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var result = parser.Parse(args); @@ -699,7 +746,8 @@ public void CustomTypeWithStringTryParseGetsParsedCorrectly(string[] args, strin [InlineData(new string[] { "cmd", "--string", "test", "-s2", "test", "-s3", "test" }, "test", false)] public void CustomTypeWithStringConstructorGetsParsedCorrectly(string[] args, string expected, bool errors) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var result = parser.Parse(args); diff --git a/CommandLineParser.Tests/Exceptions/ExceptionsTest.cs b/CommandLineParser.Tests/Exceptions/ExceptionsTest.cs index f6ea0fb..a392666 100644 --- a/CommandLineParser.Tests/Exceptions/ExceptionsTest.cs +++ b/CommandLineParser.Tests/Exceptions/ExceptionsTest.cs @@ -1,6 +1,11 @@ using MatthiWare.CommandLine.Abstractions.Command; +using MatthiWare.CommandLine.Abstractions.Usage; using MatthiWare.CommandLine.Core.Attributes; using MatthiWare.CommandLine.Core.Exceptions; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; @@ -17,7 +22,9 @@ public ExceptionsTest(ITestOutputHelper testOutputHelper) : base(testOutputHelpe [Fact] public void SubCommandNotFoundTest() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { "cmd" }); @@ -31,7 +38,9 @@ public void SubCommandNotFoundTest() [Fact] public async Task SubCommandNotFoundTestAsync() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = await parser.ParseAsync(new string[] { "cmd" }); @@ -45,7 +54,9 @@ public async Task SubCommandNotFoundTestAsync() [Fact] public void CommandNotFoundTest() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand().Name("missing").Required(); @@ -61,7 +72,9 @@ public void CommandNotFoundTest() [Fact] public async Task CommandNotFoundTestAsync() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand().Name("missing").Required(); @@ -77,7 +90,9 @@ public async Task CommandNotFoundTestAsync() [Fact] public async Task OptionNotFoundTestAsync() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = await parser.ParseAsync(new string[] { }); @@ -91,7 +106,9 @@ public async Task OptionNotFoundTestAsync() [Fact] public void CommandParseExceptionTest() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand() .Name("missing") @@ -112,7 +129,9 @@ public void CommandParseExceptionTest() [Fact] public async Task CommandParseExceptionTestAsync() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand() .Name("missing") @@ -130,10 +149,75 @@ public async Task CommandParseExceptionTestAsync() Assert.Same(parser.Commands.First(), result.Errors.Cast().First().Command); } + [Fact] + public async Task CommandParseException_Prints_Errors() + { + var printerMock = new Mock(); + + Services.AddSingleton(printerMock.Object); + + Services.AddCommandLineParser(); + + var parser = ResolveParser(); + + parser.AddCommand() + .Name("missing") + .Required() + .Configure(opt => opt.MissingOption) + .Name("o") + .Required(); + + var result = await parser.ParseAsync(new string[] { "-a", "1", "-b", "2", "-a", "10" ,"20" ,"30", "missing" }); + + printerMock.Verify(_ => _.PrintErrors(It.IsAny>())); + } + + [Fact] + public void CommandParseException_Should_Contain_Correct_Message_Single() + { + var cmdMock = new Mock(); + cmdMock.SetupGet(_ => _.Name).Returns("test"); + + var exceptionList = new List + { + new Exception("msg1") + }; + + var parseException = new CommandParseException(cmdMock.Object, exceptionList.AsReadOnly()); + var msg = parseException.Message; + var expected = @"Unable to parse command 'test' reason: msg1"; + + Assert.Equal(expected, msg); + } + + [Fact] + public void CommandParseException_Should_Contain_Correct_Message_Multiple() + { + var cmdMock = new Mock(); + cmdMock.SetupGet(_ => _.Name).Returns("test"); + + var exceptionList = new List + { + new Exception("msg1"), + new Exception("msg2") + }; + + var parseException = new CommandParseException(cmdMock.Object, exceptionList.AsReadOnly()); + var msg = parseException.Message; + var expected = @"Unable to parse command 'test' because 2 errors occured + - msg1 + - msg2 +"; + + Assert.Equal(expected, msg); + } + [Fact] public void OptionParseExceptionTest() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = parser.Parse(new string[] { "-m", "bla" }); @@ -147,7 +231,9 @@ public void OptionParseExceptionTest() [Fact] public async Task OptionParseExceptionTestAsync() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); var result = await parser.ParseAsync(new string[] { "-m", "bla" }); @@ -158,6 +244,15 @@ public async Task OptionParseExceptionTestAsync() Assert.Same(parser.Options.First(), result.Errors.Cast().First().Option); } + private class OtherOptions + { + [Required, Name("a")] + public int A { get; set; } + + [Required, Name("b")] + public int B { get; set; } + } + private class Options { [Required, Name("m", "missing")] diff --git a/CommandLineParser.Tests/Parsing/OptionClusteringTests.cs b/CommandLineParser.Tests/Parsing/OptionClusteringTests.cs index cd0efbd..29836cb 100644 --- a/CommandLineParser.Tests/Parsing/OptionClusteringTests.cs +++ b/CommandLineParser.Tests/Parsing/OptionClusteringTests.cs @@ -14,7 +14,9 @@ public OptionClusteringTests(ITestOutputHelper testOutputHelper) : base(testOutp [Fact] public void ClusterdOptionsAreParsedCorrectly() { - var parser = new CommandLineParser>(Services); + Services.AddCommandLineParser>(); + + var parser = ResolveParser>(); var result = parser.Parse(new[] { "-abc" }); @@ -30,7 +32,9 @@ public void ClusterdOptionsAreParsedCorrectly() [Fact] public void ClusterdOptionsAllSetTheSameValue() { - var parser = new CommandLineParser>(Services); + Services.AddCommandLineParser>(); + + var parser = ResolveParser>(); var result = parser.Parse(new[] { "-abc", "false" }); @@ -46,7 +50,9 @@ public void ClusterdOptionsAllSetTheSameValue() [Fact] public void ClusterdOptionsAreIgnoredWhenRepeated() { - var parser = new CommandLineParser>(Services); + Services.AddCommandLineParser>(); + + var parser = ResolveParser>(); var result = parser.Parse(new[] { "-abc", "false", "-abc", "true" }); @@ -62,7 +68,9 @@ public void ClusterdOptionsAreIgnoredWhenRepeated() [Fact] public void ClusterdOptionsInCommandWork() { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand>().Name("cmd").Required().OnExecuting((o, model) => { @@ -79,7 +87,9 @@ public void ClusterdOptionsInCommandWork() [Fact] public void ClusterdOptionsInCommandAndReusedInParentWork() { - var parser = new CommandLineParser>(Services); + Services.AddCommandLineParser>(); + + var parser = ResolveParser>(); parser.AddCommand>().Name("cmd").Required().OnExecuting((o, model) => { @@ -100,7 +110,9 @@ public void ClusterdOptionsInCommandAndReusedInParentWork() [Fact] public void ClusterdOptionsInCommandAndReusedInParentWork_String_Version() { - var parser = new CommandLineParser>(Services); + Services.AddCommandLineParser>(); + + var parser = ResolveParser>(); parser.AddCommand>().Name("cmd").Required().OnExecuting((o, model) => { diff --git a/CommandLineParser.Tests/Parsing/Resolvers/DefaultResolverTests.cs b/CommandLineParser.Tests/Parsing/Resolvers/DefaultResolverTests.cs index 62bf15b..a221452 100644 --- a/CommandLineParser.Tests/Parsing/Resolvers/DefaultResolverTests.cs +++ b/CommandLineParser.Tests/Parsing/Resolvers/DefaultResolverTests.cs @@ -21,8 +21,6 @@ public void ThrowsExceptionInCorrectPlaces() { Assert.Throws(() => new DefaultResolver(null, null)); Assert.Throws(() => new DefaultResolver(NullLogger.Instance, null)); - Assert.Throws(() => new DefaultResolver(NullLogger.Instance, ServiceProvider).CanResolve("")); - Assert.Throws(() => new DefaultResolver(NullLogger.Instance, ServiceProvider).Resolve("")); } [Fact] @@ -31,7 +29,9 @@ public void WorksCorrectlyWithNullValues() var resolver = new DefaultResolver(NullLogger.Instance, ServiceProvider); Assert.False(resolver.CanResolve((ArgumentModel)null)); + Assert.False(resolver.CanResolve((string)null)); Assert.Null(resolver.Resolve((ArgumentModel)null)); + Assert.Null(resolver.Resolve((string)null)); } [Theory] @@ -43,6 +43,7 @@ public void TestCanResolve(bool expected, string key, string value) var model = new ArgumentModel(key, value); Assert.Equal(expected, resolver.CanResolve(model)); + Assert.Equal(expected, resolver.CanResolve(value)); } [Theory] @@ -54,6 +55,7 @@ public void TestCanResolveWithWrongCtor(bool expected, string key, string value) var model = new ArgumentModel(key, value); Assert.Equal(expected, resolver.CanResolve(model)); + Assert.Equal(expected, resolver.CanResolve(value)); } [Theory] @@ -65,6 +67,7 @@ public void TestResolve(string expected, string key, string value) var model = new ArgumentModel(key, value); Assert.Equal(expected, resolver.Resolve(model).Result); + Assert.Equal(expected, resolver.Resolve(value).Result); } public class MyTestType diff --git a/CommandLineParser.Tests/Parsing/Resolvers/GlobalParserTests.cs b/CommandLineParser.Tests/Parsing/Resolvers/GlobalParserTests.cs index e919c0c..01a4fc1 100644 --- a/CommandLineParser.Tests/Parsing/Resolvers/GlobalParserTests.cs +++ b/CommandLineParser.Tests/Parsing/Resolvers/GlobalParserTests.cs @@ -7,15 +7,17 @@ namespace MatthiWare.CommandLine.Tests.Parsing.Resolvers { public class GlobalParserTests : TestBase { + private readonly Abstractions.ICommandLineParser parser; + public GlobalParserTests(ITestOutputHelper testOutputHelper) : base(testOutputHelper) { + Services.AddCommandLineParser(); + parser = ResolveParser(); } [Fact] public void ParseByte() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-byte", "1" }); result.AssertNoErrors(); @@ -26,8 +28,6 @@ public void ParseByte() [Fact] public void ParseString() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-str", "text" }); result.AssertNoErrors(); @@ -38,8 +38,6 @@ public void ParseString() [Fact] public void ParseSByte() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-sbyte", "1" }); result.AssertNoErrors(); @@ -50,8 +48,6 @@ public void ParseSByte() [Fact] public void ParseInt() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-int", "1" }); result.AssertNoErrors(); @@ -62,8 +58,6 @@ public void ParseInt() [Fact] public void ParseLong() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-long", "1" }); result.AssertNoErrors(); @@ -74,8 +68,6 @@ public void ParseLong() [Fact] public void ParseULong() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-ulong", "1" }); result.AssertNoErrors(); @@ -86,8 +78,6 @@ public void ParseULong() [Fact] public void ParseUShort() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-ushort", "1" }); result.AssertNoErrors(); @@ -98,8 +88,6 @@ public void ParseUShort() [Fact] public void ParseShort() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-short", "1" }); result.AssertNoErrors(); @@ -110,8 +98,6 @@ public void ParseShort() [Fact] public void ParseUint() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-uint", "1" }); result.AssertNoErrors(); @@ -122,8 +108,6 @@ public void ParseUint() [Fact] public void ParseDecimal() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-decimal", "1.0" }); result.AssertNoErrors(); @@ -134,8 +118,6 @@ public void ParseDecimal() [Fact] public void ParseFloat() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-float", "1.0" }); result.AssertNoErrors(); @@ -146,8 +128,6 @@ public void ParseFloat() [Fact] public void ParseBool() { - var parser = new CommandLineParser(Services); - var result = parser.Parse(new[] { "-bool", "true" }); result.AssertNoErrors(); @@ -162,8 +142,6 @@ public void ParseBool() [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntArray(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -180,8 +158,6 @@ public void ParseIntArray(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseStringArray(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -198,8 +174,6 @@ public void ParseStringArray(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntList(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -216,8 +190,6 @@ public void ParseIntList(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntEnumerable(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -234,8 +206,6 @@ public void ParseIntEnumerable(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntCollection(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -252,8 +222,6 @@ public void ParseIntCollection(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntReadonlyList(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -270,8 +238,6 @@ public void ParseIntReadonlyList(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntReadonlyCollection(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -288,8 +254,6 @@ public void ParseIntReadonlyCollection(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntSet(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); @@ -306,8 +270,6 @@ public void ParseIntSet(string[] args, bool avoidCompilerError) [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters", Justification = "Compiler Error")] public void ParseIntISet(string[] args, bool avoidCompilerError) { - var parser = new CommandLineParser(Services); - var result = parser.Parse(args); result.AssertNoErrors(); diff --git a/CommandLineParser.Tests/Parsing/Validation/ValidationAbstractionTests.cs b/CommandLineParser.Tests/Parsing/Validation/ValidationAbstractionTests.cs index 0cbd803..65d9f2e 100644 --- a/CommandLineParser.Tests/Parsing/Validation/ValidationAbstractionTests.cs +++ b/CommandLineParser.Tests/Parsing/Validation/ValidationAbstractionTests.cs @@ -18,7 +18,8 @@ public ValidationAbstractionTests(ITestOutputHelper testOutputHelper) : base(tes [Fact] public void ParsingCallsValidation() { - var parser = new CommandLineParser(); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var validValidationResultMock = new Mock(); validValidationResultMock.SetupGet(v => v.IsValid).Returns(true); @@ -49,7 +50,8 @@ public void ParsingCallsValidation() [Fact] public async Task ParsingCallsValidationAsync() { - var parser = new CommandLineParser(); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var validValidationResultMock = new Mock(); validValidationResultMock.SetupGet(v => v.IsValid).Returns(true); diff --git a/CommandLineParser.Tests/TestBase.cs b/CommandLineParser.Tests/TestBase.cs index 0de5060..b828f4c 100644 --- a/CommandLineParser.Tests/TestBase.cs +++ b/CommandLineParser.Tests/TestBase.cs @@ -1,17 +1,44 @@ -using Microsoft.Extensions.DependencyInjection; +using MatthiWare.CommandLine.Abstractions; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using Xunit.Abstractions; namespace MatthiWare.CommandLine.Tests { - public abstract class TestBase + public abstract class TestBase { private readonly ITestOutputHelper testOutputHelper; + private IServiceProvider serviceProvider = null; public ILogger Logger { get; set; } + public IServiceCollection Services { get; set; } + public IServiceProvider ServiceProvider + { + get + { + if (serviceProvider is null) + { + serviceProvider = Services.BuildServiceProvider(); + } + + return serviceProvider; + } + } + + public ICommandLineParser ResolveParser() + where TOption : class, new() + { + return ServiceProvider.GetRequiredService>(); + } + + public ICommandLineParser ResolveParser() + { + return ServiceProvider.GetRequiredService(); + } + public TestBase(ITestOutputHelper testOutputHelper) { this.testOutputHelper = testOutputHelper ?? throw new ArgumentNullException(nameof(testOutputHelper)); diff --git a/CommandLineParser.Tests/Usage/DamerauLevenshteinTests.cs b/CommandLineParser.Tests/Usage/DamerauLevenshteinTests.cs index 7b9517e..ce10c4b 100644 --- a/CommandLineParser.Tests/Usage/DamerauLevenshteinTests.cs +++ b/CommandLineParser.Tests/Usage/DamerauLevenshteinTests.cs @@ -1,6 +1,8 @@ using MatthiWare.CommandLine.Abstractions; using MatthiWare.CommandLine.Abstractions.Command; +using MatthiWare.CommandLine.Abstractions.Usage; using MatthiWare.CommandLine.Core.Usage; +using Microsoft.Extensions.DependencyInjection; using Moq; using System.Collections.Generic; using Xunit; @@ -107,15 +109,40 @@ public void NoSuggestionsReturnsEmpty() } [Fact] - public void Test() + public void ShouldPrintSuggestion() { - var parser = new CommandLineParser(Services); + var builderMock = new Mock(); + Services.AddSingleton(builderMock.Object); + + Services.AddCommandLineParser(); + + var parser = ResolveParser(); parser.AddCommand().Name("cmd"); var result = parser.Parse(new[] { "cmdd" }); result.AssertNoErrors(); + builderMock.Verify(_ => _.AddSuggestion("cmd"), Times.Once()); + } + + [Fact] + public void ShouldNotPrintSuggestionForSkippedArguments() + { + var builderMock = new Mock(); + Services.AddSingleton(builderMock.Object); + + var options = new CommandLineParserOptions { StopParsingAfter = "--" }; + Services.AddCommandLineParser(options); + + var parser = ResolveParser(); + + parser.AddCommand().Name("cmd"); + + var result = parser.Parse(new[] { "--", "cmdd" }); + + result.AssertNoErrors(); + builderMock.Verify(_ => _.AddSuggestion("cmd"), Times.Never()); } } } diff --git a/CommandLineParser.Tests/Usage/HelpDisplayCommandTests.cs b/CommandLineParser.Tests/Usage/HelpDisplayCommandTests.cs index bc505af..3e7219a 100644 --- a/CommandLineParser.Tests/Usage/HelpDisplayCommandTests.cs +++ b/CommandLineParser.Tests/Usage/HelpDisplayCommandTests.cs @@ -85,7 +85,8 @@ public async Task TestHelpDisplayFiresCorrectlyAsync(string[] args, bool fires) Services.AddSingleton(usagePrinterMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var cmd = parser.AddCommand() .Name("db") diff --git a/CommandLineParser.Tests/Usage/UsagePrinterTests.cs b/CommandLineParser.Tests/Usage/UsagePrinterTests.cs index 0d76329..363e71f 100644 --- a/CommandLineParser.Tests/Usage/UsagePrinterTests.cs +++ b/CommandLineParser.Tests/Usage/UsagePrinterTests.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.DependencyInjection; using Moq; using System; +using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; @@ -42,7 +43,8 @@ public void AllOptionsHaveDefaultValueShouldNotPrintUsages(string[] args, bool c Services.AddSingleton(printerMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.Parse(args); @@ -67,19 +69,43 @@ private class UsagePrinterCommandOptions [InlineData(new string[] { }, true)] [InlineData(new string[] { "-o", "bla" }, false)] [InlineData(new string[] { "-xd", "bla" }, true)] + [InlineData(new string[] { "--", "test" }, true)] public void UsagePrintGetsCalledInCorrectCases(string[] args, bool called) { var printerMock = new Mock(); Services.AddSingleton(printerMock.Object); - var parser = new CommandLineParser(Services); + var opt = new CommandLineParserOptions { StopParsingAfter = "--" }; + Services.AddCommandLineParser(opt); + var parser = ResolveParser(); parser.Parse(args); printerMock.Verify(mock => mock.PrintUsage(), called ? Times.Once() : Times.Never()); } + [Theory] + [InlineData(new string[] { "--", "get-al" }, false)] + [InlineData(new string[] { "--", "get-all" }, false)] + public async Task PrintUsage_ShouldBeCalled_When_Command_Is_Defined_After_StopParsingFlag(string[] args, bool _) + { + var printerMock = new Mock(); + + Services.AddSingleton(printerMock.Object); + + var opt = new CommandLineParserOptions { StopParsingAfter = "--" }; + Services.AddCommandLineParser(opt); + var parser = ResolveParser(); + + parser.AddCommand().Name("get-all"); + + await parser.ParseAsync(args); + + printerMock.Verify(mock => mock.PrintUsage(), Times.Once()); + printerMock.Verify(mock => mock.PrintSuggestion(It.IsAny()), Times.Never()); + } + [Fact] public void UsagePrinterPrintsOptionCorrectly() { @@ -87,7 +113,8 @@ public void UsagePrinterPrintsOptionCorrectly() Services.AddSingleton(printerMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser< UsagePrinterGetsCalledOptions>(); + var parser = ResolveParser< UsagePrinterGetsCalledOptions>(); parser.Parse(new[] { "-o", "--help" }); @@ -101,7 +128,8 @@ public void UsagePrinterPrintsCommandCorrectly() Services.AddSingleton(printerMock.Object); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.AddCommand() .Name("cmd") @@ -127,7 +155,8 @@ public void CustomInvokedPrinterWorksCorrectly(string[] args, bool cmdPassed, bo Services.AddSingleton(builderMock.Object); - var parser = new CommandLineParser(parserOptions, Services); + Services.AddCommandLineParser(parserOptions); + var parser = ResolveParser(); parser.AddCommand() .Name("cmd") @@ -183,7 +212,8 @@ public void TestSuggestion() Services.AddSingleton(consoleMock.Object); Services.AddSingleton(Logger); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var cmdConfig = parser.AddCommand(); cmdConfig.Name("ZZZZZZZZZZZZZZ").Configure(o => o.Option).Name("tst"); @@ -191,7 +221,7 @@ public void TestSuggestion() parser.AddCommand().Name("Test"); parser.Configure(o => o.Option).Name("Test1"); - var model = new UnusedArgumentModel("tst", parser); + var model = new UnusedArgumentModel("tst", (IArgument)parser); var printer = parser.Services.GetRequiredService(); // ACT @@ -216,7 +246,8 @@ public void TestNoSuggestion() Services.AddSingleton(suggestionProviderMock.Object); Services.AddSingleton(Logger); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); // ACT parser.Parse(new[] { "tst" }).AssertNoErrors(); @@ -239,7 +270,8 @@ public void TestSuggestionWithParsing() Services.AddSingleton(consoleMock.Object); Services.AddSingleton(Logger); - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); var cmdConfig = parser.AddCommand(); cmdConfig.Name("ZZZZZZZZZZZZZZ").Configure(o => o.Option).Name("tst"); diff --git a/CommandLineParser/Abstractions/ICommandLineParser'.cs b/CommandLineParser/Abstractions/ICommandLineParser'.cs index 4c6469d..761e19b 100644 --- a/CommandLineParser/Abstractions/ICommandLineParser'.cs +++ b/CommandLineParser/Abstractions/ICommandLineParser'.cs @@ -1,6 +1,7 @@ using MatthiWare.CommandLine.Abstractions.Command; using MatthiWare.CommandLine.Abstractions.Parsing; using MatthiWare.CommandLine.Abstractions.Usage; +using MatthiWare.CommandLine.Abstractions.Validations; using System; using System.Linq.Expressions; using System.Reflection; @@ -13,11 +14,17 @@ namespace MatthiWare.CommandLine.Abstractions /// Command line parser /// /// Argument options model - public interface ICommandLineParser + public interface ICommandLineParser : ICommandLineCommandContainer where TOption : class, new() { #region Properties + /// + /// this parser is currently using. + /// NOTE: In order to use the options they need to be passed using the constructor. + /// + CommandLineParserOptions ParserOptions { get; } + /// /// Utility to print usage information to the output /// @@ -28,6 +35,16 @@ public interface ICommandLineParser /// IServiceProvider Services { get; } + /// + /// Container for all validators + /// + IValidatorsContainer Validators { get; } + + /// + /// Token based argument parser + /// + IArgumentManager ArgumentManager { get; } + #endregion #region Parsing @@ -47,6 +64,13 @@ public interface ICommandLineParser /// The task that resolves to the result. Task> ParseAsync(string[] args, CancellationToken cancellationToken); + /// + /// Parses the arguments async + /// + /// CLI Arguments + /// The task that resolves to the result. + Task> ParseAsync(string[] args); + #endregion #region Configuration diff --git a/CommandLineParser/Abstractions/ICommandLineParser.cs b/CommandLineParser/Abstractions/ICommandLineParser.cs new file mode 100644 index 0000000..06b640f --- /dev/null +++ b/CommandLineParser/Abstractions/ICommandLineParser.cs @@ -0,0 +1,9 @@ +namespace MatthiWare.CommandLine.Abstractions +{ + /// + /// Command line parser + /// + public interface ICommandLineParser : ICommandLineParser + { + } +} diff --git a/CommandLineParser/Abstractions/Parsing/IArgumentManager.cs b/CommandLineParser/Abstractions/Parsing/IArgumentManager.cs index c9fa388..f736e58 100644 --- a/CommandLineParser/Abstractions/Parsing/IArgumentManager.cs +++ b/CommandLineParser/Abstractions/Parsing/IArgumentManager.cs @@ -1,4 +1,6 @@ -using MatthiWare.CommandLine.Abstractions.Models; +using MatthiWare.CommandLine.Abstractions.Command; +using MatthiWare.CommandLine.Abstractions.Models; +using MatthiWare.CommandLine.Abstractions.Usage; using System; using System.Collections.Generic; @@ -10,10 +12,22 @@ namespace MatthiWare.CommandLine.Abstractions.Parsing public interface IArgumentManager { /// - /// Returns a read-only list of unused arguments + /// Returns a read-only list of arguments that never got processed because they appeared after the flag. + /// + IReadOnlyList UnprocessedArguments { get; } + + /// + /// Returns a read-only list of unused arguments. + /// In most cases this will be mistyped arguments that are not mapped to the actual option/command names. + /// You can pass these arguments inside the to get a suggestion of what could be the correct argument. /// IReadOnlyList UnusedArguments { get; } + /// + /// Returns if the flag was found. + /// + bool StopParsingFlagSpecified { get; } + /// /// Tries to get the arguments associated to the current option /// @@ -27,6 +41,7 @@ public interface IArgumentManager /// /// Input arguments /// List of processesing errors - void Process(IReadOnlyList arguments, IList errors); + /// Container for the commands and options + void Process(IReadOnlyList arguments, IList errors, ICommandLineCommandContainer commandContainer); } } diff --git a/CommandLineParser/Abstractions/Usage/IUsagePrinter.cs b/CommandLineParser/Abstractions/Usage/IUsagePrinter.cs index b288699..acf05e4 100644 --- a/CommandLineParser/Abstractions/Usage/IUsagePrinter.cs +++ b/CommandLineParser/Abstractions/Usage/IUsagePrinter.cs @@ -25,8 +25,8 @@ public interface IUsagePrinter /// Print an argument /// /// The given argument - [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use PrintCommandUsage or PrintOptionUsage instead")] + [EditorBrowsable(EditorBrowsableState.Never)] void PrintUsage(IArgument argument); /// @@ -63,6 +63,11 @@ public interface IUsagePrinter /// list of errors void PrintErrors(IReadOnlyCollection errors); - void PrintSuggestion(UnusedArgumentModel model); + /// + /// Prints suggestions based on the input arguments + /// + /// Input model + /// True if a suggestion was found and printed, otherwise false + bool PrintSuggestion(UnusedArgumentModel model); } } diff --git a/CommandLineParser/CommandLineParser.cs b/CommandLineParser/CommandLineParser.cs index 432f50e..4203b41 100644 --- a/CommandLineParser/CommandLineParser.cs +++ b/CommandLineParser/CommandLineParser.cs @@ -1,11 +1,14 @@ -using Microsoft.Extensions.DependencyInjection; +using MatthiWare.CommandLine.Abstractions; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.ComponentModel; namespace MatthiWare.CommandLine { /// /// Command line parser /// - public class CommandLineParser : CommandLineParser + public class CommandLineParser : CommandLineParser, ICommandLineParser { /// /// Creates a new instance of the commandline parser @@ -26,6 +29,8 @@ public CommandLineParser(CommandLineParserOptions parserOptions) /// Creates a new instance of the commandline parser /// /// Services collection to use, if null will create an internal one + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Use extension method 'AddCommandLineParser' to register the parser with DI")] public CommandLineParser(IServiceCollection serviceCollection) : this(new CommandLineParserOptions(), serviceCollection) { } @@ -35,8 +40,27 @@ public CommandLineParser(IServiceCollection serviceCollection) /// /// options that the parser will use /// Services collection to use, if null will create an internal one + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Use extension method 'AddCommandLineParser' to register the parser with DI")] public CommandLineParser(CommandLineParserOptions parserOptions, IServiceCollection serviceCollection) : base(parserOptions, serviceCollection) { } + + /// + /// Creates a new instance of the commandline parser + /// + /// Services provider to use + public CommandLineParser(IServiceProvider serviceProvider) + : this(new CommandLineParserOptions(), serviceProvider) + { } + + /// + /// Creates a new instance of the commandline parser + /// + /// options that the parser will use + /// Services Provider to use + public CommandLineParser(CommandLineParserOptions parserOptions, IServiceProvider serviceProvider) + : base(parserOptions, serviceProvider) + { } } } diff --git a/CommandLineParser/CommandLineParser.csproj b/CommandLineParser/CommandLineParser.csproj index e54a983..9e3ee78 100644 --- a/CommandLineParser/CommandLineParser.csproj +++ b/CommandLineParser/CommandLineParser.csproj @@ -4,7 +4,7 @@ netstandard2.0 MatthiWare.CommandLine MatthiWare.CommandLineParser - 0.5.0 + 0.7.0 Matthias Beerens MatthiWare Command Line Parser @@ -14,14 +14,14 @@ https://github.com/MatthiWare/CommandLineParser.Core Commandline parser commandline-parser cli 7.3 - 0.5.0.0 - 0.5.0.0 + 0.7.0.0 + 0.7.0.0 LICENSE - - Option clustering/grouping -- Suggestions when mistyping command/options -- Positional parameters -- Support for all basic datatypes + - Change license to MIT Copyright Matthias Beerens 2018 + git + True + README.md @@ -39,11 +39,15 @@ True + + True + \ + - - + + diff --git a/CommandLineParser/CommandLineParser.nuspec b/CommandLineParser/CommandLineParser.nuspec deleted file mode 100644 index 0643dae..0000000 --- a/CommandLineParser/CommandLineParser.nuspec +++ /dev/null @@ -1,31 +0,0 @@ - - - - MatthiWare.CommandLineParser - 0.5.0 - CommandLineParser.Core - Matthias Beerens - Matthiee - https://github.com/MatthiWare/CommandLineParser.Core/blob/master/LICENSE - https://github.com/MatthiWare/CommandLineParser.Core - false - - Command Line Parser for .NET Core written in .NET Standard 2.0. - - Configuration is done through a strongly typed option model class using attributes or a fluent API. Both can be used to configure the properties of the options class. - This library allows to add commands with their own set of options as well. - - A simple, light-weight and strongly typed command line parser. Configuration using Fluent API, Attributes and model classes. - Improve dependency injection, improve command registration - Copyright Matthias Beerens 2018 - commandline parser commandline-parser - - - - - - - - - - \ No newline at end of file diff --git a/CommandLineParser/CommandLineParser.xml b/CommandLineParser/CommandLineParser.xml index 9a402e8..0f11e20 100644 --- a/CommandLineParser/CommandLineParser.xml +++ b/CommandLineParser/CommandLineParser.xml @@ -417,6 +417,12 @@ Argument options model + + + this parser is currently using. + NOTE: In order to use the options they need to be passed using the constructor. + + Utility to print usage information to the output @@ -427,6 +433,16 @@ Resolver that is used to instantiate types by an given container + + + Container for all validators + + + + + Token based argument parser + + Parses the arguments @@ -442,6 +458,13 @@ The task that resolves to the result. + + + Parses the arguments async + + CLI Arguments + The task that resolves to the result. + Discovers commands and registers them from any given assembly @@ -501,6 +524,11 @@ The type of the command + + + Command line parser + + API for configuring options @@ -767,9 +795,21 @@ Managers the arguments + + + Returns a read-only list of arguments that never got processed because they appeared after the flag. + + - Returns a read-only list of unused arguments + Returns a read-only list of unused arguments. + In most cases this will be mistyped arguments that are not mapped to the actual option/command names. + You can pass these arguments inside the to get a suggestion of what could be the correct argument. + + + + + Returns if the flag was found. @@ -780,12 +820,13 @@ The result arguments True if arguments are found, false if not - + Processes the argument list Input arguments List of processesing errors + Container for the commands and options @@ -1084,6 +1125,13 @@ list of errors + + + Prints suggestions based on the input arguments + + Input model + True if a suggestion was found and printed, otherwise false + Validator @@ -1214,6 +1262,19 @@ options that the parser will use Services collection to use, if null will create an internal one + + + Creates a new instance of the commandline parser + + Services provider to use + + + + Creates a new instance of the commandline parser + + options that the parser will use + Services Provider to use + Configuration options for @@ -1269,32 +1330,26 @@ Options model + + + - - this parser is currently using. - NOTE: In order to use the options they need to be passed using the constructor. - + - - Read-only collection of options specified - + - - Read-only list of commands specified - + - - Container for all validators - + @@ -1320,6 +1375,19 @@ container resolver to use The options the parser will use + + + Creates a new instance of the commandline parser + + Service provider to resolve internal services with + + + + Creates a new instance of the commandline parser + + Service provider to resolve internal services with + The options the parser will use + Configures an option in the model @@ -1335,6 +1403,13 @@ arguments from the commandline The result of the parsing, + + + Parses the commandline arguments async + + arguments from the commandline + The result of the parsing, + Parses the commandline arguments async @@ -1646,13 +1721,19 @@ + + + + + + - + - + @@ -1933,5 +2014,27 @@ + + + Extension methods to allow DI services to be registered. + + + + + Adds to the services + This won't overwrite existing services. + + Base option type + Current service collection + Current options reference + + + + Adds to the services + This won't overwrite existing services. + + Current service collection + Current options reference + diff --git a/CommandLineParser/CommandLineParser`TOption.cs b/CommandLineParser/CommandLineParser`TOption.cs index 9127c19..0aa8d0b 100644 --- a/CommandLineParser/CommandLineParser`TOption.cs +++ b/CommandLineParser/CommandLineParser`TOption.cs @@ -22,6 +22,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using System.ComponentModel; [assembly: InternalsVisibleTo("CommandLineParser.Tests")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] @@ -41,40 +42,33 @@ public class CommandLineParser : ICommandLineParser, ICommandL private readonly string m_helpOptionName; private readonly string m_helpOptionNameLong; private readonly ILogger logger; - private readonly IArgumentManager argumentManager; - /// - /// this parser is currently using. - /// NOTE: In order to use the options they need to be passed using the constructor. - /// + /// + public IArgumentManager ArgumentManager => Services.GetRequiredService(); + + /// public CommandLineParserOptions ParserOptions { get; } /// public IUsagePrinter Printer => Services.GetRequiredService(); - /// - /// Read-only collection of options specified - /// + /// public IReadOnlyList Options => new ReadOnlyCollectionWrapper(m_options.Values); /// public IServiceProvider Services { get; } - /// - /// Read-only list of commands specified - /// + /// public IReadOnlyList Commands => m_commands.AsReadOnly(); - /// - /// Container for all validators - /// + /// public IValidatorsContainer Validators => Services.GetRequiredService(); /// /// Creates a new instance of the commandline parser /// public CommandLineParser() - : this(new CommandLineParserOptions(), null) + : this(new CommandLineParserOptions(), null as IServiceProvider) { } /// @@ -82,13 +76,15 @@ public CommandLineParser() /// /// The parser options public CommandLineParser(CommandLineParserOptions parserOptions) - : this(parserOptions, null) + : this(parserOptions, null as IServiceProvider) { } /// /// Creates a new instance of the commandline parser /// /// container resolver to use + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("Use extension method 'AddCommandLineParser' to register the parser with DI")] public CommandLineParser(IServiceCollection servicesCollection) : this(new CommandLineParserOptions(), servicesCollection) { } @@ -98,6 +94,8 @@ public CommandLineParser(IServiceCollection servicesCollection) /// /// container resolver to use /// The options the parser will use + [Obsolete("Use extension method 'AddCommandLineParser' to register the parser with DI")] + [EditorBrowsable(EditorBrowsableState.Never)] public CommandLineParser(CommandLineParserOptions parserOptions, IServiceCollection servicesCollection) { ValidateOptions(parserOptions); @@ -111,7 +109,47 @@ public CommandLineParser(CommandLineParserOptions parserOptions, IServiceCollect Services = services.BuildServiceProvider(); logger = Services.GetRequiredService>(); - argumentManager = Services.GetRequiredService(); + + m_option = new TOption(); + + (m_helpOptionName, m_helpOptionNameLong) = parserOptions.GetConfiguredHelpOption(); + + InitialzeModel(); + } + + /// + /// Creates a new instance of the commandline parser + /// + /// Service provider to resolve internal services with + public CommandLineParser(IServiceProvider serviceProvider) + : this(new CommandLineParserOptions(), serviceProvider) + { } + + /// + /// Creates a new instance of the commandline parser + /// + /// Service provider to resolve internal services with + /// The options the parser will use + public CommandLineParser(CommandLineParserOptions parserOptions, IServiceProvider serviceProvider) + { + ValidateOptions(parserOptions); + + ParserOptions = UpdateOptionsIfNeeded(parserOptions); + + if (serviceProvider == null) + { + var services = new ServiceCollection(); + + services.AddInternalCommandLineParserServices(this, ParserOptions); + + Services = services.BuildServiceProvider(); + } + else + { + Services = serviceProvider; + } + + logger = Services.GetRequiredService>(); m_option = new TOption(); @@ -122,6 +160,11 @@ public CommandLineParser(CommandLineParserOptions parserOptions, IServiceCollect private void ValidateOptions(CommandLineParserOptions options) { + if (options is null) + { + throw new ArgumentNullException("The provided options cannot be null."); + } + if (string.IsNullOrWhiteSpace(options.PrefixShortOption)) { throw new ArgumentException($"The provided options are not valid. {nameof(options.PrefixShortOption)} cannot be null or empty."); @@ -183,10 +226,16 @@ private IOptionBuilder ConfigureInternal(LambdaExpression selector, string /// /// arguments from the commandline /// The result of the parsing, - public IParserResult Parse(string[] args) - { - return ParseAsync(args).GetAwaiter().GetResult(); - } + public IParserResult Parse(string[] args) + => ParseAsync(args).GetAwaiter().GetResult(); + + /// + /// Parses the commandline arguments async + /// + /// arguments from the commandline + /// The result of the parsing, + public Task> ParseAsync(string[] args) + => ParseAsync(args, default); /// /// Parses the commandline arguments async @@ -200,7 +249,7 @@ public async Task> ParseAsync(string[] args, Cancellation var result = new ParseResult(); - argumentManager.Process(args, errors); + ArgumentManager.Process(args, errors, this); CheckForGlobalHelpOption(result); @@ -214,11 +263,24 @@ public async Task> ParseAsync(string[] args, Cancellation await AutoExecuteCommandsAsync(result, cancellationToken); - AutoPrintUsageAndErrors(result, args.Length == 0); + AutoPrintUsageAndErrors(result, NoActualArgsSupplied(args.Length)); return result; } + private bool NoActualArgsSupplied(int argsCount) + { + int leftOverAmountOfArguments = argsCount; + + if (ArgumentManager.StopParsingFlagSpecified) + { + leftOverAmountOfArguments--; // the flag itself + leftOverAmountOfArguments -= ArgumentManager.UnprocessedArguments.Count; + } + + return leftOverAmountOfArguments == 0; + } + private async Task ValidateAsync(T @object, ParseResult parseResult, List errors, CancellationToken token) { if (parseResult.HelpRequested) @@ -247,7 +309,7 @@ private async Task ValidateAsync(T @object, ParseResult parseResult, private void CheckForGlobalHelpOption(ParseResult result) { - if (argumentManager.TryGetValue(this, out var model)) + if (ArgumentManager.TryGetValue(this, out var model)) { HelpRequested(result, this, model); } @@ -268,7 +330,11 @@ private void AutoPrintUsageAndErrors(ParseResult result, bool noArgsSup { PrintHelpRequestedForArgument(result.HelpRequestedFor); } - else if (!noArgsSupplied && argumentManager.UnusedArguments.Count > 0) + else if (!noArgsSupplied && result.HasErrors && result.Errors.Any(e => e is CommandParseException || e is OptionParseException)) + { + PrintErrors(result.Errors); + } + else if (!noArgsSupplied && ArgumentManager.UnusedArguments.Count > 0) { PrintHelp(); PrintSuggestionsIfAny(); @@ -303,7 +369,16 @@ private void PrintErrors(IReadOnlyCollection errors) private void PrintHelp() => Printer.PrintUsage(); - private void PrintSuggestionsIfAny() => Printer.PrintSuggestion(argumentManager.UnusedArguments.First()); + private void PrintSuggestionsIfAny() + { + foreach (var argument in ArgumentManager.UnusedArguments) + { + if (Printer.PrintSuggestion(argument)) + { + return; + } + } + } private async Task AutoExecuteCommandsAsync(ParseResult result, CancellationToken cancellationToken) { @@ -394,7 +469,7 @@ private async Task ParseCommandsAsync(IList errors, ParseResult result, CancellationToken cancellationToken) { - var found = argumentManager.TryGetValue(cmd, out var model); + var found = ArgumentManager.TryGetValue(cmd, out var model); if (!found) { @@ -452,7 +527,7 @@ private void ParseOptions(IList errors, ParseResult result) private void ParseOption(CommandLineOptionBase option, ParseResult result) { - bool found = argumentManager.TryGetValue(option, out ArgumentModel model); + bool found = ArgumentManager.TryGetValue(option, out ArgumentModel model); if (found && HelpRequested(result, option, model)) { diff --git a/CommandLineParser/Core/DependencyInjectionExtensions.cs b/CommandLineParser/Core/DependencyInjectionExtensions.cs index 7662f3e..1c4192d 100644 --- a/CommandLineParser/Core/DependencyInjectionExtensions.cs +++ b/CommandLineParser/Core/DependencyInjectionExtensions.cs @@ -16,6 +16,8 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using System; +using System.ComponentModel; namespace MatthiWare.CommandLine.Core { @@ -33,6 +35,8 @@ public static class DependencyInjectionExtensions /// Current instance reference /// Current options reference /// Input service collection to allow method chaining + [Obsolete("Use AddCommandLineParser method instead")] + [EditorBrowsable(EditorBrowsableState.Never)] public static IServiceCollection AddInternalCommandLineParserServices(this IServiceCollection services, CommandLineParser parser, CommandLineParserOptions options) where TOption : class, new() { @@ -50,7 +54,22 @@ public static IServiceCollection AddInternalCommandLineParserServices(t .AddSuggestionProvider(); } - internal static IServiceCollection AddArgumentManager(this IServiceCollection services) + internal static IServiceCollection AddInternalCommandLineParserServices2(this IServiceCollection services, CommandLineParserOptions options) + { + return services + .AddArgumentManager() + .AddValidatorContainer() + .AddParserOptions(options) + .AddDefaultResolvers() + .AddCLIPrinters() + .AddCommandDiscoverer() + .AddEnvironmentVariables() + .AddDefaultLogger() + .AddModelInitializer() + .AddSuggestionProvider(); + } + + private static IServiceCollection AddArgumentManager(this IServiceCollection services) { services.TryAddScoped(); @@ -59,7 +78,7 @@ internal static IServiceCollection AddArgumentManager(this IServiceCollection se private static IServiceCollection AddParserOptions(this IServiceCollection services, CommandLineParserOptions options) { - services.AddSingleton(options); + services.TryAddSingleton(options ?? new CommandLineParserOptions()); return services; } @@ -67,22 +86,42 @@ private static IServiceCollection AddParserOptions(this IServiceCollection servi private static IServiceCollection AddCommandLineParser(this IServiceCollection services, CommandLineParser parser) where TOption : class, new() { - services.AddSingleton(parser); - services.AddSingleton>(parser); + services.TryAddSingleton(parser); + services.TryAddSingleton>(parser); + + return services; + } + + internal static IServiceCollection AddCommandLineParserFactoryGeneric(this IServiceCollection services, Func> parserFactory) + where TOption : class, new() + { + services.TryAddSingleton(parserFactory); + services.TryAddSingleton((provider) => provider.GetService>()); + services.TryAddSingleton>((provider) => provider.GetService>()); + + return services; + } + + internal static IServiceCollection AddCommandLineParserFactory(this IServiceCollection services, Func parserFactory) + { + services.TryAddSingleton(parserFactory); + services.TryAddSingleton((provider) => provider.GetService()); + services.TryAddSingleton((provider) => provider.GetService()); + services.TryAddSingleton>((provider) => provider.GetService()); return services; } private static IServiceCollection AddValidatorContainer(this IServiceCollection services) { - services.AddSingleton(); + services.TryAddSingleton(); return services; } private static IServiceCollection AddSuggestionProvider(this IServiceCollection services) { - services.AddSingleton(); + services.TryAddSingleton(); return services; } diff --git a/CommandLineParser/Core/Exceptions/CommandParseException.cs b/CommandLineParser/Core/Exceptions/CommandParseException.cs index 4e25db6..7638e1d 100644 --- a/CommandLineParser/Core/Exceptions/CommandParseException.cs +++ b/CommandLineParser/Core/Exceptions/CommandParseException.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Text; using MatthiWare.CommandLine.Abstractions.Command; namespace MatthiWare.CommandLine.Core.Exceptions @@ -20,7 +22,35 @@ public class CommandParseException : BaseParserException /// the failed command /// collection of inner exception public CommandParseException(ICommandLineCommand command, IReadOnlyCollection innerExceptions) - : base(command, "", new AggregateException(innerExceptions)) + : base(command, CreateMessage(command, innerExceptions), new AggregateException(innerExceptions)) { } + + private static string CreateMessage(ICommandLineCommand command, IReadOnlyCollection exceptions) + { + if (exceptions.Count > 1) + { + return CreateMultipleExceptionsMessage(command, exceptions); + } + else + { + return CreateSingleExceptionMessage(command, exceptions.First()); + } + } + + private static string CreateSingleExceptionMessage(ICommandLineCommand command, Exception exception) + => $"Unable to parse command '{command.Name}' reason: {exception.Message}"; + + private static string CreateMultipleExceptionsMessage(ICommandLineCommand command, IReadOnlyCollection exceptions) + { + var message = new StringBuilder(); + message.AppendLine($"Unable to parse command '{command.Name}' because {exceptions.Count} errors occured"); + + foreach (var exception in exceptions) + { + message.AppendLine($" - {exception.Message}"); + } + + return message.ToString(); + } } } diff --git a/CommandLineParser/Core/Parsing/ArgumentManager.cs b/CommandLineParser/Core/Parsing/ArgumentManager.cs index 1130e53..5cd7310 100644 --- a/CommandLineParser/Core/Parsing/ArgumentManager.cs +++ b/CommandLineParser/Core/Parsing/ArgumentManager.cs @@ -15,30 +15,34 @@ namespace MatthiWare.CommandLine.Core.Parsing public class ArgumentManager : IArgumentManager { private readonly CommandLineParserOptions options; - private readonly ICommandLineCommandContainer commandContainer; private readonly ILogger logger; private IEnumerator enumerator; private readonly Dictionary results = new Dictionary(); private readonly List unusedArguments = new List(); + private readonly List unprocessedArguments = new List(); private ProcessingContext CurrentContext; - private bool isFirstUnprocessedArgument = true; /// public IReadOnlyList UnusedArguments => unusedArguments; + /// + public IReadOnlyList UnprocessedArguments => unprocessedArguments; + + /// + public bool StopParsingFlagSpecified { get; private set; } + /// public bool TryGetValue(IArgument argument, out ArgumentModel model) => results.TryGetValue(argument, out model); /// - public ArgumentManager(CommandLineParserOptions options, ICommandLineCommandContainer commandContainer, ILogger logger) + public ArgumentManager(CommandLineParserOptions options, ILogger logger) { this.options = options ?? throw new ArgumentNullException(nameof(options)); - this.commandContainer = commandContainer ?? throw new ArgumentNullException(nameof(commandContainer)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// - public void Process(IReadOnlyList arguments, IList errors) + public void Process(IReadOnlyList arguments, IList errors, ICommandLineCommandContainer commandContainer) { results.Clear(); unusedArguments.Clear(); @@ -46,8 +50,6 @@ public void Process(IReadOnlyList arguments, IList errors) enumerator = new ArgumentRecordEnumerator(options, arguments); CurrentContext = new ProcessingContext(null, commandContainer, logger); - isFirstUnprocessedArgument = true; - try { while (enumerator.MoveNext()) @@ -56,7 +58,7 @@ public void Process(IReadOnlyList arguments, IList errors) if (!processed) { - AddUnprocessedArgument(enumerator.Current); + AddUnusedArgument(enumerator.Current); } } } @@ -108,15 +110,17 @@ private bool ProcessHelp(HelpRecord help) private bool StopProcessing() { + StopParsingFlagSpecified = true; + while (enumerator.MoveNext()) { - // do nothing + AddUnprocessedArgument(enumerator.Current); } - return false; + return true; } - private void AddUnprocessedArgument(ArgumentRecord rec) + private void AddUnusedArgument(ArgumentRecord rec) { var arg = CurrentContext.CurrentOption != null ? (IArgument)CurrentContext.CurrentOption : (IArgument)CurrentContext.CurrentCommand; var item = new UnusedArgumentModel(rec.RawData, arg); @@ -124,6 +128,14 @@ private void AddUnprocessedArgument(ArgumentRecord rec) unusedArguments.Add(item); } + private void AddUnprocessedArgument(ArgumentRecord rec) + { + var arg = CurrentContext.CurrentOption != null ? (IArgument)CurrentContext.CurrentOption : (IArgument)CurrentContext.CurrentCommand; + var item = new UnusedArgumentModel(rec.RawData, arg); + + unprocessedArguments.Add(item); + } + private bool ProcessOption(OptionRecord rec) { var foundOption = FindOption(rec); diff --git a/CommandLineParser/Core/Parsing/Resolvers/DefaultResolver.cs b/CommandLineParser/Core/Parsing/Resolvers/DefaultResolver.cs index 322b8ad..4081373 100644 --- a/CommandLineParser/Core/Parsing/Resolvers/DefaultResolver.cs +++ b/CommandLineParser/Core/Parsing/Resolvers/DefaultResolver.cs @@ -32,15 +32,9 @@ public DefaultResolver(ILogger logger, IServiceProvider servi public override bool CanResolve(ArgumentModel model) => TryResolve(model, out _); - public override bool CanResolve(string value) - { - throw new NotImplementedException(); - } + public override bool CanResolve(string value) => CanResolve(new ArgumentModel(string.Empty, value)); - public override T Resolve(string value) - { - throw new NotImplementedException(); - } + public override T Resolve(string value) => Resolve(new ArgumentModel(string.Empty, value)); public override T Resolve(ArgumentModel model) { diff --git a/CommandLineParser/Core/Usage/UsagePrinter.cs b/CommandLineParser/Core/Usage/UsagePrinter.cs index f1300d8..be906a8 100644 --- a/CommandLineParser/Core/Usage/UsagePrinter.cs +++ b/CommandLineParser/Core/Usage/UsagePrinter.cs @@ -106,13 +106,13 @@ public virtual void PrintUsage(ICommandLineOption option) => PrintOptionUsage(option); /// - public void PrintSuggestion(UnusedArgumentModel model) + public virtual bool PrintSuggestion(UnusedArgumentModel model) { var suggestions = suggestionProvider.GetSuggestions(model.Key, model.Argument as ICommandLineCommandContainer); if (!suggestions.Any()) { - return; + return false; } Builder.AddSuggestionHeader(model.Key); @@ -120,6 +120,8 @@ public void PrintSuggestion(UnusedArgumentModel model) Builder.AddSuggestion(suggestions.First()); console.WriteLine(Builder.Build()); + + return true; } } } diff --git a/CommandLineParser/DependencyInjectionExtensions.cs b/CommandLineParser/DependencyInjectionExtensions.cs new file mode 100644 index 0000000..23f8c86 --- /dev/null +++ b/CommandLineParser/DependencyInjectionExtensions.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.DependencyInjection; +using MatthiWare.CommandLine.Core; +using System; +using MatthiWare.CommandLine.Abstractions; + +namespace MatthiWare.CommandLine +{ + /// + /// Extension methods to allow DI services to be registered. + /// + public static class DependencyInjectionExtensions + { + /// + /// Adds to the services + /// This won't overwrite existing services. + /// + /// Base option type + /// Current service collection + /// Current options reference + public static void AddCommandLineParser(this IServiceCollection services, CommandLineParserOptions options = null) + where TOption : class, new() + { + Func> factory = (IServiceProvider provider) + => new CommandLineParser(provider.GetService(), provider); + + services + .AddInternalCommandLineParserServices2(options) + .AddCommandLineParserFactoryGeneric(factory); + } + + /// + /// Adds to the services + /// This won't overwrite existing services. + /// + /// Current service collection + /// Current options reference + public static void AddCommandLineParser(this IServiceCollection services, CommandLineParserOptions options = null) + { + Func factory = (IServiceProvider provider) + => new CommandLineParser(provider.GetService(), provider); + + services + .AddInternalCommandLineParserServices2(options) + .AddCommandLineParserFactory(factory); + } + } +} diff --git a/Extensions/FluentValidationsExtensions/CommandLineParser.FluentValidations.xml b/Extensions/FluentValidationsExtensions/CommandLineParser.FluentValidations.xml index a17ff4c..4cd0a7f 100644 --- a/Extensions/FluentValidationsExtensions/CommandLineParser.FluentValidations.xml +++ b/Extensions/FluentValidationsExtensions/CommandLineParser.FluentValidations.xml @@ -54,7 +54,7 @@ FluentValidations Extensions for CommandLineParser - + Extensions to configure FluentValidations for the Parser diff --git a/Extensions/FluentValidationsExtensions/Core/FluentValidationConfiguration.cs b/Extensions/FluentValidationsExtensions/Core/FluentValidationConfiguration.cs index bc09bd0..bd1dfc3 100644 --- a/Extensions/FluentValidationsExtensions/Core/FluentValidationConfiguration.cs +++ b/Extensions/FluentValidationsExtensions/Core/FluentValidationConfiguration.cs @@ -50,7 +50,7 @@ public FluentValidationConfiguration AddValidator(Type key, Type validator) /// Validator type /// Self public FluentValidationConfiguration AddValidator() - where V : AbstractValidator, new() + where V : AbstractValidator { GetValidatorCollection(typeof(K)).AddValidator(); @@ -65,7 +65,7 @@ public FluentValidationConfiguration AddValidator() /// Instance /// Self public FluentValidationConfiguration AddValidatorInstance(V instance) - where V : AbstractValidator, new() + where V : AbstractValidator { if (instance is null) { diff --git a/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.cs b/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.cs index 07ea45e..4a2d3c9 100644 --- a/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.cs +++ b/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.cs @@ -1,4 +1,5 @@ -using MatthiWare.CommandLine.Extensions.FluentValidations.Core; +using MatthiWare.CommandLine.Abstractions; +using MatthiWare.CommandLine.Extensions.FluentValidations.Core; using System; namespace MatthiWare.CommandLine.Extensions.FluentValidations @@ -14,7 +15,7 @@ public static class FluentValidationsExtensions /// /// /// Configuration action - public static void UseFluentValidations(this CommandLineParser parser, Action configAction) + public static void UseFluentValidations(this ICommandLineParser parser, Action configAction) where T : class, new() { var config = new FluentValidationConfiguration(parser.Validators, parser.Services); diff --git a/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.csproj b/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.csproj index 455bdf1..f702416 100644 --- a/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.csproj +++ b/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.csproj @@ -4,24 +4,24 @@ netstandard2.0 MatthiWare.CommandLine.Extensions.FluentValidations CommandLineParser.FluentValidations - 0.5.0 + 0.7.0 Matthias Beerens MatthiWare - FluentValidations Extension For CommandLineParser.Core - FluentValidations extension for CommandLineParser.Core + FluentValidations Extension For MatthiWare.CommandLineParser + FluentValidations extension for MatthiWare.CommandLineParser https://github.com/MatthiWare/CommandLineParser.Core https://github.com/MatthiWare/CommandLineParser.Core Commandline parser commandline-parser cli fluent-validations extension 7.3 - 0.5.0.0 - 0.5.0.0 + 0.7.0.0 + 0.7.0.0 LICENSE - - Option clustering/grouping -- Suggestions when mistyping command/options -- Positional parameters -- Support for all basic datatypes + - Update license to MIT Copyright Matthias Beerens 2019 + MatthiWare.CommandLineParser.Extensions.FluentValidations + git + True @@ -33,7 +33,7 @@ - + diff --git a/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.nuspec b/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.nuspec index 2c6662c..9191744 100644 --- a/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.nuspec +++ b/Extensions/FluentValidationsExtensions/FluentValidationsExtensions.nuspec @@ -22,7 +22,7 @@ Copyright Matthias Beerens 2019 commandline parser commandline-parser extension fluent-validation validations - + diff --git a/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsExtensions.Tests.csproj b/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsExtensions.Tests.csproj index bf03ac0..c0590d6 100644 --- a/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsExtensions.Tests.csproj +++ b/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsExtensions.Tests.csproj @@ -1,20 +1,20 @@  - netcoreapp3.1 + net5.0 false - + all runtime; build; native; contentfiles; analyzers - - - - + + + + all runtime; build; native; contentfiles; analyzers diff --git a/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsTests.cs b/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsTests.cs index bca4dcc..4a0d1a4 100644 --- a/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsTests.cs +++ b/Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsTests.cs @@ -5,6 +5,8 @@ using MatthiWare.CommandLine.Extensions.FluentValidations; using MatthiWare.CommandLine.Extensions.FluentValidations.Core; using MatthiWare.CommandLine.Tests; +using Microsoft.Extensions.DependencyInjection; +using Moq; using Xunit; using Xunit.Abstractions; @@ -26,7 +28,8 @@ public FluentValidationsTests(ITestOutputHelper testOutputHelper) : base(testOut [InlineData(false, false)] public void FluentValidationsShouldWork(bool useGeneric, bool useInstance) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.UseFluentValidations(config => { @@ -47,7 +50,8 @@ public void FluentValidationsShouldWork(bool useGeneric, bool useInstance) [InlineData(false, false)] public void WrongArgumentsShouldThrowValidationError(bool useGeneric, bool useInstance) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.UseFluentValidations(config => { @@ -68,7 +72,8 @@ public void WrongArgumentsShouldThrowValidationError(bool useGeneric, bool useIn [InlineData(false, false)] public void SubCommandShouldFailIfValidationFailsForModel(bool useGeneric, bool useInstance) { - var parser = new CommandLineParser(Services); + Services.AddCommandLineParser(); + var parser = ResolveParser(); parser.UseFluentValidations(config => { @@ -82,6 +87,28 @@ public void SubCommandShouldFailIfValidationFailsForModel(bool useGeneric, bool Assert.True(result.AssertNoErrors(false)); } + [Fact] + public void GenericAddValidatorWithDependencyShouldWork() + { + var dependencyMock = new Mock(); + dependencyMock.Setup(_ => _.IsValid(It.IsAny())).Returns(true).Verifiable(); + + Services.AddSingleton(dependencyMock.Object); + + Services.AddCommandLineParser(); + var parser = ResolveParser(); + + parser.UseFluentValidations(config => + { + config.AddValidator(); + }); + + var result = parser.Parse(new string[] { "-e", "jane.doe@provider.com", "-i", "0" }); + + result.AssertNoErrors(); + dependencyMock.Verify(); + } + private void OnConfigureFluentValidations(FluentValidationConfiguration config, bool useGeneric, bool useInstantiated) { if (useGeneric) diff --git a/Extensions/Tests/FluentValidationsExtensions.Tests/Validators/ValidatorWithDependency.cs b/Extensions/Tests/FluentValidationsExtensions.Tests/Validators/ValidatorWithDependency.cs new file mode 100644 index 0000000..240879b --- /dev/null +++ b/Extensions/Tests/FluentValidationsExtensions.Tests/Validators/ValidatorWithDependency.cs @@ -0,0 +1,18 @@ +using FluentValidation; +using FluentValidationsExtensions.Tests.Models; + +namespace FluentValidationsExtensions.Tests.Validators +{ + public class ValidatorWithDependency : AbstractValidator + { + public ValidatorWithDependency(IValidationDependency dependency) + { + RuleFor(_ => _.Email).Must(dependency.IsValid); + } + } + + public interface IValidationDependency + { + bool IsValid(string input); + } +} diff --git a/LICENSE b/LICENSE index 7ba7a13..e5e8f95 100644 --- a/LICENSE +++ b/LICENSE @@ -1,661 +1,21 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) 2018 Matthias Beerens - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. +MIT License + +Copyright (c) 2022 MatthiWare + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 54524dc..3bc598c 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -[![AppVeyor](https://ci.appveyor.com/api/projects/status/4w6ik2k8lx95afp8?svg=true)](https://ci.appveyor.com/project/Matthiee/commandlineparser-core) +[![.NET Core](https://github.com/MatthiWare/CommandLineParser.Core/actions/workflows/dotnet-core.yml/badge.svg)](https://github.com/MatthiWare/CommandLineParser.Core/actions/workflows/dotnet-core.yml) [![Issues](https://img.shields.io/github/issues/MatthiWare/CommandLineParser.Core.svg)](https://github.com/MatthiWare/CommandLineParser.Core/issues) [![CodeCov](https://codecov.io/gh/MatthiWare/CommandLineParser.Core/branch/master/graph/badge.svg)](https://codecov.io/gh/MatthiWare/CommandLineParser.Core) [![CodeFactor](https://www.codefactor.io/repository/github/matthiware/commandlineparser.core/badge)](https://www.codefactor.io/repository/github/matthiware/commandlineparser.core) -[![License](https://img.shields.io/badge/License-AGPL%20v3-blue.svg)](https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)) +[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://tldrlegal.com/license/mit-license) [![Nuget](https://buildstats.info/nuget/MatthiWare.CommandLineParser)](https://www.nuget.org/packages/MatthiWare.CommandLineParser) # CommandLineParser diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..23c5255 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 0.5.x | :white_check_mark: | +| < 0.5 | :x: | + +## Reporting a Vulnerability + +Send an email to security@matthiware.be diff --git a/SampleApp/Program.cs b/SampleApp/Program.cs index bdf3df5..1829476 100644 --- a/SampleApp/Program.cs +++ b/SampleApp/Program.cs @@ -2,6 +2,7 @@ using System.Reflection; using System.Threading.Tasks; using MatthiWare.CommandLine; +using MatthiWare.CommandLine.Abstractions; using MatthiWare.CommandLine.Extensions.FluentValidations; using Microsoft.Extensions.DependencyInjection; using SampleApp.DependencyInjection; @@ -27,7 +28,11 @@ static async Task Main(string[] args) var parserOptions = new CommandLineParserOptions { AppName = "Sample App" }; - var parser = new CommandLineParser(parserOptions, services); + services.AddCommandLineParser(parserOptions); + + var provider = services.BuildServiceProvider(); + + var parser = provider.GetRequiredService>(); #region Example to add FluentValidations to the project parser.UseFluentValidations((config) => diff --git a/SampleApp/SampleApp.csproj b/SampleApp/SampleApp.csproj index ff0aa85..b1afe0e 100644 --- a/SampleApp/SampleApp.csproj +++ b/SampleApp/SampleApp.csproj @@ -2,12 +2,12 @@ Exe - netcoreapp3.1 + net5.0 7.3 - + diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 1a087b6..0000000 --- a/appveyor.yml +++ /dev/null @@ -1,23 +0,0 @@ -# Operating system (build VM template) -os: Visual Studio 2019 - -version: 0.4.{build} - -environment: - GH_PKG_TOKEN: - secure: bnq6VslCdaO6sR3mk0X31tZ3QOXnBtftA09+T9m9qBkxFIENdBRAD8bPHxRvESc5 - -# Build script -build_script: - - ps: .\build.ps1 --target="AppVeyor" --verbosity=Verbose - -# artifacts -artifacts: -- path: 'nuget\*.nupkg' - name: NuGet - -# Tests -test: off - -init: - - git config --global core.autocrlf true \ No newline at end of file diff --git a/build.cake b/build.cake deleted file mode 100644 index 7c68e5e..0000000 --- a/build.cake +++ /dev/null @@ -1,176 +0,0 @@ -#tool "nuget:?package=xunit.runner.console&version=2.4.1" -#tool nuget:?package=Codecov -#addin "nuget:?package=Cake.Codecov&version=0.9.1"" -#addin nuget:?package=Cake.Coverlet -/////////////////////////////////////////////////////////////////////////////// -// ARGUMENTS -/////////////////////////////////////////////////////////////////////////////// - -var target = Argument("target", "Default"); -var configuration = Argument("configuration", "Release"); - -////////////////////////////////////////////////////////////////////// -// PARAMETERS -////////////////////////////////////////////////////////////////////// - -var project = "CommandLineParser"; -var solution = $"./{project}.sln"; -var cmdParserProject = $"./{project}/{project}.csproj"; -var fveProject = $"./Extensions/FluentValidationsExtensions/FluentValidationsExtensions.csproj"; -var nuspecFile = $"./{project}/{project}.nuspec"; -var fvNuspecFile = $"./Extensions/FluentValidationsExtensions/FluentValidationsExtensions.nuspec"; -var tests = $"./{project}.Tests/{project}.Tests.csproj"; -var fveTests = $"./Extensions/Tests/FluentValidationsExtensions.Tests/FluentValidationsExtensions.Tests.csproj"; -var publishPath = MakeAbsolute(Directory("./output")); -var nugetPackageDir = MakeAbsolute(Directory("./nuget")); -var codeCoverageOutput = MakeAbsolute(Directory("./code-coverage/")); - -/////////////////////////////////////////////////////////////////////////////// -// TASKS -/////////////////////////////////////////////////////////////////////////////// - -Task("Publish-NuGet") - .IsDependentOn("Generate-NuGet") - .Does(() => { - return; - - var feed = new - { - Name = "Github", - Source = "https://nuget.pkg.github.com/MatthiWare/index.json" - }; - - NuGetAddSource(feed.Name, feed.Source); - - var pushSettings = new NuGetPushSettings { - Source = "Github", - ApiKey = EnvironmentVariable("GH_PKG_TOKEN") - }; - - NuGetPush("./nuget/*.*", pushSettings); - }); - -Task("Clean") - .Does( () => { - CleanDirectories($"./{project}/obj/**/*.*"); - CleanDirectories($"./{project}/bin/{configuration}/**/*.*"); -}); - -Task("Clean-Publish") - .IsDependentOn("Clean") - .Does( () => { - CleanDirectory(publishPath); -}); - -Task("Build") - .Does(() => - { - DotNetCoreBuild(solution, - new DotNetCoreBuildSettings - { - NoRestore = false, - Configuration = configuration - }); - }); - -Task("Test") - .IsDependentOn("Build") - .Does( () => { - - var coverletSettings = new CoverletSettings { - CollectCoverage = true, - CoverletOutputDirectory = codeCoverageOutput, - CoverletOutputFormat = CoverletOutputFormat.opencover, - CoverletOutputName = $"coverage.xml", - MergeWithFile = $"{codeCoverageOutput}\\coverage.xml" - }; - - var coverletSettings2 = new CoverletSettings { - CollectCoverage = true, - CoverletOutputDirectory = codeCoverageOutput, - CoverletOutputFormat = CoverletOutputFormat.opencover, - CoverletOutputName = $"coverage2.xml", - MergeWithFile = $"{codeCoverageOutput}\\coverage.xml" - }; - - Information($"MergeWithFile: {coverletSettings.MergeWithFile.FullPath}"); - - //Information(FileSize(coverletSettings.MergeWithFile)); - - var testSettings = new DotNetCoreTestSettings { - NoBuild = true, - NoRestore = true, - Configuration = configuration - }; - - // Upload a coverage report. - // Information("(1) Codecov: Uploading coverage.xml"); - // Codecov($"{codeCoverageOutput}\\coverage.xml"); - - DotNetCoreTest(fveTests, testSettings, coverletSettings); - - DotNetCoreTest(tests, testSettings, coverletSettings2); - - // Upload a coverage report. - Information("(1) Codecov: Uploading coverage.xml (merged)"); - Codecov($"{codeCoverageOutput}\\coverage2.xml"); -}); - -Task("Publish") - .IsDependentOn("Test") - .IsDependentOn("Clean-Publish") - .Does( () => { - DotNetCorePublish(cmdParserProject, - new DotNetCorePublishSettings { - - NoRestore = true, - Configuration = configuration, - OutputDirectory = publishPath - }); - - DotNetCorePublish(fveProject, - new DotNetCorePublishSettings { - - NoRestore = true, - Configuration = configuration, - OutputDirectory = publishPath - }); - - Information("Publish: Done"); -}); - -Task("Generate-NuGet") - .IsDependentOn("Publish") - .Does(() => - { - var nuGetPackSettings = new NuGetPackSettings - { - BasePath = publishPath, - OutputDirectory = nugetPackageDir, - IncludeReferencedProjects = false, - - Properties = new Dictionary - { - { "Configuration", configuration } - } - }; - - var files = GetFiles("./output/**/*.*"); - foreach(var file in files) - { - Information("File: {0}", file); - } - - NuGetPack(nuspecFile, nuGetPackSettings); - NuGetPack(fvNuspecFile, nuGetPackSettings); - - Information("NuGetPack: Done"); - }); - -Task("Default") - .IsDependentOn("Test"); - -Task("AppVeyor") - .IsDependentOn("Publish-NuGet"); - -RunTarget(target); \ No newline at end of file diff --git a/build.config b/build.config deleted file mode 100644 index 6313cad..0000000 --- a/build.config +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash -CAKE_VERSION=0.38.5 -DOTNET_VERSION=3.1.402 \ No newline at end of file diff --git a/build.ps1 b/build.ps1 deleted file mode 100644 index e48d09a..0000000 --- a/build.ps1 +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env pwsh -$DotNetInstallerUri = 'https://dot.net/v1/dotnet-install.ps1'; -$DotNetUnixInstallerUri = 'https://dot.net/v1/dotnet-install.sh' -$DotNetChannel = 'LTS' -$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent - -[string] $CakeVersion = '' -[string] $DotNetVersion= '' -foreach($line in Get-Content (Join-Path $PSScriptRoot 'build.config')) -{ - if ($line -like 'CAKE_VERSION=*') { - $CakeVersion = $line.SubString(13) - } - elseif ($line -like 'DOTNET_VERSION=*') { - $DotNetVersion =$line.SubString(15) - } -} - - -if ([string]::IsNullOrEmpty($CakeVersion) -or [string]::IsNullOrEmpty($DotNetVersion)) { - 'Failed to parse Cake / .NET Core SDK Version' - exit 1 -} - -# Make sure tools folder exists -$ToolPath = Join-Path $PSScriptRoot "tools" -if (!(Test-Path $ToolPath)) { - Write-Verbose "Creating tools directory..." - New-Item -Path $ToolPath -Type Directory -Force | out-null -} - - -if ($PSVersionTable.PSEdition -ne 'Core') { - # Attempt to set highest encryption available for SecurityProtocol. - # PowerShell will not set this by default (until maybe .NET 4.6.x). This - # will typically produce a message for PowerShell v2 (just an info - # message though) - try { - # Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48) - # Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't - # exist in .NET 4.0, even though they are addressable if .NET 4.5+ is - # installed (.NET 4.5 is an in-place upgrade). - [System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48 - } catch { - Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3' - } -} - -########################################################################### -# INSTALL .NET CORE CLI -########################################################################### - -$env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 -$env:DOTNET_CLI_TELEMETRY_OPTOUT=1 -$env:DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX=2 - - -Function Remove-PathVariable([string]$VariableToRemove) -{ - $SplitChar = ';' - if ($IsMacOS -or $IsLinux) { - $SplitChar = ':' - } - - $path = [Environment]::GetEnvironmentVariable("PATH", "User") - if ($path -ne $null) - { - $newItems = $path.Split($SplitChar, [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove } - [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join($SplitChar, $newItems), "User") - } - - $path = [Environment]::GetEnvironmentVariable("PATH", "Process") - if ($path -ne $null) - { - $newItems = $path.Split($SplitChar, [StringSplitOptions]::RemoveEmptyEntries) | Where-Object { "$($_)" -inotlike $VariableToRemove } - [Environment]::SetEnvironmentVariable("PATH", [System.String]::Join($SplitChar, $newItems), "Process") - } -} - -# Get .NET Core CLI path if installed. -$FoundDotNetCliVersion = $null; -if (Get-Command dotnet -ErrorAction SilentlyContinue) { - $FoundDotNetCliVersion = dotnet --version; -} - -if($FoundDotNetCliVersion -ne $DotNetVersion) { - $InstallPath = Join-Path $PSScriptRoot ".dotnet" - if (!(Test-Path $InstallPath)) { - New-Item -Path $InstallPath -ItemType Directory -Force | Out-Null; - } - - if ($IsMacOS -or $IsLinux) { - $ScriptPath = Join-Path $InstallPath 'dotnet-install.sh' - (New-Object System.Net.WebClient).DownloadFile($DotNetUnixInstallerUri, $ScriptPath); - & bash $ScriptPath --version "$DotNetVersion" --install-dir "$InstallPath" --channel "$DotNetChannel" --no-path - - Remove-PathVariable "$InstallPath" - $env:PATH = "$($InstallPath):$env:PATH" - } - else { - $ScriptPath = Join-Path $InstallPath 'dotnet-install.ps1' - (New-Object System.Net.WebClient).DownloadFile($DotNetInstallerUri, $ScriptPath); - & $ScriptPath -Channel $DotNetChannel -Version $DotNetVersion -InstallDir $InstallPath; - - Remove-PathVariable "$InstallPath" - $env:PATH = "$InstallPath;$env:PATH" - } - $env:DOTNET_ROOT=$InstallPath -} - -########################################################################### -# INSTALL CAKE -########################################################################### - -# Make sure Cake has been installed. -[string] $CakeExePath = '' -[string] $CakeInstalledVersion = Get-Command dotnet-cake -ErrorAction SilentlyContinue | % {&$_.Source --version} - -if ($CakeInstalledVersion -eq $CakeVersion) { - # Cake found locally - $CakeExePath = (Get-Command dotnet-cake).Source -} -else { - $CakePath = [System.IO.Path]::Combine($ToolPath,'.store', 'cake.tool', $CakeVersion) # Old PowerShell versions Join-Path only supports one child path - - $CakeExePath = (Get-ChildItem -Path $ToolPath -Filter "dotnet-cake*" -File| ForEach-Object FullName | Select-Object -First 1) - - - if ((!(Test-Path -Path $CakePath -PathType Container)) -or (!(Test-Path $CakeExePath -PathType Leaf))) { - - if ((![string]::IsNullOrEmpty($CakeExePath)) -and (Test-Path $CakeExePath -PathType Leaf)) - { - & dotnet tool uninstall --tool-path $ToolPath Cake.Tool - } - - & dotnet tool install --tool-path $ToolPath --version $CakeVersion Cake.Tool - if ($LASTEXITCODE -ne 0) - { - 'Failed to install cake' - exit 1 - } - $CakeExePath = (Get-ChildItem -Path $ToolPath -Filter "dotnet-cake*" -File| ForEach-Object FullName | Select-Object -First 1) - } -} - -########################################################################### -# RUN BUILD SCRIPT -########################################################################### -& "$CakeExePath" ./build.cake --bootstrap -if ($LASTEXITCODE -eq 0) -{ - & "$CakeExePath" ./build.cake $args -} -exit $LASTEXITCODE \ No newline at end of file diff --git a/build.sh b/build.sh deleted file mode 100644 index 06bcee8..0000000 --- a/build.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/usr/bin/env bash -# Define varibles -SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) -source $SCRIPT_DIR/build.config -TOOLS_DIR=$SCRIPT_DIR/tools -CAKE_EXE=$TOOLS_DIR/dotnet-cake -CAKE_PATH=$TOOLS_DIR/.store/cake.tool/$CAKE_VERSION - -if [ "$CAKE_VERSION" = "" ] || [ "$DOTNET_VERSION" = "" ]; then - echo "An error occured while parsing Cake / .NET Core SDK version." - exit 1 -fi - -# Make sure the tools folder exist. -if [ ! -d "$TOOLS_DIR" ]; then - mkdir "$TOOLS_DIR" -fi - -########################################################################### -# INSTALL .NET CORE CLI -########################################################################### - -export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1 -export DOTNET_CLI_TELEMETRY_OPTOUT=1 -export DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER=0 -export DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX=2 - -DOTNET_INSTALLED_VERSION=$(dotnet --version 2>&1) - -if [ "$DOTNET_VERSION" != "$DOTNET_INSTALLED_VERSION" ]; then - echo "Installing .NET CLI..." - if [ ! -d "$SCRIPT_DIR/.dotnet" ]; then - mkdir "$SCRIPT_DIR/.dotnet" - fi - curl -Lsfo "$SCRIPT_DIR/.dotnet/dotnet-install.sh" https://dot.net/v1/dotnet-install.sh - bash "$SCRIPT_DIR/.dotnet/dotnet-install.sh" --version $DOTNET_VERSION --install-dir .dotnet --no-path - export PATH="$SCRIPT_DIR/.dotnet":$PATH - export DOTNET_ROOT="$SCRIPT_DIR/.dotnet" -fi - -########################################################################### -# INSTALL CAKE -########################################################################### - -CAKE_INSTALLED_VERSION=$(dotnet-cake --version 2>&1) - -if [ "$CAKE_VERSION" != "$CAKE_INSTALLED_VERSION" ]; then - if [ ! -f "$CAKE_EXE" ] || [ ! -d "$CAKE_PATH" ]; then - if [ -f "$CAKE_EXE" ]; then - dotnet tool uninstall --tool-path $TOOLS_DIR Cake.Tool - fi - - echo "Installing Cake $CAKE_VERSION..." - dotnet tool install --tool-path $TOOLS_DIR --version $CAKE_VERSION Cake.Tool - if [ $? -ne 0 ]; then - echo "An error occured while installing Cake." - exit 1 - fi - fi - - # Make sure that Cake has been installed. - if [ ! -f "$CAKE_EXE" ]; then - echo "Could not find Cake.exe at '$CAKE_EXE'." - exit 1 - fi -else - CAKE_EXE="dotnet-cake" -fi - -########################################################################### -# RUN BUILD SCRIPT -########################################################################### - -# Start Cake -(exec "$CAKE_EXE" build.cake --bootstrap) && (exec "$CAKE_EXE" build.cake "$@") \ No newline at end of file