diff --git a/BREAKING CHANGES.md b/BREAKING CHANGES.md new file mode 100644 index 0000000000..95de0cc230 --- /dev/null +++ b/BREAKING CHANGES.md @@ -0,0 +1,5 @@ +v3.0.0 + - `AssemblyFileSemVer` variable removed, AssemblyVersioningScheme configuration value makes this variable obsolete + - `ClassicVersion` variable removed, + - `ClassicVersionWithTag` variable removed, as above + - MSBuild task arguments (AssemblyVersioningScheme, DevelopBranchTag, ReleaseBranchTag, TagPrefix, NextVersion) have been removed, use GitVersionConfig.yaml instead \ No newline at end of file diff --git a/GitVersion.sln b/GitVersion.sln index c3c5f54722..965c8df351 100644 --- a/GitVersion.sln +++ b/GitVersion.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30723.0 +# Visual Studio 14 +VisualStudioVersion = 14.0.22512.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitVersionExe", "GitVersionExe\GitVersionExe.csproj", "{C3578A7B-09A6-4444-9383-0DEAFA4958BD}" EndProject @@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitVersionCore.Tests", "Git EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3EFFC5D6-88D0-49D9-BB53-E1B7EB49DD45}" ProjectSection(SolutionItems) = preProject + BREAKING CHANGES.md = BREAKING CHANGES.md + GitVersionConfig.yaml = GitVersionConfig.yaml LICENSE = LICENSE README.md = README.md EndProjectSection @@ -24,47 +26,33 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU - Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU - Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C3578A7B-09A6-4444-9383-0DEAFA4958BD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C3578A7B-09A6-4444-9383-0DEAFA4958BD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C3578A7B-09A6-4444-9383-0DEAFA4958BD}.Debug|x86.ActiveCfg = Debug|Any CPU {C3578A7B-09A6-4444-9383-0DEAFA4958BD}.Release|Any CPU.ActiveCfg = Release|Any CPU {C3578A7B-09A6-4444-9383-0DEAFA4958BD}.Release|Any CPU.Build.0 = Release|Any CPU - {C3578A7B-09A6-4444-9383-0DEAFA4958BD}.Release|x86.ActiveCfg = Release|Any CPU {5A86453B-96FB-4B6E-A283-225BB9F753D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5A86453B-96FB-4B6E-A283-225BB9F753D3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5A86453B-96FB-4B6E-A283-225BB9F753D3}.Debug|x86.ActiveCfg = Debug|Any CPU {5A86453B-96FB-4B6E-A283-225BB9F753D3}.Release|Any CPU.ActiveCfg = Release|Any CPU {5A86453B-96FB-4B6E-A283-225BB9F753D3}.Release|Any CPU.Build.0 = Release|Any CPU - {5A86453B-96FB-4B6E-A283-225BB9F753D3}.Release|x86.ActiveCfg = Release|Any CPU {F7AC0E71-3E9A-4F6D-B986-E004825A48E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F7AC0E71-3E9A-4F6D-B986-E004825A48E1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F7AC0E71-3E9A-4F6D-B986-E004825A48E1}.Debug|x86.ActiveCfg = Debug|Any CPU {F7AC0E71-3E9A-4F6D-B986-E004825A48E1}.Release|Any CPU.ActiveCfg = Release|Any CPU {F7AC0E71-3E9A-4F6D-B986-E004825A48E1}.Release|Any CPU.Build.0 = Release|Any CPU - {F7AC0E71-3E9A-4F6D-B986-E004825A48E1}.Release|x86.ActiveCfg = Release|Any CPU {BF905F84-382C-440D-92F5-C61108626D8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BF905F84-382C-440D-92F5-C61108626D8D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BF905F84-382C-440D-92F5-C61108626D8D}.Debug|x86.ActiveCfg = Debug|Any CPU {BF905F84-382C-440D-92F5-C61108626D8D}.Release|Any CPU.ActiveCfg = Release|Any CPU {BF905F84-382C-440D-92F5-C61108626D8D}.Release|Any CPU.Build.0 = Release|Any CPU - {BF905F84-382C-440D-92F5-C61108626D8D}.Release|x86.ActiveCfg = Release|Any CPU {F9741A0D-B9D7-4557-9A1C-A7252C1071F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F9741A0D-B9D7-4557-9A1C-A7252C1071F5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F9741A0D-B9D7-4557-9A1C-A7252C1071F5}.Debug|x86.ActiveCfg = Debug|Any CPU {F9741A0D-B9D7-4557-9A1C-A7252C1071F5}.Release|Any CPU.ActiveCfg = Release|Any CPU {F9741A0D-B9D7-4557-9A1C-A7252C1071F5}.Release|Any CPU.Build.0 = Release|Any CPU - {F9741A0D-B9D7-4557-9A1C-A7252C1071F5}.Release|x86.ActiveCfg = Release|Any CPU {75C2BE85-1DAF-4E34-8305-B17AFAA982A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {75C2BE85-1DAF-4E34-8305-B17AFAA982A6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {75C2BE85-1DAF-4E34-8305-B17AFAA982A6}.Debug|x86.ActiveCfg = Debug|Any CPU {75C2BE85-1DAF-4E34-8305-B17AFAA982A6}.Release|Any CPU.ActiveCfg = Release|Any CPU {75C2BE85-1DAF-4E34-8305-B17AFAA982A6}.Release|Any CPU.Build.0 = Release|Any CPU - {75C2BE85-1DAF-4E34-8305-B17AFAA982A6}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/GitVersion.sln.DotSettings b/GitVersion.sln.DotSettings index 74fd05fb95..63741850d2 100644 --- a/GitVersion.sln.DotSettings +++ b/GitVersion.sln.DotSettings @@ -54,6 +54,8 @@ ERROR WARNING ERROR + DO_NOT_SHOW + DO_NOT_SHOW ERROR ERROR ERROR diff --git a/GitVersionConfig.yaml b/GitVersionConfig.yaml index 1efd4771c1..cc0b555163 100644 --- a/GitVersionConfig.yaml +++ b/GitVersionConfig.yaml @@ -1,2 +1,2 @@ -assembly-versioning-scheme: MajorMinor -next-version: 2.0.0 +assembly-versioning-scheme: MajorMinorPatch +next-version: 3.0.0 diff --git a/GitVersionTask.Tests/BuildServers/BuildServerBaseTests.cs b/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs similarity index 85% rename from GitVersionTask.Tests/BuildServers/BuildServerBaseTests.cs rename to GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs index 2582c199f8..8a1f3b3670 100644 --- a/GitVersionTask.Tests/BuildServers/BuildServerBaseTests.cs +++ b/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs @@ -22,7 +22,8 @@ public void BuildNumberIsFullSemVer() semanticVersion.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); semanticVersion.BuildMetaData.Sha = "commitSha"; - new BuildServer().WriteIntegration(semanticVersion, writes.Add); + var variables = VariableProvider.GetVariablesFor(semanticVersion, AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDelivery); + new BuildServer().WriteIntegration(writes.Add, variables); writes[1].ShouldBe("1.2.3-beta.1+5"); } diff --git a/GitVersionTask.Tests/BuildServers/ContinuaCiTests.cs b/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs similarity index 100% rename from GitVersionTask.Tests/BuildServers/ContinuaCiTests.cs rename to GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs diff --git a/GitVersionTask.Tests/BuildServers/MyGetTests.cs b/GitVersionCore.Tests/BuildServers/MyGetTests.cs similarity index 100% rename from GitVersionTask.Tests/BuildServers/MyGetTests.cs rename to GitVersionCore.Tests/BuildServers/MyGetTests.cs diff --git a/GitVersionTask.Tests/BuildServers/TeamCityTests.cs b/GitVersionCore.Tests/BuildServers/TeamCityTests.cs similarity index 100% rename from GitVersionTask.Tests/BuildServers/TeamCityTests.cs rename to GitVersionCore.Tests/BuildServers/TeamCityTests.cs diff --git a/GitVersionCore.Tests/ConfigProviderTests.cs b/GitVersionCore.Tests/ConfigProviderTests.cs index a8c1aa4527..5396bd410f 100644 --- a/GitVersionCore.Tests/ConfigProviderTests.cs +++ b/GitVersionCore.Tests/ConfigProviderTests.cs @@ -1,3 +1,4 @@ +using System; using System.IO; using System.Linq; using System.Reflection; @@ -25,28 +26,44 @@ public void CanReadDocument() { const string text = @" assembly-versioning-scheme: MajorMinor -develop-branch-tag: alpha -release-branch-tag: rc next-version: 2.0.0 tag-prefix: '[vV|version-]' +mode: ContinuousDelivery +branches: + develop: + mode: ContinuousDeployment + tag: dev + release[/-]: + mode: ContinuousDeployment + tag: rc "; SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(gitDirectory, fileSystem); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); - config.DevelopBranchTag.ShouldBe("alpha"); - config.ReleaseBranchTag.ShouldBe("rc"); config.NextVersion.ShouldBe("2.0.0"); config.TagPrefix.ShouldBe("[vV|version-]"); + config.VersioningMode.ShouldBe(VersioningMode.ContinuousDelivery); + config.Branches["develop"].Tag.ShouldBe("dev"); + config.Branches["release[/-]"].Tag.ShouldBe("rc"); + config.Branches["release[/-]"].VersioningMode.ShouldBe(VersioningMode.ContinuousDeployment); + config.Branches["develop"].VersioningMode.ShouldBe(VersioningMode.ContinuousDeployment); } [Test] public void CanReadOldDocument() { - const string text = @"assemblyVersioningScheme: MajorMinor"; + const string text = @" +assemblyVersioningScheme: MajorMinor +develop-branch-tag: alpha +release-branch-tag: rc +"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(gitDirectory, fileSystem); - config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); + var error = Should.Throw(() => ConfigurationProvider.Provide(gitDirectory, fileSystem)); + error.Message.ShouldContainWithoutWhitespace(@"GitVersionConfig.yaml contains old configuration, please fix the following errors: +assemblyVersioningScheme has been replaced by assembly-versioning-scheme +develop-branch-tag has been replaced by branch specific configuration.See https://github.com/ParticularLabs/GitVersion/wiki/Branch-Specific-Configuration +release-branch-tag has been replaced by branch specific configuration.See https://github.com/ParticularLabs/GitVersion/wiki/Branch-Specific-Configuration"); } [Test] @@ -56,8 +73,8 @@ public void CanReadDefaultDocument() SetupConfigFileContent(text); var config = ConfigurationProvider.Provide(gitDirectory, fileSystem); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); - config.DevelopBranchTag.ShouldBe("unstable"); - config.ReleaseBranchTag.ShouldBe("beta"); + config.Branches["develop"].Tag.ShouldBe("unstable"); + config.Branches["release[/-]"].Tag.ShouldBe("beta"); config.TagPrefix.ShouldBe("[vV]"); config.NextVersion.ShouldBe(null); } @@ -66,7 +83,9 @@ public void CanReadDefaultDocument() public void VerifyInit() { var config = typeof(Config); - var aliases = config.GetProperties().Select(p => ((YamlAliasAttribute) p.GetCustomAttribute(typeof(YamlAliasAttribute))).Alias); + var aliases = config.GetProperties() + .Where(p => p.GetCustomAttribute() == null) + .Select(p => ((YamlMemberAttribute) p.GetCustomAttribute(typeof(YamlMemberAttribute))).Alias); var writer = new StringWriter(); ConfigReader.WriteSample(writer); @@ -82,7 +101,10 @@ public void VerifyInit() public void VerifyAliases() { var config = typeof(Config); - var propertiesMissingAlias = config.GetProperties().Where(p => p.GetCustomAttribute(typeof(YamlAliasAttribute)) == null).Select(p => p.Name); + var propertiesMissingAlias = config.GetProperties() + .Where(p => p.GetCustomAttribute() == null) + .Where(p => p.GetCustomAttribute(typeof(YamlMemberAttribute)) == null) + .Select(p => p.Name); propertiesMissingAlias.ShouldBeEmpty(); } diff --git a/GitVersionCore.Tests/Fixtures/BaseGitFlowRepositoryFixture.cs b/GitVersionCore.Tests/Fixtures/BaseGitFlowRepositoryFixture.cs index ad7b5f43d7..64800c90cf 100644 --- a/GitVersionCore.Tests/Fixtures/BaseGitFlowRepositoryFixture.cs +++ b/GitVersionCore.Tests/Fixtures/BaseGitFlowRepositoryFixture.cs @@ -3,13 +3,26 @@ using GitVersion; using LibGit2Sharp; +/// +/// Creates a repo with a develop branch off master which is a single commit ahead of master +/// public class BaseGitFlowRepositoryFixture : EmptyRepositoryFixture { + /// + /// Creates a repo with a develop branch off master which is a single commit ahead of master + /// + /// Master will be tagged with the initial version before branching develop + /// public BaseGitFlowRepositoryFixture(string initialVersion) : base(new Config()) { SetupRepo(r => r.MakeATaggedCommit(initialVersion)); } + /// + /// Creates a repo with a develop branch off master which is a single commit ahead of master + /// + /// The initial setup actions will be performed before branching develop + /// public BaseGitFlowRepositoryFixture(Action initialMasterAction) : base(new Config()) { SetupRepo(initialMasterAction); @@ -19,10 +32,11 @@ void SetupRepo(Action initialMasterAction) { var randomFile = Path.Combine(Repository.Info.WorkingDirectory, Guid.NewGuid().ToString()); File.WriteAllText(randomFile, string.Empty); - Repository.Index.Stage(randomFile); + Repository.Stage(randomFile); initialMasterAction(Repository); Repository.CreateBranch("develop").Checkout(); + Repository.MakeACommit(); } } \ No newline at end of file diff --git a/GitVersionCore.Tests/Fixtures/EmptyRepositoryFixture.cs b/GitVersionCore.Tests/Fixtures/EmptyRepositoryFixture.cs index dc88f61b55..f57a38f3c7 100644 --- a/GitVersionCore.Tests/Fixtures/EmptyRepositoryFixture.cs +++ b/GitVersionCore.Tests/Fixtures/EmptyRepositoryFixture.cs @@ -1,5 +1,7 @@ -using System; +using System.Diagnostics; +using System.Text; using GitVersion; +using GitVersion.Helpers; using LibGit2Sharp; public class EmptyRepositoryFixture : RepositoryFixtureBase @@ -9,10 +11,25 @@ public EmptyRepositoryFixture(Config configuration) : { } + public void DumpGraph() + { + var output = new StringBuilder(); + + ProcessHelper.Run( + o => output.AppendLine(o), + e => output.AppendLineFormat("ERROR: {0}", e), + null, + "git", + @"log --graph --abbrev-commit --decorate --date=relative --all", + RepositoryPath); + + Trace.Write(output.ToString()); + } + static IRepository CreateNewRepository(string path) { LibGit2Sharp.Repository.Init(path); - Console.WriteLine("Created git repository at '{0}'", path); + Trace.WriteLine("Created git repository at '{0}'", path); return new Repository(path); } diff --git a/GitVersionCore.Tests/GitVersionContextBuilder.cs b/GitVersionCore.Tests/GitVersionContextBuilder.cs new file mode 100644 index 0000000000..6ff6455a18 --- /dev/null +++ b/GitVersionCore.Tests/GitVersionContextBuilder.cs @@ -0,0 +1,80 @@ +namespace GitVersionCore.Tests +{ + using GitVersion; + using LibGit2Sharp; + + public class GitVersionContextBuilder + { + IRepository repository; + Config config; + + public GitVersionContextBuilder WithRepository(IRepository repository) + { + this.repository = repository; + return this; + } + + public GitVersionContextBuilder WithConfig(Config config) + { + this.config = config; + return this; + } + + public GitVersionContextBuilder WithTaggedMaster() + { + repository = CreateRepository(); + var target = repository.Head.Tip; + ((MockTagCollection)repository.Tags).Add(new MockTag ("1.0.0", target)); + return this; + } + + public GitVersionContextBuilder AddCommit() + { + ((MockBranch)repository.Head).Add(new MockCommit()); + return this; + } + + public GitVersionContextBuilder WithDevelopBranch() + { + return WithBranch("develop"); + } + + public GitVersionContextBuilder WithBranch(string branchName) + { + repository = CreateRepository(); + return AddBranch(branchName); + } + + public GitVersionContextBuilder AddBranch(string branchName) + { + var mockBranch = new MockBranch(branchName) + { + new MockCommit() + }; + ((MockBranchCollection)repository.Branches).Add(mockBranch); + ((MockRepository)repository).Head = mockBranch; + return this; + } + + public GitVersionContext Build() + { + return new GitVersionContext(repository ?? CreateRepository(), config ?? new Config()); + } + + IRepository CreateRepository() + { + var mockBranch = new MockBranch("master") { new MockCommit { CommitterEx = SignatureBuilder.SignatureNow() } }; + var mockRepository = new MockRepository + { + Branches = new MockBranchCollection + { + mockBranch + }, + Tags = new MockTagCollection(), + Head = mockBranch + }; + + return mockRepository; + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/GitVersionContextTests.cs b/GitVersionCore.Tests/GitVersionContextTests.cs new file mode 100644 index 0000000000..3247cf506c --- /dev/null +++ b/GitVersionCore.Tests/GitVersionContextTests.cs @@ -0,0 +1,75 @@ +namespace GitVersionCore.Tests +{ + using GitVersion; + using LibGit2Sharp; + using NUnit.Framework; + using Shouldly; + + public class GitVersionContextTests + { + [Test] + [Theory] + public void CanInheritVersioningMode(VersioningMode mode) + { + var config = new Config + { + VersioningMode = mode + }; + + var mockBranch = new MockBranch("master") { new MockCommit { CommitterEx = SignatureBuilder.SignatureNow() } }; + var mockRepository = new MockRepository + { + Branches = new MockBranchCollection + { + mockBranch + } + }; + + var context = new GitVersionContext(mockRepository, mockBranch, config); + context.Configuration.VersioningMode.ShouldBe(mode); + } + + [Test] + public void UsesBranchSpecificConfigOverTopLevelDefaults() + { + var config = new Config + { + VersioningMode = VersioningMode.ContinuousDelivery + }; + config.Branches["develop"].VersioningMode = VersioningMode.ContinuousDeployment; + config.Branches["develop"].Tag = "alpha"; + var develop = new MockBranch("develop") { new MockCommit { CommitterEx = SignatureBuilder.SignatureNow() } }; + var mockRepository = new MockRepository + { + Branches = new MockBranchCollection + { + new MockBranch("master") { new MockCommit { CommitterEx = SignatureBuilder.SignatureNow() } }, + develop + } + }; + var context = new GitVersionContext(mockRepository, develop, config); + context.Configuration.Tag.ShouldBe("alpha"); + } + + [Test] + public void CanFindParentBranchForInheritingIncrementStrategy() + { + var config = new Config(); + config.Branches["develop"].Increment = IncrementStrategy.Major; + config.Branches["feature[/-]"].Increment = IncrementStrategy.Inherit; + + using (var repo = new EmptyRepositoryFixture(config)) + { + repo.Repository.MakeACommit(); + repo.Repository.CreateBranch("develop").Checkout(); + repo.Repository.MakeACommit(); + var featureBranch = repo.Repository.CreateBranch("feature/foo"); + featureBranch.Checkout(); + repo.Repository.MakeACommit(); + + var context = new GitVersionContext(repo.Repository, config); + context.Configuration.Increment.ShouldBe(IncrementStrategy.Major); + } + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/GitVersionCore.Tests.csproj b/GitVersionCore.Tests/GitVersionCore.Tests.csproj index 714da59636..b76eadfead 100644 --- a/GitVersionCore.Tests/GitVersionCore.Tests.csproj +++ b/GitVersionCore.Tests/GitVersionCore.Tests.csproj @@ -68,41 +68,64 @@ - - Helpers\DirectoryHelper.cs - + + + + + + + - - - - - - - - - - - + + + + + + + + + - - + + + + + + + + + + + + + - + + + + + + + + + + + diff --git a/GitVersionCore.Tests/Helpers/Constants.cs b/GitVersionCore.Tests/Helpers/Constants.cs index 444663252f..96953428c0 100644 --- a/GitVersionCore.Tests/Helpers/Constants.cs +++ b/GitVersionCore.Tests/Helpers/Constants.cs @@ -3,9 +3,20 @@ public static class Constants { + static DateTimeOffset simulatedTime = DateTimeOffset.Now.AddHours(-1); + + public static DateTimeOffset Now + { + get + { + simulatedTime = simulatedTime.AddMinutes(1); + return simulatedTime; + } + } + public static Signature SignatureNow() { - var dateTimeOffset = DateTimeOffset.Now; + var dateTimeOffset = Now; return Signature(dateTimeOffset); } diff --git a/GitVersionTask.Tests/Helpers/DirectoryHelper.cs b/GitVersionCore.Tests/Helpers/DirectoryHelper.cs similarity index 100% rename from GitVersionTask.Tests/Helpers/DirectoryHelper.cs rename to GitVersionCore.Tests/Helpers/DirectoryHelper.cs diff --git a/GitVersionCore.Tests/Helpers/GitTestExtensions.cs b/GitVersionCore.Tests/Helpers/GitTestExtensions.cs index e1ff69a596..bdbb3eff96 100644 --- a/GitVersionCore.Tests/Helpers/GitTestExtensions.cs +++ b/GitVersionCore.Tests/Helpers/GitTestExtensions.cs @@ -8,14 +8,14 @@ public static class GitTestExtensions { public static Commit MakeACommit(this IRepository repository) { - return MakeACommit(repository, DateTimeOffset.Now); + return MakeACommit(repository, Constants.Now); } public static Commit MakeACommit(this IRepository repository, DateTimeOffset dateTimeOffset) { var randomFile = Path.Combine(repository.Info.WorkingDirectory, Guid.NewGuid().ToString()); File.WriteAllText(randomFile, string.Empty); - repository.Index.Stage(randomFile); + repository.Stage(randomFile); return repository.Commit("Test Commit", Constants.Signature(dateTimeOffset), Constants.Signature(dateTimeOffset)); } @@ -26,6 +26,7 @@ public static void MergeNoFF(this IRepository repository, string branch) public static void MergeNoFF(this IRepository repository, string branch, Signature sig) { + // Fixes a race condition repository.Merge(repository.FindBranch(branch), sig, new MergeOptions { FastForwardStrategy = FastForwardStrategy.NoFastFoward diff --git a/GitVersionCore.Tests/Helpers/NextVersionWriter.cs b/GitVersionCore.Tests/Helpers/NextVersionWriter.cs deleted file mode 100644 index 553babf058..0000000000 --- a/GitVersionCore.Tests/Helpers/NextVersionWriter.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.IO; -using LibGit2Sharp; - -public static class NextVersionWriter -{ - public static void AddNextVersionTxtFile(this IRepository repository, string version) - { - var nextVersionFile = Path.Combine(repository.Info.WorkingDirectory, "NextVersion.txt"); - File.WriteAllText(nextVersionFile, version); - } -} \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/DevelopScenarios.cs b/GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs similarity index 52% rename from GitVersionCore.Tests/IntegrationTests/GitFlow/DevelopScenarios.cs rename to GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs index 32f0b504a9..e865ca613d 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/DevelopScenarios.cs +++ b/GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs @@ -6,57 +6,86 @@ public class DevelopScenarios { [Test] - public void WhenDevelopBranchedFromMaster_MinorIsIncreased() + public void WhenDevelopBranchedFromTaggedCommitOnMasterVersionDoesNotChange() { using (var fixture = new EmptyRepositoryFixture(new Config())) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop").Checkout(); - fixture.AssertFullSemver("1.1.0-unstable.0+0"); + fixture.AssertFullSemver("1.0.0+0"); } } [Test] - public void MergingReleaseBranchBackIntoDevelopWithoutMergingToMaster_DoesNotBumpDevelopVersion() + public void CanChangeDevelopTagViaConfig() { - using (var fixture = new EmptyRepositoryFixture(new Config())) + var config = new Config(); + config.Branches["develop"].Tag = "alpha"; + using (var fixture = new EmptyRepositoryFixture(config)) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop").Checkout(); - fixture.Repository.CreateBranch("release-2.0.0").Checkout(); - fixture.AssertFullSemver("2.0.0-beta.1+0"); - fixture.Repository.Checkout("develop"); - fixture.AssertFullSemver("1.1.0-unstable.0+0"); - fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); - fixture.AssertFullSemver("1.1.0-unstable.0+0"); + fixture.Repository.MakeACommit(); + fixture.AssertFullSemver("1.1.0-alpha.1+1"); } } - + [Test] - public void CanChangeDevelopTagViaConfig() + public void CanClearDevelopTagViaConfig() { - using (var fixture = new EmptyRepositoryFixture(new Config + var config = new Config(); + config.Branches["develop"].Tag = ""; + using (var fixture = new EmptyRepositoryFixture(config)) { - DevelopBranchTag = "alpha" - })) + fixture.Repository.MakeATaggedCommit("1.0.0"); + fixture.Repository.CreateBranch("develop").Checkout(); + fixture.Repository.MakeACommit(); + fixture.AssertFullSemver("1.1.0+1"); + } + } + + [Test] + public void WhenDevelopBranchedFromMaster_MinorIsIncreased() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop").Checkout(); - fixture.AssertFullSemver("1.1.0-alpha.0+0"); + fixture.Repository.MakeACommit(); + fixture.AssertFullSemver("1.1.0-unstable.1+1"); } } - + [Test] - public void CanClearDevelopTagViaConfig() + public void MergingReleaseBranchBackIntoDevelopWithMergingToMaster_DoesBumpDevelopVersion() { - using (var fixture = new EmptyRepositoryFixture(new Config + using (var fixture = new EmptyRepositoryFixture(new Config())) { - DevelopBranchTag = "" - })) + fixture.Repository.MakeATaggedCommit("1.0.0"); + fixture.Repository.CreateBranch("develop").Checkout(); + fixture.Repository.MakeACommit(); + fixture.Repository.CreateBranch("release-2.0.0").Checkout(); + fixture.Repository.MakeACommit(); + fixture.Repository.Checkout("master"); + fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); + + fixture.Repository.Checkout("develop"); + fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); + fixture.AssertFullSemver("2.1.0-unstable.1+0"); + } + } + + [Test] + public void CanHandleContinuousDelivery() + { + var config = new Config(); + config.Branches["develop"].VersioningMode = VersioningMode.ContinuousDelivery; + using (var fixture = new EmptyRepositoryFixture(config)) { fixture.Repository.MakeATaggedCommit("1.0.0"); fixture.Repository.CreateBranch("develop").Checkout(); - fixture.AssertFullSemver("1.1.0+0"); + fixture.Repository.MakeATaggedCommit("1.1.0-alpha7"); + fixture.AssertFullSemver("1.1.0-alpha.7+0"); } } diff --git a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/GitHubFlowFeatureBranchTests.cs b/GitVersionCore.Tests/IntegrationTests/FeatureBranchTests.cs similarity index 53% rename from GitVersionCore.Tests/IntegrationTests/GitHubFlow/GitHubFlowFeatureBranchTests.cs rename to GitVersionCore.Tests/IntegrationTests/FeatureBranchTests.cs index 1cdd7e34fb..ef4bf5d0f9 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/GitHubFlowFeatureBranchTests.cs +++ b/GitVersionCore.Tests/IntegrationTests/FeatureBranchTests.cs @@ -3,19 +3,35 @@ using NUnit.Framework; [TestFixture] -public class GitHubFlowFeatureBranchTests +public class FeatureBranchTests { [Test] - public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumber() + public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffDevelop() { using (var fixture = new EmptyRepositoryFixture(new Config())) { fixture.Repository.MakeATaggedCommit("1.0.0"); + fixture.Repository.CreateBranch("develop"); + fixture.Repository.Checkout("develop"); fixture.Repository.CreateBranch("feature/JIRA-123"); fixture.Repository.Checkout("feature/JIRA-123"); fixture.Repository.MakeCommits(5); - fixture.AssertFullSemver("1.0.1-JIRA-123+5"); + fixture.AssertFullSemver("1.1.0-JIRA-123.1+5"); + } + } + + [Test] + public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffMaster() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("1.0.0"); + fixture.Repository.CreateBranch("feature/JIRA-123"); + fixture.Repository.Checkout("feature/JIRA-123"); + fixture.Repository.MakeCommits(5); + + fixture.AssertFullSemver("1.0.1-JIRA-123.1+5"); } } @@ -29,7 +45,7 @@ public void TestFeatureBranch() fixture.Repository.Checkout("feature-test"); fixture.Repository.MakeCommits(5); - fixture.AssertFullSemver("1.0.1-feature-test+5"); + fixture.AssertFullSemver("1.0.1-test.1+5"); } } } \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/GitFlowFeatureBranchTests.cs b/GitVersionCore.Tests/IntegrationTests/GitFlow/GitFlowFeatureBranchTests.cs deleted file mode 100644 index 4790aa96e0..0000000000 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/GitFlowFeatureBranchTests.cs +++ /dev/null @@ -1,23 +0,0 @@ -using GitVersion; -using LibGit2Sharp; -using NUnit.Framework; - -[TestFixture] -public class GitFlowFeatureBranchTests -{ - [Test] - public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumber() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - fixture.Repository.MakeATaggedCommit("1.0.0"); - fixture.Repository.CreateBranch("develop"); - fixture.Repository.Checkout("develop"); - fixture.Repository.CreateBranch("feature/JIRA-123"); - fixture.Repository.Checkout("feature/JIRA-123"); - fixture.Repository.MakeCommits(5); - - fixture.AssertFullSemver("1.1.0-JIRA-123+5"); - } - } -} \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/GitFlowSupportBranchScenarios.cs b/GitVersionCore.Tests/IntegrationTests/GitFlow/GitFlowSupportBranchScenarios.cs deleted file mode 100644 index 6dc80e8b39..0000000000 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/GitFlowSupportBranchScenarios.cs +++ /dev/null @@ -1,49 +0,0 @@ -using LibGit2Sharp; -using NUnit.Framework; - -[TestFixture] -public class GitFlowSupportBranchScenarios -{ - [Test] - public void SupportIsCalculatedCorrectly() - { - using (var fixture = new BaseGitFlowRepositoryFixture("1.1.0")) - { - // Create 2.0.0 release - fixture.Repository.CreateBranch("release-2.0.0").Checkout(); - fixture.Repository.MakeCommits(2); - - // Merge into develop and master - fixture.Repository.Checkout("master"); - fixture.Repository.MergeNoFF("release-2.0.0"); - fixture.Repository.ApplyTag("2.0.0"); - fixture.Repository.Checkout("develop"); - fixture.Repository.MergeNoFF("release-2.0.0"); - fixture.AssertFullSemver("2.1.0-unstable.0+0"); - - // Now lets support 1.x release - fixture.Repository.Checkout("1.1.0"); - fixture.Repository.CreateBranch("support/1.0.0").Checkout(); - fixture.AssertFullSemver("1.1.0"); - - // Create release branch from support branch - fixture.Repository.CreateBranch("release/1.2.0").Checkout(); - fixture.Repository.MakeACommit(); - fixture.AssertFullSemver("1.2.0-beta.1+1"); - - // Create 1.2.0 release - fixture.Repository.Checkout("support/1.0.0"); - fixture.Repository.MergeNoFF("release/1.2.0"); - fixture.AssertFullSemver("1.2.0"); - fixture.Repository.ApplyTag("1.2.0"); - - // Create 1.2.1 hotfix - fixture.Repository.CreateBranch("hotfix/1.2.1").Checkout(); - fixture.Repository.MakeACommit(); - fixture.AssertFullSemver("1.2.1-beta.1+3"); // TODO This should be +1 - fixture.Repository.Checkout("support/1.0.0"); - fixture.Repository.MergeNoFF("hotfix/1.2.1"); - fixture.AssertFullSemver("1.2.1"); - } - } -} \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/ReleaseBranchTests.cs b/GitVersionCore.Tests/IntegrationTests/GitFlow/ReleaseBranchTests.cs deleted file mode 100644 index be36693040..0000000000 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/ReleaseBranchTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -using GitVersion; -using LibGit2Sharp; -using NUnit.Framework; - -[TestFixture] -public class GitFlowReleaseBranchTests -{ - [Test] - public void CanTakeVersionFromReleaseBranch() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - fixture.Repository.MakeATaggedCommit("1.0.3"); - fixture.Repository.CreateBranch("develop"); - fixture.Repository.MakeCommits(5); - fixture.Repository.CreateBranch("release-2.0.0"); - fixture.Repository.Checkout("release-2.0.0"); - - fixture.AssertFullSemver("2.0.0-beta.1+5"); - } - } - - [Test] - public void CanTakeVersionFromReleaseBranchWithTagOverriden() - { - using (var fixture = new EmptyRepositoryFixture(new Config { ReleaseBranchTag = "rc" })) - { - fixture.Repository.MakeATaggedCommit("1.0.3"); - fixture.Repository.CreateBranch("develop"); - fixture.Repository.MakeCommits(5); - fixture.Repository.CreateBranch("release-2.0.0"); - fixture.Repository.Checkout("release-2.0.0"); - - fixture.AssertFullSemver("2.0.0-rc.1+5"); - } - } - - [Test] - public void CanHandleReleaseBranchWithStability() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - fixture.Repository.MakeATaggedCommit("1.0.3"); - fixture.Repository.CreateBranch("develop"); - fixture.Repository.MakeCommits(5); - fixture.Repository.CreateBranch("release-2.0.0-Final"); - fixture.Repository.Checkout("release-2.0.0-Final"); - - fixture.AssertFullSemver("2.0.0-beta.1+5"); - } - } - - [Test] - public void WhenReleaseBranchIsMergedIntoMasterVersionIsTakenWithIt() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - fixture.Repository.MakeATaggedCommit("1.0.3"); - fixture.Repository.CreateBranch("develop"); - fixture.Repository.MakeCommits(1); - fixture.Repository.CreateBranch("release-2.0.0"); - fixture.Repository.Checkout("release-2.0.0"); - fixture.Repository.MakeCommits(4); - fixture.Repository.Checkout("master"); - fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); - - // TODO For GitHubFlow this is 2.0.0+6, why is it different - fixture.AssertFullSemver("2.0.0"); - } - } - - // TODO This test fails for GitFlow, it needs to be fixed (although in reality a support branch should be used) - [Test, Ignore] - public void WhenReleaseBranchIsMergedIntoMasterHighestVersionIsTakenWithIt() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - fixture.Repository.MakeATaggedCommit("1.0.3"); - fixture.Repository.CreateBranch("develop"); - fixture.Repository.MakeCommits(1); - - fixture.Repository.CreateBranch("release-2.0.0"); - fixture.Repository.Checkout("release-2.0.0"); - fixture.Repository.MakeCommits(4); - fixture.Repository.Checkout("master"); - fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); - fixture.Repository.Checkout("develop"); - fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); - - fixture.Repository.CreateBranch("release-1.0.0"); - fixture.Repository.Checkout("release-1.0.0"); - fixture.Repository.MakeCommits(4); - fixture.Repository.Checkout("master"); - fixture.Repository.MergeNoFF("release-1.0.0", Constants.SignatureNow()); - fixture.Repository.Checkout("develop"); - fixture.Repository.MergeNoFF("release-1.0.0", Constants.SignatureNow()); - - fixture.AssertFullSemver("2.0.0+11"); - } - } -} \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/MasterTests.cs b/GitVersionCore.Tests/IntegrationTests/MasterTests.cs similarity index 64% rename from GitVersionCore.Tests/IntegrationTests/GitHubFlow/MasterTests.cs rename to GitVersionCore.Tests/IntegrationTests/MasterTests.cs index 29337f7004..f7d25c5058 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/MasterTests.cs +++ b/GitVersionCore.Tests/IntegrationTests/MasterTests.cs @@ -1,8 +1,6 @@ -using System; -using GitVersion; +using GitVersion; using LibGit2Sharp; using NUnit.Framework; -using Shouldly; [TestFixture] public class MasterTests @@ -41,36 +39,6 @@ public void GivenARepositoryWithCommitsButNoTagsWithDetachedHead_VersionShouldBe } } - [Test] - public void GivenARepositoryWithNoTagsAndANextVersionTxtFile_VersionShouldMatchVersionTxtFile() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - const string ExpectedNextVersion = "1.0.0"; - fixture.Repository.MakeACommit(); - fixture.Repository.MakeACommit(); - fixture.Repository.MakeACommit(); - fixture.Repository.AddNextVersionTxtFile(ExpectedNextVersion); - - fixture.AssertFullSemver("1.0.0+2"); - } - } - - [Test] - public void GivenARepositoryWithTagAndANextVersionTxtFile_VersionShouldMatchVersionTxtFile() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - const string ExpectedNextVersion = "1.1.0"; - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); - fixture.Repository.MakeCommits(5); - fixture.Repository.AddNextVersionTxtFile(ExpectedNextVersion); - - fixture.AssertFullSemver("1.1.0+5"); - } - } - [Test] public void GivenARepositoryWithTagAndNextVersionInConfig_VersionShouldMatchVersionTxtFile() { @@ -85,26 +53,14 @@ public void GivenARepositoryWithTagAndNextVersionInConfig_VersionShouldMatchVers } } - [Test] - public void GivenARepositoryWithANextVersionTxtFileAndNextVersionInConfig_ErrorIsThrown() - { - using (var fixture = new EmptyRepositoryFixture(new Config { NextVersion = "1.1.0" })) - { - fixture.Repository.AddNextVersionTxtFile("1.1.0"); - - Should.Throw(() => fixture.AssertFullSemver("1.1.0+5")); - } - } - [Test] public void GivenARepositoryWithTagAndANextVersionTxtFileAndNoCommits_VersionShouldBeTag() { - using (var fixture = new EmptyRepositoryFixture(new Config())) + const string ExpectedNextVersion = "1.1.0"; + using (var fixture = new EmptyRepositoryFixture(new Config { NextVersion = ExpectedNextVersion })) { - const string ExpectedNextVersion = "1.1.0"; const string TaggedVersion = "1.0.3"; fixture.Repository.MakeATaggedCommit(TaggedVersion); - fixture.Repository.AddNextVersionTxtFile(ExpectedNextVersion); fixture.AssertFullSemver("1.0.3+0"); } @@ -135,21 +91,6 @@ public void GivenARepositoryWithTagAndNoNextVersionTxtFileAndNoCommits_VersionSh } } - [Test] - public void GivenARepositoryWithTagAndOldNextVersionTxtFile_VersionShouldBeTagWithBumpedPatch() - { - using (var fixture = new EmptyRepositoryFixture(new Config())) - { - const string NextVersionTxt = "1.0.0"; - const string TaggedVersion = "1.1.0"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); - fixture.Repository.MakeCommits(5); - fixture.Repository.AddNextVersionTxtFile(NextVersionTxt); - - fixture.AssertFullSemver("1.1.1+5"); - } - } - [Test] public void GivenARepositoryWithTagAndOldNextVersionConfig_VersionShouldBeTagWithBumpedPatch() { @@ -165,14 +106,13 @@ public void GivenARepositoryWithTagAndOldNextVersionConfig_VersionShouldBeTagWit } [Test] - public void GivenARepositoryWithTagAndOldNextVersionTxtFileAndNoCommits_VersionShouldBeTag() + public void GivenARepositoryWithTagAndOldNextVersionConfigAndNoCommits_VersionShouldBeTag() { - using (var fixture = new EmptyRepositoryFixture(new Config())) + const string NextVersionConfig = "1.0.0"; + using (var fixture = new EmptyRepositoryFixture(new Config { NextVersion = NextVersionConfig })) { - const string NextVersionTxt = "1.0.0"; const string TaggedVersion = "1.1.0"; fixture.Repository.MakeATaggedCommit(TaggedVersion); - fixture.Repository.AddNextVersionTxtFile(NextVersionTxt); fixture.AssertFullSemver("1.1.0+0"); } diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/MetaDataByCommitScenarios.cs b/GitVersionCore.Tests/IntegrationTests/MetaDataByCommitScenarios.cs similarity index 67% rename from GitVersionCore.Tests/IntegrationTests/GitFlow/MetaDataByCommitScenarios.cs rename to GitVersionCore.Tests/IntegrationTests/MetaDataByCommitScenarios.cs index 701bedd6a9..1bfe1b5191 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/MetaDataByCommitScenarios.cs +++ b/GitVersionCore.Tests/IntegrationTests/MetaDataByCommitScenarios.cs @@ -1,6 +1,4 @@ -using System; -using GitVersion; -using LibGit2Sharp; +using LibGit2Sharp; using NUnit.Framework; using Shouldly; @@ -79,89 +77,6 @@ public void CanCorrectlyDetectCommitCountsSemVer() } } - - /* - * hotfix-1.2.1 -----------C-- - * / \ - * master A----------------F-----H-------N - * \ / \ / - * hotfix-1.3.1 \ / ----L - * \ / \ - * release-1.3.0 \ -D----G--- \ - * \ / \ \ - * develop -----B----E-------I-----M--O--P - * \ / - * feature -------J-K- - * - * - * - A is tagged `1.2.0` - * - F is tagged `1.2.1` - * - H is tagged `1.3.0` - * - N is tagged `1.3.1` - */ - - [Test] - public void CanCorrectlyDetectCommitCountsAndReleaseDataWhenThatApplies() - { - using (var f = new CommitCountingRepoFixture()) - { - ResetToP(f.Repository); - EnsureBranchMatch(f, "develop"); - - ResetToO(f.Repository); - EnsureBranchMatch(f, "develop"); - - ResetToN(f.Repository); - EnsureBranchMatch(f, "master", r => (Commit)r.Tags["1.3.0"].Target); - - ResetToM(f.Repository); - EnsureBranchMatch(f, "develop"); - - ResetToL(f.Repository); - EnsureBranchMatch(f, "hotfix-1.3.1", r => (Commit)r.Tags["1.3.0"].Target); - - ResetToK(f.Repository); - EnsureBranchMatch(f, "feature"); - - ResetToJ(f.Repository); - EnsureBranchMatch(f, "feature"); - - ResetToI(f.Repository); - EnsureBranchMatch(f, "develop"); - - ResetToH(f.Repository); - EnsureBranchMatch(f, "master", r => (Commit)r.Tags["1.3.0"].Target); - - ResetToG(f.Repository); - EnsureBranchMatch(f, "release-1.3.0"); - - ResetToF(f.Repository); - EnsureBranchMatch(f, "master", r => (Commit)r.Tags["1.2.0"].Target); - - ResetToE(f.Repository); - EnsureBranchMatch(f, "develop"); - - ResetToD(f.Repository); - EnsureBranchMatch(f, "release-1.3.0"); - - ResetToC(f.Repository); - EnsureBranchMatch(f, "hotfix-1.2.1", r => (Commit)r.Tags["1.2.0"].Target); - - ResetToB(f.Repository); - EnsureBranchMatch(f, "develop"); - } - } - - static void EnsureBranchMatch(CommitCountingRepoFixture fixture, string branchName, Func commitFinder = null) - { - var referenceCommitFinder = commitFinder ?? (r => r.FindBranch(branchName).Tip); - - var commit = referenceCommitFinder(fixture.Repository); - var releaseDate = LastMinorVersionFinder.Execute(fixture.Repository, new Config(), commit); - releaseDate.ShouldBe(commit.When()); - } - - static void EnsureMetaDataMatch(CommitCountingRepoFixture fixture,string expectedSemVer) { var result = fixture.ExecuteGitVersion(); diff --git a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/OtherBranchTests.cs b/GitVersionCore.Tests/IntegrationTests/OtherBranchTests.cs similarity index 90% rename from GitVersionCore.Tests/IntegrationTests/GitHubFlow/OtherBranchTests.cs rename to GitVersionCore.Tests/IntegrationTests/OtherBranchTests.cs index 11b3893fea..1e3a545c29 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/OtherBranchTests.cs +++ b/GitVersionCore.Tests/IntegrationTests/OtherBranchTests.cs @@ -16,7 +16,7 @@ public void CanTakeVersionFromReleaseBranch() fixture.Repository.CreateBranch("alpha-2.0.0"); fixture.Repository.Checkout("alpha-2.0.0"); - fixture.AssertFullSemver("2.0.0-alpha.1+5"); + fixture.AssertFullSemver("2.0.0-alpha.1+0"); } } } \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/PatchScenarios.cs b/GitVersionCore.Tests/IntegrationTests/PatchScenarios.cs similarity index 67% rename from GitVersionCore.Tests/IntegrationTests/GitFlow/PatchScenarios.cs rename to GitVersionCore.Tests/IntegrationTests/PatchScenarios.cs index e17fc1e37f..ab9c7219c2 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/PatchScenarios.cs +++ b/GitVersionCore.Tests/IntegrationTests/PatchScenarios.cs @@ -1,5 +1,4 @@ using System.Linq; -using System.Threading; using LibGit2Sharp; using NUnit.Framework; @@ -27,24 +26,17 @@ public void PatchLatestReleaseExample() fixture.Repository.MergeNoFF("hotfix-1.2.1", Constants.SignatureNow()); - fixture.AssertFullSemver("1.2.1"); + fixture.AssertFullSemver("1.2.1+0"); fixture.Repository.ApplyTag("1.2.1"); - fixture.AssertFullSemver("1.2.1"); + fixture.AssertFullSemver("1.2.1+0"); // Verify develop version fixture.Repository.Checkout("develop"); - fixture.AssertFullSemver("1.3.0-unstable.0+0"); + fixture.AssertFullSemver("1.3.0-unstable.1+1"); - // Warning: Hack-ish hack - // - // Ensure the merge commit is done at a different time than the previous one - // Otherwise, as they would have the same content and signature, the same sha would be generated. - // Thus 'develop' and 'master' would point at the same exact commit and the Assert below would fail. - Thread.Sleep(1000); fixture.Repository.MergeNoFF("hotfix-1.2.1", Constants.SignatureNow()); - - fixture.AssertFullSemver("1.3.0-unstable.1+1"); + fixture.AssertFullSemver("1.3.0-unstable.1+0"); } } @@ -58,27 +50,27 @@ public void PatchOlderReleaseExample() r.MakeATaggedCommit("1.2.0"); })) { - + var targetCommit = ((Commit) fixture.Repository.Tags.Single(t => t.Name == "1.1.0").Target); // create hotfix branch - fixture.Repository.CreateBranch("hotfix-1.1.1", (Commit) fixture.Repository.Tags.Single(t => t.Name == "1.1.0").Target).Checkout(); + fixture.Repository.CreateBranch("hotfix-1.1.1", targetCommit).Checkout(); fixture.AssertFullSemver("1.1.1-beta.1+0"); fixture.Repository.MakeACommit(); fixture.AssertFullSemver("1.1.1-beta.1+1"); // Merge hotfix branch to support - fixture.Repository.CreateBranch("support-1.2", (Commit) fixture.Repository.Tags.Single(t => t.Name == "1.1.0").Target).Checkout(); - fixture.AssertFullSemver("1.1.0"); + fixture.Repository.CreateBranch("support-1.1", (Commit) fixture.Repository.Tags.Single(t => t.Name == "1.1.0").Target).Checkout(); + fixture.AssertFullSemver("1.1.0+0"); fixture.Repository.MergeNoFF("hotfix-1.1.1", Constants.SignatureNow()); - fixture.AssertFullSemver("1.1.1"); + fixture.AssertFullSemver("1.1.1+0"); fixture.Repository.ApplyTag("1.1.1"); - fixture.AssertFullSemver("1.1.1"); + fixture.AssertFullSemver("1.1.1+0"); // Verify develop version fixture.Repository.Checkout("develop"); - fixture.AssertFullSemver("1.3.0-unstable.0+0"); + fixture.AssertFullSemver("1.3.0-unstable.1+1"); } } } \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs b/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs new file mode 100644 index 0000000000..37fb557385 --- /dev/null +++ b/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs @@ -0,0 +1,98 @@ +using GitVersion; +using LibGit2Sharp; +using NUnit.Framework; + +[TestFixture] +public class PullRequestScenarios +{ + [Test] + public void CanCalculatePullRequestChanges() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("0.1.0"); + fixture.Repository.CreateBranch("feature/Foo").Checkout(); + fixture.Repository.MakeACommit(); + + fixture.Repository.Checkout("master"); + fixture.Repository.MergeNoFF("feature/Foo"); + fixture.Repository.CreateBranch("pull/2/merge").Checkout(); + fixture.Repository.Checkout("master"); + fixture.Repository.Reset(ResetMode.Hard, "HEAD~1"); + fixture.Repository.Checkout("pull/2/merge"); + + fixture.DumpGraph(); + fixture.AssertFullSemver("0.1.1-PullRequest.1+2"); + } + } + + [Test] + public void CanCalculatePullRequestChangesInheritingConfig() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("0.1.0"); + fixture.Repository.CreateBranch("develop").Checkout(); + fixture.Repository.MakeACommit(); + fixture.Repository.CreateBranch("feature/Foo").Checkout(); + fixture.Repository.MakeACommit(); + + fixture.Repository.Checkout("develop"); + fixture.Repository.MergeNoFF("feature/Foo"); + fixture.Repository.CreateBranch("pull/2/merge").Checkout(); + fixture.Repository.Checkout("develop"); + fixture.Repository.Reset(ResetMode.Hard, "HEAD~1"); + fixture.Repository.Checkout("pull/2/merge"); + + fixture.DumpGraph(); + fixture.AssertFullSemver("0.2.0-PullRequest.1+3"); + } + } + + [Test] + public void CanCalculatePullRequestChangesFromRemoteRepo() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("0.1.0"); + fixture.Repository.CreateBranch("feature/Foo").Checkout(); + fixture.Repository.MakeACommit(); + + fixture.Repository.Checkout("master"); + fixture.Repository.MergeNoFF("feature/Foo"); + fixture.Repository.CreateBranch("pull/2/merge").Checkout(); + fixture.Repository.Checkout("master"); + fixture.Repository.Reset(ResetMode.Hard, "HEAD~1"); + fixture.Repository.Checkout("pull/2/merge"); + // If we delete the branch, it is effectively the same as remote PR + fixture.Repository.Branches.Remove("feature/Foo"); + + fixture.DumpGraph(); + fixture.AssertFullSemver("0.1.1-PullRequest.1+2"); + } + } + + [Test] + public void CanCalculatePullRequestChangesInheritingConfigFromRemoteRepo() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("0.1.0"); + fixture.Repository.CreateBranch("develop").Checkout(); + fixture.Repository.MakeACommit(); + fixture.Repository.CreateBranch("feature/Foo").Checkout(); + fixture.Repository.MakeACommit(); + + fixture.Repository.Checkout("develop"); + fixture.Repository.MergeNoFF("feature/Foo"); + fixture.Repository.CreateBranch("pull/2/merge").Checkout(); + fixture.Repository.Checkout("develop"); + fixture.Repository.Reset(ResetMode.Hard, "HEAD~1"); + fixture.Repository.Checkout("pull/2/merge"); + // If we delete the branch, it is effectively the same as remote PR + fixture.Repository.Branches.Remove("feature/Foo"); + + fixture.AssertFullSemver("0.2.0-PullRequest.2+3"); + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/ReleaseBranchTests.cs b/GitVersionCore.Tests/IntegrationTests/ReleaseBranchTests.cs similarity index 51% rename from GitVersionCore.Tests/IntegrationTests/GitHubFlow/ReleaseBranchTests.cs rename to GitVersionCore.Tests/IntegrationTests/ReleaseBranchTests.cs index d6fe14854c..58d32c5dde 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/ReleaseBranchTests.cs +++ b/GitVersionCore.Tests/IntegrationTests/ReleaseBranchTests.cs @@ -3,7 +3,7 @@ using NUnit.Framework; [TestFixture] -public class ReleaseBranchTests +public class GitFlowReleaseBranchTests { [Test] public void CanTakeVersionFromReleaseBranch() @@ -15,26 +15,70 @@ public void CanTakeVersionFromReleaseBranch() fixture.Repository.CreateBranch("release-2.0.0"); fixture.Repository.Checkout("release-2.0.0"); - fixture.AssertFullSemver("2.0.0-beta.1+5"); + fixture.AssertFullSemver("2.0.0-beta.1+0"); + fixture.Repository.MakeCommits(2); + fixture.AssertFullSemver("2.0.0-beta.1+2"); } } [Test] public void CanTakeVersionFromReleaseBranchWithTagOverriden() { - using (var fixture = new EmptyRepositoryFixture(new Config { ReleaseBranchTag = "rc" })) + var config = new Config(); + config.Branches["release[/-]"].Tag = "rc"; + using (var fixture = new EmptyRepositoryFixture(config)) { fixture.Repository.MakeATaggedCommit("1.0.3"); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Repository.Checkout("release-2.0.0"); - fixture.AssertFullSemver("2.0.0-rc.1+5"); + fixture.AssertFullSemver("2.0.0-rc.1+0"); + fixture.Repository.MakeCommits(2); + fixture.AssertFullSemver("2.0.0-rc.1+2"); } } [Test] - public void WhenReleaseBranchIsMergedIntoMasterVersionIsTakenWithIt() + public void CanHandleReleaseBranchWithStability() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("1.0.3"); + fixture.Repository.CreateBranch("develop"); + fixture.Repository.MakeCommits(5); + fixture.Repository.CreateBranch("release-2.0.0-Final"); + fixture.Repository.Checkout("release-2.0.0-Final"); + + fixture.AssertFullSemver("2.0.0-beta.1+0"); + fixture.Repository.MakeCommits(2); + fixture.AssertFullSemver("2.0.0-beta.1+2"); + } + } + + [Test] + public void WhenReleaseBranch_OffDevelop_IsMergedIntoMasterAndDevelop_VersionIsTakenWithIt() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("1.0.3"); + fixture.Repository.CreateBranch("develop"); + fixture.Repository.MakeCommits(1); + + fixture.Repository.CreateBranch("release-2.0.0"); + fixture.Repository.Checkout("release-2.0.0"); + fixture.Repository.MakeCommits(4); + fixture.Repository.Checkout("master"); + fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); + + fixture.AssertFullSemver("2.0.0+0"); + fixture.Repository.MakeCommits(2); + fixture.AssertFullSemver("2.0.0+2"); + } + } + + [Test] + public void WhenReleaseBranch_OffMaster_IsMergedIntoMaster_VersionIsTakenWithIt() { using (var fixture = new EmptyRepositoryFixture(new Config())) { @@ -46,9 +90,35 @@ public void WhenReleaseBranchIsMergedIntoMasterVersionIsTakenWithIt() fixture.Repository.Checkout("master"); fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); - fixture.AssertFullSemver("2.0.0+6"); + fixture.AssertFullSemver("2.0.0+0"); + } + } + + [Test] + public void WhenReleaseBranchIsMergedIntoDevelopHighestVersionIsTakenWithIt() + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.MakeATaggedCommit("1.0.3"); + fixture.Repository.CreateBranch("develop"); + fixture.Repository.MakeCommits(1); + + fixture.Repository.CreateBranch("release-2.0.0"); + fixture.Repository.Checkout("release-2.0.0"); + fixture.Repository.MakeCommits(4); + fixture.Repository.Checkout("develop"); + fixture.Repository.MergeNoFF("release-2.0.0", Constants.SignatureNow()); + + fixture.Repository.CreateBranch("release-1.0.0"); + fixture.Repository.Checkout("release-1.0.0"); + fixture.Repository.MakeCommits(4); + fixture.Repository.Checkout("develop"); + fixture.Repository.MergeNoFF("release-1.0.0", Constants.SignatureNow()); + + fixture.AssertFullSemver("2.1.0-unstable.1+5"); } } + [Test] public void WhenReleaseBranchIsMergedIntoMasterHighestVersionIsTakenWithIt() { @@ -69,7 +139,7 @@ public void WhenReleaseBranchIsMergedIntoMasterHighestVersionIsTakenWithIt() fixture.Repository.Checkout("master"); fixture.Repository.MergeNoFF("release-1.0.0", Constants.SignatureNow()); - fixture.AssertFullSemver("2.0.0+11"); + fixture.AssertFullSemver("2.0.0+5"); } } @@ -96,7 +166,7 @@ public void WhenMergingReleaseBackToDevShouldNotResetBetaVersion() fixture.Repository.MakeCommits(1); - fixture.AssertFullSemver("2.0.0-beta.2+0"); + fixture.AssertFullSemver("2.0.0-beta.2+2"); //merge down to develop fixture.Repository.Checkout("develop"); @@ -105,7 +175,7 @@ public void WhenMergingReleaseBackToDevShouldNotResetBetaVersion() //but keep working on the release fixture.Repository.Checkout("release-2.0.0"); - fixture.AssertFullSemver("2.0.0-beta.2+0"); + fixture.AssertFullSemver("2.0.0-beta.2+3"); } } } \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/GitHubFlowSupportBranchScenarios.cs b/GitVersionCore.Tests/IntegrationTests/SupportBranchScenarios.cs similarity index 91% rename from GitVersionCore.Tests/IntegrationTests/GitHubFlow/GitHubFlowSupportBranchScenarios.cs rename to GitVersionCore.Tests/IntegrationTests/SupportBranchScenarios.cs index 96ad48d0a9..af8fab6f65 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitHubFlow/GitHubFlowSupportBranchScenarios.cs +++ b/GitVersionCore.Tests/IntegrationTests/SupportBranchScenarios.cs @@ -3,7 +3,7 @@ using NUnit.Framework; [TestFixture] -public class GitHubFlowSupportBranchScenarios +public class SupportBranchScenarios { [Test] public void SupportIsCalculatedCorrectly() @@ -37,16 +37,16 @@ public void SupportIsCalculatedCorrectly() // Create 1.2.0 release fixture.Repository.Checkout("support/1.0.0"); fixture.Repository.MergeNoFF("release/1.2.0"); - fixture.AssertFullSemver("1.2.0+2"); + fixture.AssertFullSemver("1.2.0+0"); fixture.Repository.ApplyTag("1.2.0"); // Create 1.2.1 hotfix fixture.Repository.CreateBranch("hotfix/1.2.1").Checkout(); fixture.Repository.MakeACommit(); - fixture.AssertFullSemver("1.2.1+1"); + fixture.AssertFullSemver("1.2.1-beta.1+1"); fixture.Repository.Checkout("support/1.0.0"); fixture.Repository.MergeNoFF("hotfix/1.2.1"); - fixture.AssertFullSemver("1.2.1+2"); + fixture.AssertFullSemver("1.2.1+0"); } } @@ -69,7 +69,7 @@ public void WhenSupportIsBranchedAndTaggedFromAnotherSupportEnsureNewMinorIsUsed fixture.Repository.MakeACommit(); fixture.Repository.MakeACommit(); - fixture.AssertFullSemver("1.3.1+2"); + fixture.AssertFullSemver("1.3.0+2"); } } } \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/SwitchingToGitFlowScenarios.cs b/GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs similarity index 90% rename from GitVersionCore.Tests/IntegrationTests/GitFlow/SwitchingToGitFlowScenarios.cs rename to GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs index 6db460f55f..b7f827d8ce 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/SwitchingToGitFlowScenarios.cs +++ b/GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs @@ -14,7 +14,7 @@ public void WhenDevelopBranchedFromMasterWithLegacyVersionTags_DevelopCanUseReac fixture.Repository.MakeATaggedCommit("1.0.0.0"); fixture.Repository.MakeCommits(2); fixture.Repository.CreateBranch("develop").Checkout(); - fixture.AssertFullSemver("1.1.0-unstable.0+0"); + fixture.AssertFullSemver("1.1.0-unstable.1+2"); } } } \ No newline at end of file diff --git a/GitVersionCore.Tests/IntegrationTests/GitFlow/WikiScenarios.cs b/GitVersionCore.Tests/IntegrationTests/WikiScenarios.cs similarity index 97% rename from GitVersionCore.Tests/IntegrationTests/GitFlow/WikiScenarios.cs rename to GitVersionCore.Tests/IntegrationTests/WikiScenarios.cs index 2e27189f61..e4ce05549a 100644 --- a/GitVersionCore.Tests/IntegrationTests/GitFlow/WikiScenarios.cs +++ b/GitVersionCore.Tests/IntegrationTests/WikiScenarios.cs @@ -44,7 +44,8 @@ public void MinorReleaseExample() // Branch to develop fixture.Repository.CreateBranch("develop").Checkout(); - fixture.AssertFullSemver("1.3.0-unstable.0+0"); + fixture.Repository.MakeACommit(); + fixture.AssertFullSemver("1.3.0-unstable.1+1"); // Open Pull Request fixture.Repository.CreateBranch("pull/2/merge").Checkout(); diff --git a/GitVersionCore.Tests/JsonVersionBuilderTests.Json.approved.txt b/GitVersionCore.Tests/JsonVersionBuilderTests.Json.approved.txt index d8f088b481..9ec84519fc 100644 --- a/GitVersionCore.Tests/JsonVersionBuilderTests.Json.approved.txt +++ b/GitVersionCore.Tests/JsonVersionBuilderTests.Json.approved.txt @@ -11,11 +11,8 @@ "LegacySemVer":"1.2.3-unstable4", "LegacySemVerPadded":"1.2.3-unstable0004", "AssemblySemVer":"1.2.3.0", - "AssemblyFileSemVer":"1.2.3.0", "FullSemVer":"1.2.3-unstable.4+5", "InformationalVersion":"1.2.3-unstable.4+5.Branch.feature1.Sha.commitSha", - "ClassicVersion":"1.2.3.5", - "ClassicVersionWithTag":"1.2.3.5-unstable.4", "BranchName":"feature1", "Sha":"commitSha", "NuGetVersionV2":"1.2.3-unstable0004", diff --git a/GitVersionCore.Tests/JsonVersionBuilderTests.cs b/GitVersionCore.Tests/JsonVersionBuilderTests.cs index cc25171a9d..986a1c34a1 100644 --- a/GitVersionCore.Tests/JsonVersionBuilderTests.cs +++ b/GitVersionCore.Tests/JsonVersionBuilderTests.cs @@ -17,7 +17,7 @@ public void Json() PreReleaseTag = "unstable4", BuildMetaData = new SemanticVersionBuildMetaData(5, "feature1", "commitSha",DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; - var variables = VariableProvider.GetVariablesFor(semanticVersion, new Config()); + var variables = VariableProvider.GetVariablesFor(semanticVersion, AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDelivery); var json = JsonOutputFormatter.ToJson(variables); Approvals.Verify(json); } diff --git a/GitVersionTask.Tests/Mocks/MockBranch.cs b/GitVersionCore.Tests/Mocks/MockBranch.cs similarity index 79% rename from GitVersionTask.Tests/Mocks/MockBranch.cs rename to GitVersionCore.Tests/Mocks/MockBranch.cs index 7da19da4bc..11d08e158b 100644 --- a/GitVersionTask.Tests/Mocks/MockBranch.cs +++ b/GitVersionCore.Tests/Mocks/MockBranch.cs @@ -18,7 +18,7 @@ public MockBranch(string name, string canonicalName) public MockBranch() { - + } MockCommitLog commits = new MockCommitLog(); string name; @@ -26,11 +26,23 @@ public MockBranch() public override string Name { get { return name; } } public override ICommitLog Commits { get { return commits; } } public override Commit Tip { get { return commits.First(); } } + public override bool IsTracking { get { return true; } } + public override string CanonicalName { get { return canonicalName; } } + public override int GetHashCode() + { + return name.GetHashCode(); + } + + public override bool Equals(object obj) + { + return ReferenceEquals(this, obj); + } + public IEnumerator GetEnumerator() { return commits.GetEnumerator(); @@ -66,7 +78,7 @@ public bool Remove(Commit item) return commits.Remove(item); } - public int Count{get{return commits.Count;}} + public int Count { get { return commits.Count; } } - public bool IsReadOnly { get{return false;} } + public bool IsReadOnly { get { return false; } } } \ No newline at end of file diff --git a/GitVersionTask.Tests/Mocks/MockBranchCollection.cs b/GitVersionCore.Tests/Mocks/MockBranchCollection.cs similarity index 82% rename from GitVersionTask.Tests/Mocks/MockBranchCollection.cs rename to GitVersionCore.Tests/Mocks/MockBranchCollection.cs index 69491569b2..a9ae6df7fd 100644 --- a/GitVersionTask.Tests/Mocks/MockBranchCollection.cs +++ b/GitVersionCore.Tests/Mocks/MockBranchCollection.cs @@ -13,7 +13,7 @@ public override IEnumerator GetEnumerator() public override Branch this[string name] { - get { return Branches.FirstOrDefault(x=>x.Name ==name); } + get { return Branches.FirstOrDefault(x => x.Name == name); } } public void Add(Branch item) @@ -40,16 +40,17 @@ public override void Remove(Branch item) { Branches.Remove(item); } - bool ICollection.Remove(Branch item) + bool ICollection.Remove(Branch item) { return Branches.Remove(item); } public int Count { - get { + get + { return Branches.Count; } } - public bool IsReadOnly { get{return false;}} + public bool IsReadOnly { get { return false; } } } \ No newline at end of file diff --git a/GitVersionTask.Tests/Mocks/MockCommit.cs b/GitVersionCore.Tests/Mocks/MockCommit.cs similarity index 57% rename from GitVersionTask.Tests/Mocks/MockCommit.cs rename to GitVersionCore.Tests/Mocks/MockCommit.cs index 7b99b27034..a180cac7f7 100644 --- a/GitVersionTask.Tests/Mocks/MockCommit.cs +++ b/GitVersionCore.Tests/Mocks/MockCommit.cs @@ -4,24 +4,29 @@ using LibGit2Sharp; [DebuggerDisplay("{DebuggerDisplay}")] -public class MockCommit:Commit +public class MockCommit : Commit { + static int commitCount = 1; + static DateTimeOffset when = DateTimeOffset.Now; + public MockCommit(ObjectId id = null) { - idEx = id ?? new ObjectId(Guid.NewGuid().ToString().Replace("-", "")+ "00000000"); - MessageEx = ""; + idEx = id ?? new ObjectId(Guid.NewGuid().ToString().Replace("-", "") + "00000000"); + MessageEx = "Commit " + commitCount++; ParentsEx = new List { null }; - CommitterEx = new Signature("Joe", "Joe@bloggs.net", DateTimeOffset.Now); + CommitterEx = new Signature("Joe", "Joe@bloggs.net", when); + // Make sure each commit is a different time + when = when.AddSeconds(1); } public string MessageEx; - public override string Message{get { return MessageEx; }} + public override string Message { get { return MessageEx; } } public Signature CommitterEx; - public override Signature Committer{get { return CommitterEx; }} + public override Signature Committer { get { return CommitterEx; } } ObjectId idEx; - public override ObjectId Id{get { return idEx; }} + public override ObjectId Id { get { return idEx; } } public override string Sha { get { return idEx.Sha; } } @@ -39,4 +44,4 @@ string DebuggerDisplay return MessageEx; } } -} +} \ No newline at end of file diff --git a/GitVersionTask.Tests/Mocks/MockCommitLog.cs b/GitVersionCore.Tests/Mocks/MockCommitLog.cs similarity index 73% rename from GitVersionTask.Tests/Mocks/MockCommitLog.cs rename to GitVersionCore.Tests/Mocks/MockCommitLog.cs index 8b97484126..a5e3f1d803 100644 --- a/GitVersionTask.Tests/Mocks/MockCommitLog.cs +++ b/GitVersionCore.Tests/Mocks/MockCommitLog.cs @@ -1,14 +1,18 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using LibGit2Sharp; -public class MockCommitLog:ICommitLog,ICollection +public class MockCommitLog : ICommitLog, ICollection { public List Commits = new List(); public IEnumerator GetEnumerator() { - return Commits.GetEnumerator(); + if (SortedBy == CommitSortStrategies.Reverse) + return Commits.GetEnumerator(); + + return Enumerable.Reverse(Commits).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() @@ -26,7 +30,7 @@ public void Clear() { Commits.Clear(); } - + public bool Contains(Commit item) { @@ -44,6 +48,8 @@ public bool Remove(Commit item) } public int Count { get { return Commits.Count; } } - public bool IsReadOnly {get { return false; } + public bool IsReadOnly + { + get { return false; } } } \ No newline at end of file diff --git a/GitVersionTask.Tests/Mocks/MockMergeCommit.cs b/GitVersionCore.Tests/Mocks/MockMergeCommit.cs similarity index 98% rename from GitVersionTask.Tests/Mocks/MockMergeCommit.cs rename to GitVersionCore.Tests/Mocks/MockMergeCommit.cs index 558a821f49..472fbd10bf 100644 --- a/GitVersionTask.Tests/Mocks/MockMergeCommit.cs +++ b/GitVersionCore.Tests/Mocks/MockMergeCommit.cs @@ -6,4 +6,4 @@ public MockMergeCommit(ObjectId id = null) : base(id) { ParentsEx.Add(null); } -} +} \ No newline at end of file diff --git a/GitVersionCore.Tests/Mocks/MockQueryableCommitLog.cs b/GitVersionCore.Tests/Mocks/MockQueryableCommitLog.cs new file mode 100644 index 0000000000..e1120b8f5d --- /dev/null +++ b/GitVersionCore.Tests/Mocks/MockQueryableCommitLog.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using LibGit2Sharp; + +public class MockQueryableCommitLog : IQueryableCommitLog +{ + readonly ICommitLog commits; + + public MockQueryableCommitLog(ICommitLog commits) + { + this.commits = commits; + } + + public IEnumerator GetEnumerator() + { + return commits.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public CommitSortStrategies SortedBy + { + get { throw new NotImplementedException(); } + } + + public ICommitLog QueryBy(CommitFilter filter) + { + throw new NotImplementedException(); + } + + public Commit FindMergeBase(Commit first, Commit second) + { + throw new NotImplementedException(); + } + + public Commit FindMergeBase(IEnumerable commits, MergeBaseFindingStrategy strategy) + { + throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/GitVersionTask.Tests/Mocks/MockReferenceCollection.cs b/GitVersionCore.Tests/Mocks/MockReferenceCollection.cs similarity index 93% rename from GitVersionTask.Tests/Mocks/MockReferenceCollection.cs rename to GitVersionCore.Tests/Mocks/MockReferenceCollection.cs index c839d9bee7..5c51ba26f7 100644 --- a/GitVersionTask.Tests/Mocks/MockReferenceCollection.cs +++ b/GitVersionCore.Tests/Mocks/MockReferenceCollection.cs @@ -8,9 +8,9 @@ public class MockReferenceCollection : ReferenceCollection, ICollection public override ReflogCollection Log(string canonicalName) { return new MockReflogCollection - { - Commits = Commits - }; + { + Commits = Commits + }; } public List Commits = new List(); diff --git a/GitVersionTask.Tests/Mocks/MockReflogCollection.cs b/GitVersionCore.Tests/Mocks/MockReflogCollection.cs similarity index 100% rename from GitVersionTask.Tests/Mocks/MockReflogCollection.cs rename to GitVersionCore.Tests/Mocks/MockReflogCollection.cs diff --git a/GitVersionTask.Tests/Mocks/MockRepository.cs b/GitVersionCore.Tests/Mocks/MockRepository.cs similarity index 96% rename from GitVersionTask.Tests/Mocks/MockRepository.cs rename to GitVersionCore.Tests/Mocks/MockRepository.cs index f0af69a7f7..bffceb33b5 100644 --- a/GitVersionTask.Tests/Mocks/MockRepository.cs +++ b/GitVersionCore.Tests/Mocks/MockRepository.cs @@ -4,6 +4,8 @@ public class MockRepository : IRepository { + IQueryableCommitLog commits; + public MockRepository() { Tags = new MockTagCollection(); @@ -166,7 +168,13 @@ public RepositoryStatus RetrieveStatus(StatusOptions options) public Configuration Config { get; set; } public Index Index { get; set; } public ReferenceCollection Refs { get; set; } - public IQueryableCommitLog Commits { get; set; } + + public IQueryableCommitLog Commits + { + get { return commits ?? new MockQueryableCommitLog(Head.Commits); } + set { commits = value; } + } + public BranchCollection Branches { get; set; } public TagCollection Tags { get; set; } public RepositoryInformation Info { get; set; } diff --git a/GitVersionTask.Tests/Mocks/MockTag.cs b/GitVersionCore.Tests/Mocks/MockTag.cs similarity index 69% rename from GitVersionTask.Tests/Mocks/MockTag.cs rename to GitVersionCore.Tests/Mocks/MockTag.cs index 5f53d2901e..5400fb5ee0 100644 --- a/GitVersionTask.Tests/Mocks/MockTag.cs +++ b/GitVersionCore.Tests/Mocks/MockTag.cs @@ -1,6 +1,6 @@ using LibGit2Sharp; -public class MockTag:Tag +public class MockTag : Tag { public string NameEx; @@ -15,6 +15,15 @@ public override GitObject Target get { return TargetEx; } } public TagAnnotation AnnotationEx; + + public MockTag() { } + + public MockTag(string name, Commit target) + { + NameEx = name; + TargetEx = target; + } + public override TagAnnotation Annotation { get { return AnnotationEx; } diff --git a/GitVersionTask.Tests/Mocks/MockTagAnnotation.cs b/GitVersionCore.Tests/Mocks/MockTagAnnotation.cs similarity index 84% rename from GitVersionTask.Tests/Mocks/MockTagAnnotation.cs rename to GitVersionCore.Tests/Mocks/MockTagAnnotation.cs index 6d158b9537..8d14af5d64 100644 --- a/GitVersionTask.Tests/Mocks/MockTagAnnotation.cs +++ b/GitVersionCore.Tests/Mocks/MockTagAnnotation.cs @@ -1,6 +1,6 @@ using LibGit2Sharp; -public class MockTagAnnotation:TagAnnotation +public class MockTagAnnotation : TagAnnotation { public Signature TaggerEx; diff --git a/GitVersionTask.Tests/Mocks/MockTagCollection.cs b/GitVersionCore.Tests/Mocks/MockTagCollection.cs similarity index 93% rename from GitVersionTask.Tests/Mocks/MockTagCollection.cs rename to GitVersionCore.Tests/Mocks/MockTagCollection.cs index 6223f12485..05f4724d7f 100644 --- a/GitVersionTask.Tests/Mocks/MockTagCollection.cs +++ b/GitVersionCore.Tests/Mocks/MockTagCollection.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using LibGit2Sharp; -public class MockTagCollection : TagCollection,ICollection +public class MockTagCollection : TagCollection, ICollection { public List Tags = new List(); diff --git a/GitVersionTask.Tests/Mocks/SignatureBuilder.cs b/GitVersionCore.Tests/Mocks/SignatureBuilder.cs similarity index 100% rename from GitVersionTask.Tests/Mocks/SignatureBuilder.cs rename to GitVersionCore.Tests/Mocks/SignatureBuilder.cs diff --git a/GitVersionCore.Tests/TestEffectiveConfiguration.cs b/GitVersionCore.Tests/TestEffectiveConfiguration.cs new file mode 100644 index 0000000000..a1470e8ac8 --- /dev/null +++ b/GitVersionCore.Tests/TestEffectiveConfiguration.cs @@ -0,0 +1,19 @@ +namespace GitVersionCore.Tests +{ + using GitVersion; + + public class TestEffectiveConfiguration : EffectiveConfiguration + { + public TestEffectiveConfiguration( + AssemblyVersioningScheme assemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch, + VersioningMode versioningMode = VersioningMode.ContinuousDelivery, + string gitTagPrefix = "v", + string tag = "", + string nextVersion = null, + string branchPrefixToTrim = "", + bool preventIncrementForMergedBranchVersion = false) : + base(assemblyVersioningScheme, versioningMode, gitTagPrefix, tag, nextVersion, IncrementStrategy.Patch, branchPrefixToTrim, preventIncrementForMergedBranchVersion) + { + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeliveryModeForPreRelease.approved.txt b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeliveryModeForPreRelease.approved.txt new file mode 100644 index 0000000000..449cbb36c0 --- /dev/null +++ b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeliveryModeForPreRelease.approved.txt @@ -0,0 +1,20 @@ +{ + "Major":1, + "Minor":2, + "Patch":3, + "PreReleaseTag":"unstable.4", + "PreReleaseTagWithDash":"-unstable.4", + "BuildMetaData":5, + "FullBuildMetaData":"5.Branch.develop.Sha.commitSha", + "MajorMinorPatch":"1.2.3", + "SemVer":"1.2.3-unstable.4", + "LegacySemVer":"1.2.3-unstable4", + "LegacySemVerPadded":"1.2.3-unstable0004", + "AssemblySemVer":"1.2.3.0", + "FullSemVer":"1.2.3-unstable.4+5", + "InformationalVersion":"1.2.3-unstable.4+5.Branch.develop.Sha.commitSha", + "BranchName":"develop", + "Sha":"commitSha", + "NuGetVersionV2":"1.2.3-unstable0004", + "NuGetVersion":"1.2.3-unstable0004" +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeliveryModeForStable.approved.txt b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeliveryModeForStable.approved.txt new file mode 100644 index 0000000000..a3f8e75125 --- /dev/null +++ b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeliveryModeForStable.approved.txt @@ -0,0 +1,20 @@ +{ + "Major":1, + "Minor":2, + "Patch":3, + "PreReleaseTag":"", + "PreReleaseTagWithDash":"", + "BuildMetaData":5, + "FullBuildMetaData":"5.Branch.develop.Sha.commitSha", + "MajorMinorPatch":"1.2.3", + "SemVer":"1.2.3", + "LegacySemVer":"1.2.3", + "LegacySemVerPadded":"1.2.3", + "AssemblySemVer":"1.2.3.0", + "FullSemVer":"1.2.3+5", + "InformationalVersion":"1.2.3+5.Branch.develop.Sha.commitSha", + "BranchName":"develop", + "Sha":"commitSha", + "NuGetVersionV2":"1.2.3", + "NuGetVersion":"1.2.3" +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeploymentModeForPreRelease.approved.txt b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeploymentModeForPreRelease.approved.txt new file mode 100644 index 0000000000..28ca6e078c --- /dev/null +++ b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeploymentModeForPreRelease.approved.txt @@ -0,0 +1,20 @@ +{ + "Major":1, + "Minor":2, + "Patch":3, + "PreReleaseTag":"unstable.5", + "PreReleaseTagWithDash":"-unstable.5", + "BuildMetaData":5, + "FullBuildMetaData":"5.Branch.develop.Sha.commitSha", + "MajorMinorPatch":"1.2.3", + "SemVer":"1.2.3-unstable.5", + "LegacySemVer":"1.2.3-unstable5", + "LegacySemVerPadded":"1.2.3-unstable0005", + "AssemblySemVer":"1.2.3.0", + "FullSemVer":"1.2.3-unstable.5+4", + "InformationalVersion":"1.2.3-unstable.5+4.Branch.develop.Sha.commitSha", + "BranchName":"develop", + "Sha":"commitSha", + "NuGetVersionV2":"1.2.3-unstable0005", + "NuGetVersion":"1.2.3-unstable0005" +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeploymentModeForStable.approved.txt b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeploymentModeForStable.approved.txt new file mode 100644 index 0000000000..b737fad5fc --- /dev/null +++ b/GitVersionCore.Tests/VariableProviderTests.ProvidesVariablesInContinuousDeploymentModeForStable.approved.txt @@ -0,0 +1,20 @@ +{ + "Major":1, + "Minor":2, + "Patch":3, + "PreReleaseTag":"", + "PreReleaseTagWithDash":"", + "BuildMetaData":5, + "FullBuildMetaData":"5.Branch.develop.Sha.commitSha", + "MajorMinorPatch":"1.2.3", + "SemVer":"1.2.3.5", + "LegacySemVer":"1.2.3.5", + "LegacySemVerPadded":"1.2.3.5", + "AssemblySemVer":"1.2.3.0", + "FullSemVer":"1.2.3.5", + "InformationalVersion":"1.2.3.5+Branch.develop.Sha.commitSha", + "BranchName":"develop", + "Sha":"commitSha", + "NuGetVersionV2":"1.2.3.5", + "NuGetVersion":"1.2.3.5" +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VariableProviderTests.cs b/GitVersionCore.Tests/VariableProviderTests.cs index 353bbe0950..3f64d2fc00 100644 --- a/GitVersionCore.Tests/VariableProviderTests.cs +++ b/GitVersionCore.Tests/VariableProviderTests.cs @@ -1,13 +1,13 @@ using System; +using ApprovalTests; using GitVersion; using NUnit.Framework; -using Shouldly; [TestFixture] public class VariableProviderTests { [Test] - public void DevelopBranchFormatsSemVerForCiFeed() + public void ProvidesVariablesInContinuousDeliveryModeForPreRelease() { var semVer = new SemanticVersion { @@ -21,10 +21,66 @@ public void DevelopBranchFormatsSemVerForCiFeed() semVer.BuildMetaData.Sha = "commitSha"; semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); + var vars = VariableProvider.GetVariablesFor(semVer, AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDelivery); - var vars = VariableProvider.GetVariablesFor(semVer, new Config()); + Approvals.Verify(JsonOutputFormatter.ToJson(vars)); + } + + [Test] + public void ProvidesVariablesInContinuousDeploymentModeForPreRelease() + { + var semVer = new SemanticVersion + { + Major = 1, + Minor = 2, + Patch = 3, + PreReleaseTag = "unstable.4", + BuildMetaData = "5.Branch.develop" + }; - vars[VariableProvider.SemVer].ShouldBe("1.2.3.5-unstable"); + semVer.BuildMetaData.Sha = "commitSha"; + semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); + + var vars = VariableProvider.GetVariablesFor(semVer, AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDeployment); + + Approvals.Verify(JsonOutputFormatter.ToJson(vars)); } + [Test] + public void ProvidesVariablesInContinuousDeliveryModeForStable() + { + var semVer = new SemanticVersion + { + Major = 1, + Minor = 2, + Patch = 3, + BuildMetaData = "5.Branch.develop" + }; + + semVer.BuildMetaData.Sha = "commitSha"; + semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); + + var vars = VariableProvider.GetVariablesFor(semVer, AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDelivery); + + Approvals.Verify(JsonOutputFormatter.ToJson(vars)); + } + + [Test] + public void ProvidesVariablesInContinuousDeploymentModeForStable() + { + var semVer = new SemanticVersion + { + Major = 1, + Minor = 2, + Patch = 3, + BuildMetaData = "5.Branch.develop" + }; + + semVer.BuildMetaData.Sha = "commitSha"; + semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); + + var vars = VariableProvider.GetVariablesFor(semVer, AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDeployment); + + Approvals.Verify(JsonOutputFormatter.ToJson(vars)); + } } \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs new file mode 100644 index 0000000000..98fd552532 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -0,0 +1,86 @@ +namespace GitVersionCore.Tests.VersionCalculation +{ + using System; + using GitVersion; + using GitVersion.VersionCalculation; + using GitVersion.VersionCalculation.BaseVersionCalculators; + using LibGit2Sharp; + using NUnit.Framework; + using Shouldly; + + [TestFixture] + public class BaseVersionCalculatorTests + { + [Test] + public void ChoosesHighestVersionReturnedFromStrategies() + { + var context = new GitVersionContextBuilder().Build(); + var dateTimeOffset = DateTimeOffset.Now; + var sut = new BaseVersionCalculator(new V1Strategy(DateTimeOffset.Now), new V2Strategy(dateTimeOffset)); + + var baseVersion = sut.GetBaseVersion(context); + + baseVersion.SemanticVersion.ToString().ShouldBe("2.0.0"); + baseVersion.ShouldIncrement.ShouldBe(true); + baseVersion.BaseVersionSource.When().ShouldBe(dateTimeOffset); + } + + [Test] + public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhen() + { + var context = new GitVersionContextBuilder().Build(); + var when = DateTimeOffset.Now; + var sut = new BaseVersionCalculator(new V1Strategy(when), new V2Strategy(null)); + + var baseVersion = sut.GetBaseVersion(context); + + baseVersion.SemanticVersion.ToString().ShouldBe("2.0.0"); + baseVersion.ShouldIncrement.ShouldBe(true); + baseVersion.BaseVersionSource.When().ShouldBe(when); + } + + [Test] + public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() + { + var context = new GitVersionContextBuilder().Build(); + var when = DateTimeOffset.Now; + var sut = new BaseVersionCalculator(new V1Strategy(null), new V2Strategy(when)); + + var baseVersion = sut.GetBaseVersion(context); + + baseVersion.SemanticVersion.ToString().ShouldBe("2.0.0"); + baseVersion.ShouldIncrement.ShouldBe(true); + baseVersion.BaseVersionSource.When().ShouldBe(when); + } + + class V1Strategy : BaseVersionStrategy + { + readonly Commit when; + + public V1Strategy(DateTimeOffset? when) + { + this.when = when == null ? null : new MockCommit { CommitterEx = when.Value.ToSignature() }; + } + + public override BaseVersion GetVersion(GitVersionContext context) + { + return new BaseVersion("Source 1", false, true, new SemanticVersion(1), when, null); + } + } + + class V2Strategy : BaseVersionStrategy + { + Commit when; + + public V2Strategy(DateTimeOffset? when) + { + this.when = when == null ? null : new MockCommit { CommitterEx = when.Value.ToSignature() }; + } + + public override BaseVersion GetVersion(GitVersionContext context) + { + return new BaseVersion("Source 2", true, true, new SemanticVersion(2), when, null); + } + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/NewNextVersionCalculatorTests.cs b/GitVersionCore.Tests/VersionCalculation/NewNextVersionCalculatorTests.cs new file mode 100644 index 0000000000..8fda45ef48 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/NewNextVersionCalculatorTests.cs @@ -0,0 +1,91 @@ +namespace GitVersionCore.Tests.VersionCalculation +{ + using System; + using GitVersion; + using GitVersion.VersionCalculation; + using NUnit.Framework; + using Shouldly; + + public class NewNextVersionCalculatorTests + { + [Test] + public void ShouldIncrementVersionBasedOnConfig() + { + var baseCalculator = new TestBaseVersionCalculator(true, true, new SemanticVersion(1), new MockCommit()); + var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(1, "master", "b1a34e", DateTimeOffset.Now); + var sut = new NewNextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var config = new Config(); + var context = new GitVersionContextBuilder().WithConfig(config).Build(); + + var version = sut.FindVersion(context); + + version.ToString().ShouldBe("1.0.1"); + } + + [Test] + public void DoesNotIncrementWhenBaseVersionSaysNotTo() + { + var baseCalculator = new TestBaseVersionCalculator(false, true, new SemanticVersion(1), new MockCommit()); + var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(1, "master", "b1a34e", DateTimeOffset.Now); + var sut = new NewNextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var config = new Config(); + var context = new GitVersionContextBuilder().WithConfig(config).Build(); + + var version = sut.FindVersion(context); + + version.ToString().ShouldBe("1.0.0"); + } + + [Test] + public void AppliesBranchPreReleaseTag() + { + var baseCalculator = new TestBaseVersionCalculator(false, true, new SemanticVersion(1), new MockCommit()); + var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(2, "develop", "b1a34e", DateTimeOffset.Now); + var sut = new NewNextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var context = new GitVersionContextBuilder() + .WithDevelopBranch() + .Build(); + + var version = sut.FindVersion(context); + + version.ToString("f").ShouldBe("1.0.0-unstable.1+2"); + } + + [Test] + public void DoesNotApplyPreReleaseTagWhenBaseVersionSaysNotTo() + { + var baseCalculator = new TestBaseVersionCalculator(false, false, new SemanticVersion(1), new MockCommit()); + var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(1, "develop", "b1a34e", DateTimeOffset.Now); + var sut = new NewNextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var context = new GitVersionContextBuilder() + .WithDevelopBranch() + .Build(); + + var version = sut.FindVersion(context); + + version.ToString("f").ShouldBe("1.0.0+1"); + } + + [Test] + public void PreReleaseTagCanUseBranchName() + { + var baseCalculator = new TestBaseVersionCalculator(false, true, new SemanticVersion(1), new MockCommit()); + var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData(2, "develop", "b1a34e", DateTimeOffset.Now); + var sut = new NewNextVersionCalculator(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var config = new Config(); + config.Branches.Add("custom/", new BranchConfig + { + Tag = "useBranchName" + }); + var context = new GitVersionContextBuilder() + .WithConfig(config) + .WithDevelopBranch() + .AddBranch("custom/foo") + .Build(); + + var version = sut.FindVersion(context); + + version.ToString("f").ShouldBe("1.0.0-foo.1+2"); + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs b/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs new file mode 100644 index 0000000000..d68469ccfd --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs @@ -0,0 +1,38 @@ +namespace GitVersionCore.Tests.VersionCalculation.Strategies +{ + using GitVersion; + using GitVersion.VersionCalculation.BaseVersionCalculators; + using NUnit.Framework; + using Shouldly; + + [TestFixture] + public class ConfigNextVersionBaseVersionStrategyTests + { + [Test] + public void ShouldNotBeIncremented() + { + var contextBuilder = new GitVersionContextBuilder() + .WithConfig(new Config + { + NextVersion = "1.0.0" + }); + var sut = new ConfigNextVersionBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(contextBuilder.Build()); + + baseVersion.ShouldIncrement.ShouldBe(false); + baseVersion.SemanticVersion.ToString().ShouldBe("1.0.0"); + } + + [Test] + public void ReturnsNullWhenNoNextVersionIsInConfig() + { + var contextBuilder = new GitVersionContextBuilder(); + var sut = new ConfigNextVersionBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(contextBuilder.Build()); + + baseVersion.ShouldBe(null); + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/Strategies/LastTagBaseVersionStrategyTests.cs b/GitVersionCore.Tests/VersionCalculation/Strategies/LastTagBaseVersionStrategyTests.cs new file mode 100644 index 0000000000..7341233a86 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/Strategies/LastTagBaseVersionStrategyTests.cs @@ -0,0 +1,39 @@ +namespace GitVersionCore.Tests.VersionCalculation.Strategies +{ + using GitVersion.VersionCalculation.BaseVersionCalculators; + using NUnit.Framework; + using Shouldly; + + [TestFixture] + public class LastTagBaseVersionStrategyTests + { + [Test] + public void ShouldAllowVersionIncrement() + { + // TODO Looks like our MockRepostory stuff doesn't work properly. commits are added to end of list, but Tip is first. + // Changing behaviour breaks a bunch of tests + var context = new GitVersionContextBuilder() + .WithTaggedMaster() + .AddCommit() + .Build(); + var sut = new LastTagBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(context); + + baseVersion.ShouldIncrement.ShouldBe(true); + } + + [Test] + public void ShouldNotAllowVersionIncrementWhenTagComesFromCurrentCommit() + { + var context = new GitVersionContextBuilder() + .WithTaggedMaster() + .Build(); + var sut = new LastTagBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(context); + + baseVersion.ShouldIncrement.ShouldBe(false); + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs b/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs new file mode 100644 index 0000000000..5681045d66 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs @@ -0,0 +1,112 @@ +namespace GitVersionCore.Tests.VersionCalculation.Strategies +{ + using System.Collections.Generic; + using GitVersion.VersionCalculation.BaseVersionCalculators; + using LibGit2Sharp; + using NUnit.Framework; + using Shouldly; + + [TestFixture] + public class MergeMessageBaseVersionStrategyTests + { + [Test] + public void ShouldNotAllowIncrementOfVersion() + { + // When a branch is merged in you want to start building stable packages of that version + // So we shouldn't bump the version + var context = new GitVersionContextBuilder().WithRepository(new MockRepository + { + Head = new MockBranch("master") { new MockCommit + { + MessageEx = "Merge branch 'hotfix-0.1.5'", + ParentsEx = GetParents(true) + } } + }).Build(); + var sut = new MergeMessageBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(context); + + baseVersion.ShouldIncrement.ShouldBe(false); + } + + [TestCase("Merge branch 'hotfix-0.1.5'", false, null)] + [TestCase("Merge branch 'develop' of github.com:Particular/NServiceBus into develop", true, null)] + [TestCase("Merge branch '4.0.3'", true, "4.0.3")] //TODO: possible make it a config option to support this + [TestCase("Merge branch 'release-10.10.50'", true, "10.10.50")] + [TestCase("Merge branch 's'", true, null)] // Must start with a number + [TestCase("Merge branch 'release-0.2.0'", true, "0.2.0")] + [TestCase("Merge branch 'hotfix-4.6.6' into support-4.6", true, "4.6.6")] + [TestCase("Merge branch 'hotfix-10.10.50'", true, "10.10.50")] + [TestCase("Merge branch 'hotfix-0.1.5'", true, "0.1.5")] + [TestCase("Merge branch 'hotfix-0.1.5'\n\nRelates to: TicketId", true, "0.1.5")] + [TestCase("Merge branch 'alpha-0.1.5'", true, "0.1.5")] + [TestCase("Merge pull request #165 from Particular/release-1.0.0", true, "1.0.0")] + [TestCase("Merge pull request #95 from Particular/issue-94", false, null)] + [TestCase("Merge pull request #165 in Particular/release-1.0.0", true, "1.0.0")] + [TestCase("Merge pull request #95 in Particular/issue-94", true, null)] + [TestCase("Merge pull request #95 in Particular/issue-94", false, null)] + [TestCase("Merge pull request #64 from arledesma/feature-VS2013_3rd_party_test_framework_support", true, null)] + [TestCase("Finish Release-0.12.0", true, "0.12.0")] //Support Syntevo SmartGit/Hg's Gitflow merge commit messages for finishing a 'Release' branch + [TestCase("Finish 0.14.1", true, "0.14.1")] //Support Syntevo SmartGit/Hg's Gitflow merge commit messages for finishing a 'Hotfix' branch + public void AssertMergeMessage(string message, bool isMergeCommit, string expectedVersion) + { + var parents = GetParents(isMergeCommit); + AssertMergeMessage(message, expectedVersion, parents); + AssertMergeMessage(message + " ", expectedVersion, parents); + AssertMergeMessage(message + "\r ", expectedVersion, parents); + AssertMergeMessage(message + "\r", expectedVersion, parents); + AssertMergeMessage(message + "\r\n", expectedVersion, parents); + AssertMergeMessage(message + "\r\n ", expectedVersion, parents); + AssertMergeMessage(message + "\n", expectedVersion, parents); + AssertMergeMessage(message + "\n ", expectedVersion, parents); + } + + static void AssertMergeMessage(string message, string expectedVersion, List parents) + { + var commit = new MockCommit + { + MessageEx = message, + ParentsEx = parents + }; + + var context = new GitVersionContextBuilder() + .WithRepository(new MockRepository + { + Head = new MockBranch("master") + { + commit, + new MockCommit() + } + }) + .Build(); + var sut = new MergeMessageBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(context); + + if (expectedVersion == null) + { + baseVersion.ShouldBe(null); + } + else + { + baseVersion.SemanticVersion.ToString().ShouldBe(expectedVersion); + } + } + + static List GetParents(bool isMergeCommit) + { + if (isMergeCommit) + { + return new List + { + null, + null + }; + } + return new List + { + null + }; + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchBaseVersionStrategyTests.cs b/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchBaseVersionStrategyTests.cs new file mode 100644 index 0000000000..ea8430d013 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchBaseVersionStrategyTests.cs @@ -0,0 +1,37 @@ +namespace GitVersionCore.Tests.VersionCalculation.Strategies +{ + using GitVersion; + using GitVersion.VersionCalculation.BaseVersionCalculators; + using LibGit2Sharp; + using NUnit.Framework; + using Shouldly; + + [TestFixture] + public class VersionInBranchBaseVersionStrategyTests + { + [Test] + [TestCase("release-2.0.0", "2.0.0")] + [TestCase("release/2.0.0", "2.0.0")] + [TestCase("hotfix-2.0.0", "2.0.0")] + [TestCase("hotfix/2.0.0", "2.0.0")] + [TestCase("hotfix/2.0.0", "2.0.0")] + [TestCase("custom/JIRA-123", null)] + public void CanTakeVersionFromBranchName(string branchName, string expectedBaseVersion) + { + var configuration = new Config(); + using (var fixture = new EmptyRepositoryFixture(configuration)) + { + fixture.Repository.MakeACommit(); + var branch = fixture.Repository.CreateBranch(branchName); + var sut = new VersionInBranchBaseVersionStrategy(); + + var baseVersion = sut.GetVersion(new GitVersionContext(fixture.Repository, branch, configuration)); + + if (expectedBaseVersion == null) + baseVersion.ShouldBe(null); + else + baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion); + } + } + } +} diff --git a/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs b/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs new file mode 100644 index 0000000000..5cb51845b3 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs @@ -0,0 +1,28 @@ +namespace GitVersionCore.Tests.VersionCalculation +{ + using GitVersion; + using GitVersion.VersionCalculation; + using GitVersion.VersionCalculation.BaseVersionCalculators; + using LibGit2Sharp; + + public class TestBaseVersionCalculator : IBaseVersionCalculator + { + readonly SemanticVersion semanticVersion; + bool shouldIncrement; + bool shouldUpdateTag; + Commit source; + + public TestBaseVersionCalculator(bool shouldIncrement, bool shouldUpdateTag, SemanticVersion semanticVersion, Commit source) + { + this.semanticVersion = semanticVersion; + this.source = source; + this.shouldUpdateTag = shouldUpdateTag; + this.shouldIncrement = shouldIncrement; + } + + public BaseVersion GetBaseVersion(GitVersionContext context) + { + return new BaseVersion("Test source", shouldIncrement, shouldUpdateTag, semanticVersion, source, null); + } + } +} \ No newline at end of file diff --git a/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs b/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs new file mode 100644 index 0000000000..51f7a95b22 --- /dev/null +++ b/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs @@ -0,0 +1,21 @@ +namespace GitVersionCore.Tests.VersionCalculation +{ + using GitVersion; + using GitVersion.VersionCalculation; + using LibGit2Sharp; + + public class TestMetaDataCalculator : IMetaDataCalculator + { + SemanticVersionBuildMetaData metaData; + + public TestMetaDataCalculator(SemanticVersionBuildMetaData metaData) + { + this.metaData = metaData; + } + + public SemanticVersionBuildMetaData Create(Commit baseVersionSource, GitVersionContext context) + { + return metaData; + } + } +} \ No newline at end of file diff --git a/GitVersionCore/AssemblyVersionsGenerator.cs b/GitVersionCore/AssemblyVersionsGenerator.cs index a8e218a64a..07fedbbc94 100644 --- a/GitVersionCore/AssemblyVersionsGenerator.cs +++ b/GitVersionCore/AssemblyVersionsGenerator.cs @@ -23,23 +23,6 @@ public static string GetAssemblyVersion( } } - public static string GetAssemblyFileVersion( - this SemanticVersion sv, - AssemblyVersioningScheme scheme) - { - switch (scheme) - { - case AssemblyVersioningScheme.Major: - case AssemblyVersioningScheme.MajorMinor: - case AssemblyVersioningScheme.MajorMinorPatch: - return string.Format("{0}.{1}.{2}.0", sv.Major, sv.Minor, sv.Patch); - case AssemblyVersioningScheme.MajorMinorPatchMetadata: - return string.Format("{0}.{1}.{2}.{3}", sv.Major, sv.Minor, sv.Patch, sv.BuildMetaData.CommitsSinceTag ?? 0); - default: - throw new ArgumentException(string.Format("Unexpected value ({0}).", scheme), "scheme"); - } - - } } } \ No newline at end of file diff --git a/GitVersionCore/BuildServers/AppVeyor.cs b/GitVersionCore/BuildServers/AppVeyor.cs index fcb6fd873d..fa77373898 100644 --- a/GitVersionCore/BuildServers/AppVeyor.cs +++ b/GitVersionCore/BuildServers/AppVeyor.cs @@ -51,7 +51,7 @@ public override string GenerateSetVersionMessage(string versionToUseForBuildNumb { if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent) { - var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); + var message = string.Format("Request failed. Received HTTP {0}", response.StatusCode); return message; } } diff --git a/GitVersionCore/BuildServers/BuildServerBase.cs b/GitVersionCore/BuildServers/BuildServerBase.cs index a38d178315..532df5a87d 100644 --- a/GitVersionCore/BuildServers/BuildServerBase.cs +++ b/GitVersionCore/BuildServers/BuildServerBase.cs @@ -9,22 +9,17 @@ public abstract class BuildServerBase : IBuildServer public abstract string GenerateSetVersionMessage(string versionToUseForBuildNumber); public abstract string[] GenerateSetParameterMessage(string name, string value); - public virtual void WriteIntegration(SemanticVersion semanticVersion, Action writer) + public virtual void WriteIntegration(Action writer, VersionVariables variables) { - if (semanticVersion == null) - { - return; - } - if (writer == null) { return; } writer(string.Format("Executing GenerateSetVersionMessage for '{0}'.", GetType().Name)); - writer(GenerateSetVersionMessage(semanticVersion.ToString("f"))); + writer(GenerateSetVersionMessage(variables.FullSemVer)); writer(string.Format("Executing GenerateBuildLogOutput for '{0}'.", GetType().Name)); - foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(semanticVersion, this)) + foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(this, variables)) { writer(buildParameter); } diff --git a/GitVersionCore/BuildServers/IBuildServer.cs b/GitVersionCore/BuildServers/IBuildServer.cs index 526711e40f..09aa87ef82 100644 --- a/GitVersionCore/BuildServers/IBuildServer.cs +++ b/GitVersionCore/BuildServers/IBuildServer.cs @@ -9,7 +9,7 @@ public interface IBuildServer string GenerateSetVersionMessage(string versionToUseForBuildNumber); string[] GenerateSetParameterMessage(string name, string value); - void WriteIntegration(SemanticVersion semanticVersion, Action writer); + void WriteIntegration(Action writer, VersionVariables variables); } } diff --git a/GitVersionCore/Configuration/BranchConfig.cs b/GitVersionCore/Configuration/BranchConfig.cs new file mode 100644 index 0000000000..a5717eb979 --- /dev/null +++ b/GitVersionCore/Configuration/BranchConfig.cs @@ -0,0 +1,33 @@ +namespace GitVersion +{ + using YamlDotNet.Serialization; + + public class BranchConfig + { + public BranchConfig() + { + } + + public BranchConfig(BranchConfig branchConfiguration) + { + VersioningMode = branchConfiguration.VersioningMode; + Tag = branchConfiguration.Tag; + Increment = branchConfiguration.Increment; + } + + [YamlMember(Alias = "mode")] + public VersioningMode? VersioningMode { get; set; } + + /// + /// Special value 'useBranchName' will extract the tag from the branch name + /// + [YamlMember(Alias = "tag")] + public string Tag { get; set; } + + [YamlMember(Alias = "increment")] + public IncrementStrategy? Increment { get; set; } + + [YamlMember(Alias = "preventIncrementOfMergedBranchVersion")] + public bool? PreventIncrementOfMergedBranchVersion { get; set; } + } +} diff --git a/GitVersionCore/Configuration/Config.cs b/GitVersionCore/Configuration/Config.cs index a7ea65d89c..16db0f0c6f 100644 --- a/GitVersionCore/Configuration/Config.cs +++ b/GitVersionCore/Configuration/Config.cs @@ -1,30 +1,85 @@ namespace GitVersion { + using System.Collections.Generic; + using System.Linq; using YamlDotNet.Serialization; public class Config { + Dictionary branches = new Dictionary(); + public Config() { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch; - DevelopBranchTag = "unstable"; - ReleaseBranchTag = "beta"; TagPrefix = "[vV]"; + VersioningMode = GitVersion.VersioningMode.ContinuousDelivery; + + Branches["master"] = new BranchConfig + { + Tag = string.Empty, + Increment = IncrementStrategy.Patch, + PreventIncrementOfMergedBranchVersion = true + }; + Branches["release[/-]"] = new BranchConfig { Tag = "beta" }; + Branches["feature[/-]"] = new BranchConfig + { + Increment = IncrementStrategy.Inherit, + Tag = "useBranchName" + }; + Branches["hotfix[/-]"] = new BranchConfig { Tag = "beta" }; + Branches["support[/-]"] = new BranchConfig + { + Tag = string.Empty, + Increment = IncrementStrategy.Patch, + PreventIncrementOfMergedBranchVersion = true + }; + Branches["develop"] = new BranchConfig + { + Tag = "unstable", + Increment = IncrementStrategy.Minor, + VersioningMode = GitVersion.VersioningMode.ContinuousDeployment + }; + Branches[@"(pull|pull\-requests|pr)[/-]"] = new BranchConfig + { + Tag = "PullRequest", + Increment = IncrementStrategy.Inherit + }; } - [YamlAlias("assembly-versioning-scheme")] + [YamlMember(Alias = "assembly-versioning-scheme")] public AssemblyVersioningScheme AssemblyVersioningScheme { get; set; } - [YamlAlias("develop-branch-tag")] - public string DevelopBranchTag { get; set; } - - [YamlAlias("release-branch-tag")] - public string ReleaseBranchTag { get; set; } + [YamlMember(Alias = "mode")] + public VersioningMode? VersioningMode { get; set; } - [YamlAlias("tag-prefix")] + [YamlMember(Alias = "tag-prefix")] public string TagPrefix { get; set; } - [YamlAlias("next-version")] + [YamlMember(Alias = "next-version")] public string NextVersion { get; set; } + + [YamlMember(Alias = "branches")] + public Dictionary Branches + { + get + { + return branches; + } + set + { + value.ToList().ForEach(_ => branches[_.Key] = MergeObjects(branches[_.Key], _.Value)); + } + } + + private T MergeObjects(T target, T source) + { + typeof(T).GetProperties() + .Where(prop => prop.CanRead && prop.CanWrite) + .Select(_ => new {prop = _, value =_.GetValue(source, null) } ) + .Where(_ => _.value != null) + .ToList() + .ForEach(_ => _.prop.SetValue(target, _.value, null)); + return target; + } } } \ No newline at end of file diff --git a/GitVersionCore/Configuration/ConfigReader.cs b/GitVersionCore/Configuration/ConfigReader.cs index 73bd570259..79469adb70 100644 --- a/GitVersionCore/Configuration/ConfigReader.cs +++ b/GitVersionCore/Configuration/ConfigReader.cs @@ -20,10 +20,12 @@ public static Config Read(TextReader reader) public static void WriteSample(TextWriter writer) { writer.WriteLine("# assembly-versioning-scheme: MajorMinorPatchMetadata | MajorMinorPatch | MajorMinor | Major"); - writer.WriteLine("# develop-branch-tag: alpha"); - writer.WriteLine("# release-branch-tag: rc"); writer.WriteLine("# tag-prefix: '[vV|version-] # regex to match git tag prefix"); writer.WriteLine("# next-version: 1.0.0"); + writer.WriteLine("# mode: ContinuousDelivery | ContinuousDeployment"); + writer.WriteLine("#branches:"); + writer.WriteLine("# release[/-]*:\n mode: ContinuousDelivery | ContinuousDeployment\n tag: rc"); + writer.WriteLine("# develop:\n mode: ContinuousDelivery | ContinuousDeployment\n tag: alpha"); } } } \ No newline at end of file diff --git a/GitVersionCore/Configuration/ConfigurationProvider.cs b/GitVersionCore/Configuration/ConfigurationProvider.cs index ca9bb7218d..8a164b8ff6 100644 --- a/GitVersionCore/Configuration/ConfigurationProvider.cs +++ b/GitVersionCore/Configuration/ConfigurationProvider.cs @@ -15,12 +15,7 @@ public static Config Provide(string gitDirectory, IFileSystem fileSystem) if (fileSystem.Exists(configFilePath)) { var readAllText = fileSystem.ReadAllText(configFilePath); - if (oldAssemblyVersioningScheme.IsMatch(readAllText)) - { - readAllText = oldAssemblyVersioningScheme.Replace(readAllText, "assembly-versioning-scheme"); - fileSystem.WriteAllText(configFilePath, readAllText); - Logger.WriteWarning("Found legacy configuration value 'assemblyVersioningScheme', replaced with 'assembly-versioning-scheme"); - } + LegacyConfigNotifier.Notify(new StringReader(readAllText)); return ConfigReader.Read(new StringReader(readAllText)); } diff --git a/GitVersionCore/Configuration/IncrementStrategy.cs b/GitVersionCore/Configuration/IncrementStrategy.cs new file mode 100644 index 0000000000..cd3b8de0b7 --- /dev/null +++ b/GitVersionCore/Configuration/IncrementStrategy.cs @@ -0,0 +1,14 @@ +namespace GitVersion +{ + public enum IncrementStrategy + { + None, + Major, + Minor, + Patch, + /// + /// Uses the increment strategy from the branch the current branch was branched from + /// + Inherit + } +} \ No newline at end of file diff --git a/GitVersionCore/Configuration/LegacyConfig.cs b/GitVersionCore/Configuration/LegacyConfig.cs new file mode 100644 index 0000000000..dea5a9076d --- /dev/null +++ b/GitVersionCore/Configuration/LegacyConfig.cs @@ -0,0 +1,18 @@ +namespace GitVersion +{ + using YamlDotNet.Serialization; + + /// + /// Obsolete properties are added to this, so we can check to see if they are used and provide good error messages for migration + /// + public class LegacyConfig + { + public string assemblyVersioningScheme { get; set; } + + [YamlMember(Alias = "develop-branch-tag")] + public string DevelopBranchTag { get; set; } + + [YamlMember(Alias = "release-branch-tag")] + public string ReleaseBranchTag { get; set; } + } +} \ No newline at end of file diff --git a/GitVersionCore/Configuration/LegacyConfigNotifier.cs b/GitVersionCore/Configuration/LegacyConfigNotifier.cs new file mode 100644 index 0000000000..7dba3c5624 --- /dev/null +++ b/GitVersionCore/Configuration/LegacyConfigNotifier.cs @@ -0,0 +1,33 @@ +namespace GitVersion +{ + using System.Collections.Generic; + using System.IO; + using System.Linq; + using YamlDotNet.Serialization; + using YamlDotNet.Serialization.NamingConventions; + + public class LegacyConfigNotifier + { + public static void Notify(StringReader reader) + { + var deserializer = new Deserializer(null, new NullNamingConvention(), ignoreUnmatched: true); + var legacyConfig = deserializer.Deserialize(reader); + if (legacyConfig == null) + return; + + var issues = new List(); + + if (legacyConfig.assemblyVersioningScheme != null) + issues.Add("assemblyVersioningScheme has been replaced by assembly-versioning-scheme"); + + if (legacyConfig.DevelopBranchTag != null) + issues.Add("develop-branch-tag has been replaced by branch specific configuration. See https://github.com/ParticularLabs/GitVersion/wiki/Branch-Specific-Configuration"); + + if (legacyConfig.ReleaseBranchTag != null) + issues.Add("release-branch-tag has been replaced by branch specific configuration. See https://github.com/ParticularLabs/GitVersion/wiki/Branch-Specific-Configuration"); + + if (issues.Any()) + throw new OldConfigurationException("GitVersionConfig.yaml contains old configuration, please fix the following errors:\r\n" + string.Join("\r\n", issues)); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/Configuration/OldConfigurationException.cs b/GitVersionCore/Configuration/OldConfigurationException.cs new file mode 100644 index 0000000000..08603b4daf --- /dev/null +++ b/GitVersionCore/Configuration/OldConfigurationException.cs @@ -0,0 +1,19 @@ +namespace GitVersion +{ + using System; + using System.Runtime.Serialization; + + [Serializable] + public class OldConfigurationException : Exception + { + public OldConfigurationException(string message) : base(message) + { + } + + protected OldConfigurationException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { + } + } +} \ No newline at end of file diff --git a/GitVersionCore/EffectiveConfiguration.cs b/GitVersionCore/EffectiveConfiguration.cs new file mode 100644 index 0000000000..b7dd6cd946 --- /dev/null +++ b/GitVersionCore/EffectiveConfiguration.cs @@ -0,0 +1,47 @@ +namespace GitVersion +{ + /// + /// Configuration can be applied to different things, effective configuration is the result after applying the appropriate configuration + /// + public class EffectiveConfiguration + { + public EffectiveConfiguration( + AssemblyVersioningScheme assemblyVersioningScheme, + VersioningMode versioningMode, string gitTagPrefix, + string tag, string nextVersion, IncrementStrategy increment, + string branchPrefixToTrim, + bool preventIncrementForMergedBranchVersion) + { + AssemblyVersioningScheme = assemblyVersioningScheme; + VersioningMode = versioningMode; + GitTagPrefix = gitTagPrefix; + Tag = tag; + NextVersion = nextVersion; + Increment = increment; + BranchPrefixToTrim = branchPrefixToTrim; + PreventIncrementForMergedBranchVersion = preventIncrementForMergedBranchVersion; + } + + public VersioningMode VersioningMode { get; private set; } + + public AssemblyVersioningScheme AssemblyVersioningScheme { get; private set; } + + /// + /// Git tag prefix + /// + public string GitTagPrefix { get; private set; } + + /// + /// Tag to use when calculating SemVer + /// + public string Tag { get; private set; } + + public string NextVersion { get; private set; } + + public IncrementStrategy Increment { get; private set; } + + public string BranchPrefixToTrim { get; private set; } + + public bool PreventIncrementForMergedBranchVersion { get; private set; } + } +} \ No newline at end of file diff --git a/GitVersionCore/Extensions/ExtensionMethods.git.cs b/GitVersionCore/Extensions/ExtensionMethods.git.cs index a9099dc71a..b8d64f3324 100644 --- a/GitVersionCore/Extensions/ExtensionMethods.git.cs +++ b/GitVersionCore/Extensions/ExtensionMethods.git.cs @@ -1,7 +1,5 @@ namespace GitVersion { - using System; - static partial class ExtensionMethods { public static string GetCanonicalBranchName(this string branchName) @@ -17,70 +15,9 @@ public static string GetCanonicalBranchName(this string branchName) return string.Format("refs/heads/{0}", branchName); } - public static bool IsHotfix(this string branchName) - { - return branchName.StartsWith("hotfix-") || branchName.StartsWith("hotfix/"); - } - - public static string GetHotfixSuffix(this string branchName) - { - return branchName.TrimStart("hotfix-").TrimStart("hotfix/"); - } - - public static bool IsRelease(this string branchName) - { - return branchName.StartsWith("release-") || branchName.StartsWith("release/"); - } - - public static string GetReleaseSuffix(this string branchName) - { - return branchName.TrimStart("release-").TrimStart("release/"); - } - - public static string GetUnknownBranchSuffix(this string branchName) - { - var unknownBranchSuffix = branchName.Split('-', '/'); - if (unknownBranchSuffix.Length == 1) - return branchName; - return unknownBranchSuffix[1]; - } - - public static string GetSuffix(this string branchName, BranchType branchType) - { - switch (branchType) - { - case BranchType.Hotfix: - return branchName.GetHotfixSuffix(); - - case BranchType.Release: - return branchName.GetReleaseSuffix(); - - case BranchType.Unknown: - return branchName.GetUnknownBranchSuffix(); - - default: - throw new NotSupportedException(string.Format("Unexpected branch type {0}.", branchType)); - } - } - - public static bool IsDevelop(this string branchName) - { - return branchName == "develop"; - } - - public static bool IsMaster(this string branchName) - { - return branchName == "master"; - } - public static bool IsPullRequest(this string branchName) { return branchName.Contains("pull/") || branchName.Contains("pull-requests/") || branchName.Contains("pr/"); } - - public static bool IsSupport(this string branchName) - { - return branchName.ToLower().StartsWith("support-") || branchName.ToLower().StartsWith("support/"); - } } } diff --git a/GitVersionCore/GitFlow/BranchClassifier.cs b/GitVersionCore/GitFlow/BranchClassifier.cs deleted file mode 100644 index 5c7c3c7101..0000000000 --- a/GitVersionCore/GitFlow/BranchClassifier.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace GitVersion -{ - using LibGit2Sharp; - - static class BranchClassifier - { - public static bool IsHotfix(this Branch branch) - { - return branch.Name.IsHotfix(); - } - - public static string GetHotfixSuffix(this Branch branch) - { - return branch.Name.GetHotfixSuffix(); - } - - public static bool IsRelease(this Branch branch) - { - return branch.Name.IsRelease(); - } - - public static string GetReleaseSuffix(this Branch branch) - { - return branch.Name.GetReleaseSuffix(); - } - - public static string GetUnknownBranchSuffix(this Branch branch) - { - return branch.Name.GetUnknownBranchSuffix(); - } - - public static string GetSuffix(this Branch branch, BranchType branchType) - { - return branch.CanonicalName.GetSuffix(branchType); - } - - public static bool IsDevelop(this Branch branch) - { - return branch.Name.IsDevelop(); - } - - public static bool IsMaster(this Branch branch) - { - return branch.Name.IsMaster(); - } - - public static bool IsPullRequest(this Branch branch) - { - return branch.CanonicalName.IsPullRequest(); - } - - public static bool IsSupport(this Branch branch) - { - return branch.Name.IsSupport(); - } - } -} diff --git a/GitVersionCore/GitFlow/BranchFinders/BranchCommitDifferenceFinder.cs b/GitVersionCore/GitFlow/BranchFinders/BranchCommitDifferenceFinder.cs deleted file mode 100644 index 88e91e1ad5..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/BranchCommitDifferenceFinder.cs +++ /dev/null @@ -1,72 +0,0 @@ -namespace GitVersion -{ - using System.Collections.Generic; - using System.Linq; - using LibGit2Sharp; - - static class BranchCommitDifferenceFinder - { - public static int NumberOfCommitsInBranchNotKnownFromBaseBranch(IRepository repo, Branch branch, BranchType branchType, string baseBranchName) - { - var baseTip = repo.FindBranch(baseBranchName).Tip; - if (branch.Tip == baseTip) - { - // The branch bears no additional commit - return 0; - } - - var ancestor = repo.Commits.FindMergeBase( - baseTip, - branch.Tip); - - if (ancestor == null) - { - var message = string.Format("A {0} branch is expected to branch off of '{1}'. However, branch '{1}' and '{2}' do not share a common ancestor.", branchType, baseBranchName, branch.Name); - throw new WarningException(message); - } - - var filter = new CommitFilter - { - Since = branch.Tip, - Until = ancestor, - SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time - }; - - return repo.Commits.QueryBy(filter) - .Count(); - } - - public static int NumberOfCommitsSinceLastTagOrBranchPoint(GitVersionContext context, List tagsInDescendingOrder, BranchType branchType, string baseBranchName) - { - if (!tagsInDescendingOrder.Any()) - { - return NumberOfCommitsInBranchNotKnownFromBaseBranch(context.Repository, context.CurrentBranch, branchType, baseBranchName); - } - - var mostRecentTag = tagsInDescendingOrder.First(); - var ancestor = mostRecentTag; - if (mostRecentTag.Target == context.CurrentCommit) - { - var previousTag = tagsInDescendingOrder.Skip(1).FirstOrDefault(); - if (previousTag != null) - { - ancestor = previousTag; - } - else - { - return NumberOfCommitsInBranchNotKnownFromBaseBranch(context.Repository, context.CurrentBranch, BranchType.Release, baseBranchName); - } - - } - - var filter = new CommitFilter - { - Since = context.CurrentCommit, - Until = ancestor.Target, - SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time - }; - - return context.Repository.Commits.QueryBy(filter).Count() - 1; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitFlow/BranchFinders/DevelopBasedVersionFinderBase.cs b/GitVersionCore/GitFlow/BranchFinders/DevelopBasedVersionFinderBase.cs deleted file mode 100644 index fc52a919a0..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/DevelopBasedVersionFinderBase.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace GitVersion -{ - using System.Linq; - using LibGit2Sharp; - - abstract class DevelopBasedVersionFinderBase - { - protected SemanticVersion FindVersion( - GitVersionContext context, - BranchType branchType) - { - var ancestor = FindCommonAncestorWithDevelop(context.Repository, context.CurrentBranch, branchType); - - if (!IsThereAnyCommitOnTheBranch(context.Repository, context.CurrentBranch)) - { - var developVersionFinder = new DevelopVersionFinder(); - return developVersionFinder.FindVersion(context); - } - - var versionOnMasterFinder = new VersionOnMasterFinder(); - var versionFromMaster = versionOnMasterFinder.Execute(context, context.CurrentCommit.When()); - - var numberOfCommitsOnBranchSinceCommit = NumberOfCommitsOnBranchSinceCommit(context, ancestor); - var preReleaseTag = context.CurrentBranch.Name - .TrimStart(branchType.ToString() + '-') - .TrimStart(branchType.ToString() + '/'); - var semanticVersion = new SemanticVersion - { - Major = versionFromMaster.Major, - Minor = versionFromMaster.Minor + 1, - Patch = 0, - PreReleaseTag = preReleaseTag, - BuildMetaData = new SemanticVersionBuildMetaData( - numberOfCommitsOnBranchSinceCommit, - context.CurrentBranch.Name, context.CurrentCommit.Sha, context.CurrentCommit.When()) - }; - - semanticVersion.OverrideVersionManuallyIfNeeded(context.Repository, context.Configuration); - - return semanticVersion; - } - - int NumberOfCommitsOnBranchSinceCommit(GitVersionContext context, Commit commit) - { - var qf = new CommitFilter - { - Since = context.CurrentBranch, - Until = commit, - SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time - }; - - return context.Repository.Commits - .QueryBy(qf) - .Count(); - } - - Commit FindCommonAncestorWithDevelop(IRepository repo, Branch branch, BranchType branchType) - { - var ancestor = repo.Commits.FindMergeBase( - repo.FindBranch("develop").Tip, - branch.Tip); - - if (ancestor != null) - { - return ancestor; - } - - throw new WarningException( - string.Format("A {0} branch is expected to branch off of 'develop'. " - + "However, branch 'develop' and '{1}' do not share a common ancestor." - , branchType, branch.Name)); - } - - public bool IsThereAnyCommitOnTheBranch(IRepository repo, Branch branch) - { - var filter = new CommitFilter - { - Since = branch, - Until = repo.FindBranch("develop") - }; - - var commits = repo.Commits.QueryBy(filter); - - if (!commits.Any()) - { - return false; - } - - return true; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitFlow/BranchFinders/DevelopVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/DevelopVersionFinder.cs deleted file mode 100644 index 16192f4aad..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/DevelopVersionFinder.cs +++ /dev/null @@ -1,38 +0,0 @@ -namespace GitVersion -{ - using System.Linq; - using LibGit2Sharp; - - class DevelopVersionFinder - { - public SemanticVersion FindVersion(GitVersionContext context) - { - var versionOnMasterFinder = new VersionOnMasterFinder(); - var tip = context.CurrentCommit; - var versionFromMaster = versionOnMasterFinder.Execute(context, tip.When()); - - var f = new CommitFilter - { - Since = tip, - Until = context.Repository.FindBranch("master").Tip, - SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time - }; - - var c = context.Repository.Commits.QueryBy(f); - var numberOfCommitsSinceRelease = c.Count(); - - var semanticVersion = new SemanticVersion - { - Major = versionFromMaster.Major, - Minor = versionFromMaster.Minor + 1, - Patch = 0, - PreReleaseTag = context.Configuration.DevelopBranchTag + numberOfCommitsSinceRelease, - BuildMetaData = new SemanticVersionBuildMetaData(numberOfCommitsSinceRelease, context.CurrentBranch.Name,tip.Sha,tip.When()), - }; - - semanticVersion.OverrideVersionManuallyIfNeeded(context.Repository, context.Configuration); - - return semanticVersion; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitFlow/BranchFinders/FeatureVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/FeatureVersionFinder.cs deleted file mode 100644 index 8065697a92..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/FeatureVersionFinder.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace GitVersion -{ - class FeatureVersionFinder : DevelopBasedVersionFinderBase - { - public SemanticVersion FindVersion(GitVersionContext context) - { - return FindVersion(context, BranchType.Feature); - } - } -} diff --git a/GitVersionCore/GitFlow/BranchFinders/HotfixVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/HotfixVersionFinder.cs deleted file mode 100644 index 17025df3c5..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/HotfixVersionFinder.cs +++ /dev/null @@ -1,52 +0,0 @@ -namespace GitVersion -{ - using LibGit2Sharp; - - class HotfixVersionFinder - { - public SemanticVersion FindVersion(GitVersionContext context) - { - var versionString = GetSuffix(context.CurrentBranch); - var shortVersion = SemanticVersion.Parse(versionString, context.Configuration.TagPrefix); - - EnsureVersionIsValid(shortVersion, context.CurrentBranch); - - var nbHotfixCommits = BranchCommitDifferenceFinder.NumberOfCommitsInBranchNotKnownFromBaseBranch(context.Repository, context.CurrentBranch, BranchType.Hotfix, "master"); - - var semanticVersionPreReleaseTag = GetSemanticVersionPreReleaseTag(context, shortVersion); - return new SemanticVersion - { - Major = shortVersion.Major, - Minor = shortVersion.Minor, - Patch = shortVersion.Patch, - PreReleaseTag = semanticVersionPreReleaseTag, - BuildMetaData = new SemanticVersionBuildMetaData(nbHotfixCommits, context.CurrentBranch.Name, context.CurrentCommit.Sha, context.CurrentCommit.When()) - }; - } - - static string GetSemanticVersionPreReleaseTag(GitVersionContext context, SemanticVersion shortVersion) - { - var semanticVersionPreReleaseTag = context.Configuration.ReleaseBranchTag + ".1"; - var tagVersion = RecentTagVersionExtractor.RetrieveMostRecentOptionalTagVersion(context, shortVersion); - if (tagVersion != null) - { - semanticVersionPreReleaseTag = tagVersion; - } - return semanticVersionPreReleaseTag; - } - - static string GetSuffix(Branch branch) - { - return branch.Name.TrimStart("hotfix-").TrimStart("hotfix/"); - } - - void EnsureVersionIsValid(SemanticVersion version, Branch branch) - { - if (version.Patch == 0) - { - var message = string.Format("Branch '{0}' doesn't respect the Hotfix branch naming convention. A patch segment different than zero is required.", branch.Name); - throw new WarningException(message); - } - } - } -} diff --git a/GitVersionCore/GitFlow/BranchFinders/MasterVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/MasterVersionFinder.cs deleted file mode 100644 index 067e05ea21..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/MasterVersionFinder.cs +++ /dev/null @@ -1,37 +0,0 @@ -namespace GitVersion -{ - using LibGit2Sharp; - - class MasterVersionFinder - { - public SemanticVersion FindVersion(GitVersionContext context) - { - foreach (var tag in context.Repository.TagsByDate(context.CurrentCommit)) - { - SemanticVersion shortVersion; - if (SemanticVersion.TryParse(tag.Name, context.Configuration.TagPrefix, out shortVersion)) - { - return BuildVersion(context.CurrentCommit, shortVersion); - } - } - - SemanticVersion versionFromTip; - if (MergeMessageParser.TryParse(context.CurrentCommit, context.Configuration, out versionFromTip)) - { - return BuildVersion(context.CurrentCommit, versionFromTip); - } - throw new WarningException("The head of master should always be a merge commit if you follow gitflow. Please create one or work around this by tagging the commit with SemVer compatible Id."); - } - - SemanticVersion BuildVersion(Commit tip, SemanticVersion shortVersion) - { - return new SemanticVersion - { - Major = shortVersion.Major, - Minor = shortVersion.Minor, - Patch = shortVersion.Patch, - BuildMetaData = new SemanticVersionBuildMetaData(null, "master",tip.Sha,tip.When()) - }; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitFlow/BranchFinders/PullVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/PullVersionFinder.cs deleted file mode 100644 index 065a4aadbc..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/PullVersionFinder.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace GitVersion -{ - class PullVersionFinder : DevelopBasedVersionFinderBase - { - public SemanticVersion FindVersion(GitVersionContext context) - { - var issueNumber = ExtractIssueNumber(context); - - var version = FindVersion(context, BranchType.PullRequest); - version.PreReleaseTag = new SemanticVersionPreReleaseTag("PullRequest", int.Parse(issueNumber)); - //TODO version.Version.BuildMetaData = NumberOfCommitsOnBranchSinceCommit(context.CurrentBranch, commonAncestor); - return version; - } - - string ExtractIssueNumber(GitVersionContext context) - { - var issueNumber = GitHelper.ExtractIssueNumber(context.CurrentBranch.CanonicalName); - - if (!GitHelper.LooksLikeAValidPullRequestNumber(issueNumber)) - { - throw new WarningException(string.Format("Unable to extract pull request number from '{0}'.", context.CurrentBranch.CanonicalName)); - } - - return issueNumber; - } - } -} diff --git a/GitVersionCore/GitFlow/BranchFinders/ReleaseVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/ReleaseVersionFinder.cs deleted file mode 100644 index f159c3c743..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/ReleaseVersionFinder.cs +++ /dev/null @@ -1,44 +0,0 @@ -namespace GitVersion -{ - using System.Linq; - using LibGit2Sharp; - - class ReleaseVersionFinder - { - public SemanticVersion FindVersion(GitVersionContext context) - { - var versionString = GetSuffix(context.CurrentBranch); - var shortVersion = SemanticVersion.Parse(versionString, context.Configuration.TagPrefix); - - EnsureVersionIsValid(shortVersion, context.CurrentBranch); - - var applicableTagsInDescendingOrder = context.Repository.SemVerTagsRelatedToVersion(context.Configuration, shortVersion).OrderByDescending(tag => SemanticVersion.Parse(tag.Name, context.Configuration.TagPrefix)).ToList(); - var numberOfCommitsSinceLastTagOrBranchPoint = BranchCommitDifferenceFinder.NumberOfCommitsSinceLastTagOrBranchPoint(context, applicableTagsInDescendingOrder, BranchType.Release, "develop"); - var semanticVersionPreReleaseTag = RecentTagVersionExtractor.RetrieveMostRecentOptionalTagVersion(context, applicableTagsInDescendingOrder) ?? context.Configuration.ReleaseBranchTag + ".1"; - - return new SemanticVersion - { - Major = shortVersion.Major, - Minor = shortVersion.Minor, - Patch = shortVersion.Patch, - PreReleaseTag = semanticVersionPreReleaseTag, - BuildMetaData = new SemanticVersionBuildMetaData(numberOfCommitsSinceLastTagOrBranchPoint, context.CurrentBranch.Name, context.CurrentCommit.Sha, context.CurrentCommit.When()) - }; - } - - static void EnsureVersionIsValid(SemanticVersion version, Branch branch) - { - if (version.Patch != 0) - { - var message = string.Format("Branch '{0}' doesn't respect the Release branch naming convention. A patch segment equals to zero is required.", branch.Name); - throw new WarningException(message); - } - - } - - static string GetSuffix(Branch branch) - { - return branch.Name.TrimStart("release-").TrimStart("release/"); - } - } -} diff --git a/GitVersionCore/GitFlow/BranchFinders/SupportVersionFinder.cs b/GitVersionCore/GitFlow/BranchFinders/SupportVersionFinder.cs deleted file mode 100644 index 5af0c8d6f8..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/SupportVersionFinder.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace GitVersion -{ - using LibGit2Sharp; - - class SupportVersionFinder - { - public SemanticVersion FindVersion(IRepository repository, Commit tip, Config configuration) - { - foreach (var tag in repository.TagsByDate(tip)) - { - SemanticVersion shortVersion; - if (SemanticVersion.TryParse(tag.Name, configuration.TagPrefix, out shortVersion)) - { - return BuildVersion(tip, shortVersion); - } - } - - SemanticVersion versionFromTip; - if (MergeMessageParser.TryParse(tip, configuration, out versionFromTip)) - { - var semanticVersion = BuildVersion(tip, versionFromTip); - semanticVersion.OverrideVersionManuallyIfNeeded(repository, configuration); - return semanticVersion; - } - throw new WarningException("The head of a support branch should always be a merge commit if you follow gitflow. Please create one or work around this by tagging the commit with SemVer compatible Id."); - } - - SemanticVersion BuildVersion(Commit tip, SemanticVersion shortVersion) - { - return new SemanticVersion - { - Major = shortVersion.Major, - Minor = shortVersion.Minor, - Patch = shortVersion.Patch, - BuildMetaData = new SemanticVersionBuildMetaData(null, "support", tip.Sha,tip.When()) - }; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitFlow/BranchFinders/VersionOnMasterFinder.cs b/GitVersionCore/GitFlow/BranchFinders/VersionOnMasterFinder.cs deleted file mode 100644 index 7b5033bc07..0000000000 --- a/GitVersionCore/GitFlow/BranchFinders/VersionOnMasterFinder.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace GitVersion -{ - using System; - - class VersionOnMasterFinder - { - public VersionPoint Execute(GitVersionContext context, DateTimeOffset olderThan) - { - var masterBranch = context.Repository.FindBranch("master"); - foreach (var commit in masterBranch.CommitsPriorToThan(olderThan)) - { - foreach (var tag in context.Repository.TagsByDate(commit)) - { - SemanticVersion semanticVersion; - if (SemanticVersion.TryParse(tag.Name, context.Configuration.TagPrefix, out semanticVersion)) - { - return new VersionPoint - { - Major = semanticVersion.Major, - Minor = semanticVersion.Minor, - }; - } - } - - SemanticVersion semanticVersionFromMergeMessage; - if (MergeMessageParser.TryParse(commit, context.Configuration, out semanticVersionFromMergeMessage)) - { - return new VersionPoint - { - Major = semanticVersionFromMergeMessage.Major, - Minor = semanticVersionFromMergeMessage.Minor, - }; - } - } - return new VersionPoint - { - Major = 0, - Minor = 1, - }; - } - - } -} diff --git a/GitVersionCore/GitFlow/GitFlowVersionFinder.cs b/GitVersionCore/GitFlow/GitFlowVersionFinder.cs deleted file mode 100644 index 9ba18ac429..0000000000 --- a/GitVersionCore/GitFlow/GitFlowVersionFinder.cs +++ /dev/null @@ -1,40 +0,0 @@ -namespace GitVersion -{ - public class GitFlowVersionFinder - { - public SemanticVersion FindVersion(GitVersionContext context) - { - if (context.CurrentBranch.IsMaster()) - { - return new MasterVersionFinder().FindVersion(context); - } - - if (context.CurrentBranch.IsHotfix()) - { - return new HotfixVersionFinder().FindVersion(context); - } - - if (context.CurrentBranch.IsRelease()) - { - return new ReleaseVersionFinder().FindVersion(context); - } - - if (context.CurrentBranch.IsDevelop()) - { - return new DevelopVersionFinder().FindVersion(context); - } - - if (context.CurrentBranch.IsPullRequest()) - { - return new PullVersionFinder().FindVersion(context); - } - - if (context.CurrentBranch.IsSupport()) - { - return new SupportVersionFinder().FindVersion(context.Repository, context.CurrentCommit, context.Configuration); - } - - return new FeatureVersionFinder().FindVersion(context); - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/BuildNumberCalculator.cs b/GitVersionCore/GitHubFlow/BuildNumberCalculator.cs deleted file mode 100644 index fb5d3e6b59..0000000000 --- a/GitVersionCore/GitHubFlow/BuildNumberCalculator.cs +++ /dev/null @@ -1,92 +0,0 @@ -namespace GitVersion -{ - using System; - using System.Linq; - using LibGit2Sharp; - - public class BuildNumberCalculator - { - NextSemverCalculator nextSemverCalculator; - LastTaggedReleaseFinder lastTaggedReleaseFinder; - IRepository gitRepo; - - public BuildNumberCalculator(NextSemverCalculator nextSemverCalculator, LastTaggedReleaseFinder lastTaggedReleaseFinder, IRepository gitRepo) - { - this.nextSemverCalculator = nextSemverCalculator; - this.lastTaggedReleaseFinder = lastTaggedReleaseFinder; - this.gitRepo = gitRepo; - } - - public SemanticVersion GetBuildNumber(GitVersionContext context) - { - var commitsSinceLastRelease = GetCommitsSinceLastRelease(context); - var semanticVersion = nextSemverCalculator.NextVersion(); - - // TODO Need a way of setting this in a cross cutting way - semanticVersion.BuildMetaData = new SemanticVersionBuildMetaData(commitsSinceLastRelease, context.CurrentBranch.Name, context.CurrentCommit.Sha, context.CurrentCommit.When()); - if (context.CurrentBranch.IsPullRequest()) - { - EnsurePullBranchShareACommonAncestorWithMaster(gitRepo, gitRepo.Head); - var extractIssueNumber = ExtractIssueNumber(context); - semanticVersion.PreReleaseTag = "PullRequest" + extractIssueNumber; - return semanticVersion; - } - - return semanticVersion; - } - - int GetCommitsSinceLastRelease(GitVersionContext context) - { - int commitsSinceLastRelease; - VersionTaggedCommit versionTaggedCommit; - if (lastTaggedReleaseFinder.GetVersion(out versionTaggedCommit)) - { - commitsSinceLastRelease = NumberOfCommitsOnBranchSinceCommit(context, versionTaggedCommit.Commit); - } - else - { - commitsSinceLastRelease = NumberOfCommitsOnBranchSinceCommit(context, context.CurrentBranch.Commits.Last()); - } - return commitsSinceLastRelease; - } - - int NumberOfCommitsOnBranchSinceCommit(GitVersionContext context, Commit commit) - { - var qf = new CommitFilter - { - Since = context.CurrentCommit, - Until = commit, - SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time - }; - - return context.Repository.Commits.QueryBy(qf).Count(); - } - - void EnsurePullBranchShareACommonAncestorWithMaster(IRepository repository, Branch pullBranch) - { - var masterTip = repository.FindBranch("master").Tip; - var ancestor = repository.Commits.FindMergeBase(masterTip, pullBranch.Tip); - - if (ancestor != null) - { - return; - } - - var message = string.Format("A pull request branch is expected to branch off of 'master'. However, branch 'master' and '{0}' do not share a common ancestor.", pullBranch.Name); - throw new Exception(message); - } - - string ExtractIssueNumber(GitVersionContext context) - { - var issueNumber = GitHelper.ExtractIssueNumber(context.CurrentBranch.CanonicalName); - - if (!GitHelper.LooksLikeAValidPullRequestNumber(issueNumber)) - { - var message = string.Format("Unable to extract pull request number from '{0}'.", context.CurrentBranch.CanonicalName); - throw new WarningException(message); - } - - return issueNumber; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/GitHubFlowVersionFinder.cs b/GitVersionCore/GitHubFlow/GitHubFlowVersionFinder.cs deleted file mode 100644 index 145e2d2936..0000000000 --- a/GitVersionCore/GitHubFlow/GitHubFlowVersionFinder.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace GitVersion -{ - public class GitHubFlowVersionFinder - { - public SemanticVersion FindVersion(GitVersionContext context) - { - var repositoryDirectory = context.Repository.GetRepositoryDirectory(); - var lastTaggedReleaseFinder = new LastTaggedReleaseFinder(context); - var nextVersionTxtFileFinder = new NextVersionTxtFileFinder(repositoryDirectory, context.Configuration); - var nextSemverCalculator = new NextSemverCalculator(nextVersionTxtFileFinder, lastTaggedReleaseFinder, context); - return new BuildNumberCalculator(nextSemverCalculator, lastTaggedReleaseFinder, context.Repository).GetBuildNumber(context); - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/LastTaggedReleaseFinder.cs b/GitVersionCore/GitHubFlow/LastTaggedReleaseFinder.cs deleted file mode 100644 index f913a1f670..0000000000 --- a/GitVersionCore/GitHubFlow/LastTaggedReleaseFinder.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace GitVersion -{ - using System.Linq; - using LibGit2Sharp; - - public class LastTaggedReleaseFinder - { - GitVersionContext context; - - public LastTaggedReleaseFinder(GitVersionContext context) - { - this.context = context; - } - - public bool GetVersion(out VersionTaggedCommit versionTaggedCommit) - { - var tags = context.Repository.Tags.Select(t => - { - SemanticVersion version; - if (SemanticVersion.TryParse(t.Name, context.Configuration.TagPrefix, out version)) - { - return new VersionTaggedCommit((Commit)t.Target, version); - } - return null; - }) - .Where(a => a != null) - .ToArray(); - var olderThan = context.CurrentCommit.When(); - var lastTaggedCommit = - context.CurrentBranch.Commits.FirstOrDefault(c => c.When() <= olderThan && tags.Any(a => a.Commit == c)); - - if (lastTaggedCommit != null) - { - versionTaggedCommit = tags.Last(a => a.Commit.Sha == lastTaggedCommit.Sha); - return true; - } - - versionTaggedCommit = null; - return false; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/MergedBranchesWithVersionFinder.cs b/GitVersionCore/GitHubFlow/MergedBranchesWithVersionFinder.cs deleted file mode 100644 index 07e83fd6a6..0000000000 --- a/GitVersionCore/GitHubFlow/MergedBranchesWithVersionFinder.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace GitVersion -{ - using System.Collections.Generic; - using System.Linq; - - public class MergedBranchesWithVersionFinder - { - GitVersionContext context; - - public MergedBranchesWithVersionFinder(GitVersionContext context) - { - this.context = context; - } - - public bool TryGetVersion(out SemanticVersion semanticVersion) - { - var shortVersion = GetAllVersions(context) - .OrderBy(x=>x.Major) - .ThenBy(x=>x.Minor).ThenBy(x=>x.Patch) - .LastOrDefault(); - if (shortVersion == null) - { - semanticVersion = null; - return false; - } - semanticVersion =new SemanticVersion - { - Major = shortVersion.Major, - Minor = shortVersion.Minor, - Patch = shortVersion.Patch - }; - return true; - } - - static IEnumerable GetAllVersions(GitVersionContext context) - { - foreach (var commit in context.CurrentBranch.Commits) - { - SemanticVersion version; - if (MergeMessageParser.TryParse(commit, context.Configuration, out version)) - { - yield return version; - } - } - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/NextSemverCalculator.cs b/GitVersionCore/GitHubFlow/NextSemverCalculator.cs deleted file mode 100644 index 0ef2409bea..0000000000 --- a/GitVersionCore/GitHubFlow/NextSemverCalculator.cs +++ /dev/null @@ -1,90 +0,0 @@ -namespace GitVersion -{ - using System; - using System.Collections.Generic; - using System.Linq; - - public class NextSemverCalculator - { - NextVersionTxtFileFinder nextVersionTxtFileFinder; - LastTaggedReleaseFinder lastTaggedReleaseFinder; - OtherBranchVersionFinder unknownBranchFinder; - GitVersionContext context; - MergedBranchesWithVersionFinder mergedBranchesWithVersionFinder; - - public NextSemverCalculator( - NextVersionTxtFileFinder nextVersionTxtFileFinder, - LastTaggedReleaseFinder lastTaggedReleaseFinder, - GitVersionContext context) - { - this.nextVersionTxtFileFinder = nextVersionTxtFileFinder; - this.lastTaggedReleaseFinder = lastTaggedReleaseFinder; - mergedBranchesWithVersionFinder = new MergedBranchesWithVersionFinder(context); - unknownBranchFinder = new OtherBranchVersionFinder(); - this.context = context; - } - - public SemanticVersion NextVersion() - { - return GetPossibleVersions().Max(); - } - - public IEnumerable GetPossibleVersions() - { - // always provide a minimum fallback version for other strategies - var defaultNextVersion = new SemanticVersion - { - Minor = 1 - }; - yield return defaultNextVersion; - - VersionTaggedCommit lastTaggedRelease; - if (lastTaggedReleaseFinder.GetVersion(out lastTaggedRelease)) - { - //If the exact commit is tagged then just return that commit - if (context.CurrentCommit.Sha == lastTaggedRelease.Commit.Sha) - { - yield return lastTaggedRelease.SemVer; - yield break; - } - defaultNextVersion = new SemanticVersion - { - Major = lastTaggedRelease.SemVer.Major, - Minor = lastTaggedRelease.SemVer.Minor, - Patch = lastTaggedRelease.SemVer.Patch + 1 - }; - yield return defaultNextVersion; - } - - SemanticVersion fileVersion; - var hasNextVersionTxtVersion = nextVersionTxtFileFinder.TryGetNextVersion(out fileVersion); - if (hasNextVersionTxtVersion && !string.IsNullOrEmpty(context.Configuration.NextVersion)) - { - throw new Exception("You cannot specify a next version in both NextVersion.txt and GitVersionConfig.yaml. Please delete NextVersion.txt and use GitVersionConfig.yaml"); - } - - if (!string.IsNullOrEmpty(context.Configuration.NextVersion)) - { - yield return SemanticVersion.Parse(context.Configuration.NextVersion, context.Configuration.TagPrefix); - } - - if (hasNextVersionTxtVersion) - { - yield return fileVersion; - } - - SemanticVersion tryGetVersion; - if (mergedBranchesWithVersionFinder.TryGetVersion(out tryGetVersion)) - { - yield return tryGetVersion; - } - - SemanticVersion otherBranchVersion; - if (unknownBranchFinder.FindVersion(context, defaultNextVersion, out otherBranchVersion)) - { - yield return otherBranchVersion; - } - - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/NextVersionTxtFileFinder.cs b/GitVersionCore/GitHubFlow/NextVersionTxtFileFinder.cs deleted file mode 100644 index 58b36ecfc3..0000000000 --- a/GitVersionCore/GitHubFlow/NextVersionTxtFileFinder.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace GitVersion -{ - using System; - using System.IO; - - public class NextVersionTxtFileFinder - { - string repositoryDirectory; - Config configuration; - - public NextVersionTxtFileFinder(string repositoryDirectory, Config configuration) - { - this.repositoryDirectory = repositoryDirectory; - this.configuration = configuration; - } - - public bool TryGetNextVersion(out SemanticVersion semanticVersion) - { - var filePath = Path.Combine(repositoryDirectory, "NextVersion.txt"); - if (!File.Exists(filePath)) - { - semanticVersion = null; - return false; - } - - var version = File.ReadAllText(filePath); - if (string.IsNullOrEmpty(version)) - { - semanticVersion = null; - return false; - } - - if (!SemanticVersion.TryParse(version, configuration.TagPrefix, out semanticVersion)) - { - throw new ArgumentException("Make sure you have a valid semantic version in NextVersion.txt"); - } - - return true; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/OtherBranchVersionFinder.cs b/GitVersionCore/GitHubFlow/OtherBranchVersionFinder.cs deleted file mode 100644 index 0fd3c92709..0000000000 --- a/GitVersionCore/GitHubFlow/OtherBranchVersionFinder.cs +++ /dev/null @@ -1,64 +0,0 @@ -namespace GitVersion -{ - using System; - using System.Linq; - - class OtherBranchVersionFinder - { - public bool FindVersion(GitVersionContext context, SemanticVersion defaultNextVersion, out SemanticVersion semanticVersion) - { - var versionInBranch = GetVersionInBranch(context); - if (versionInBranch == null) - { - if (!context.CurrentBranch.IsMaster()) - defaultNextVersion.PreReleaseTag = context.CurrentBranch.Name.Split('/').Last(); - semanticVersion = null; - - return false; - } - - var applicableTagsInDescendingOrder = context.Repository.SemVerTagsRelatedToVersion(context.Configuration, versionInBranch.Item2).OrderByDescending(tag => SemanticVersion.Parse(tag.Name, context.Configuration.TagPrefix)).ToList(); - var nbHotfixCommits = BranchCommitDifferenceFinder.NumberOfCommitsSinceLastTagOrBranchPoint(context, applicableTagsInDescendingOrder, BranchType.Unknown, "master"); - var semanticVersionPreReleaseTag = RecentTagVersionExtractor.RetrieveMostRecentOptionalTagVersion(context, applicableTagsInDescendingOrder) ?? CreateDefaultPreReleaseTag(context, versionInBranch.Item1); - - - if (semanticVersionPreReleaseTag.Name == "release") - { - semanticVersionPreReleaseTag.Name = context.Configuration.ReleaseBranchTag; - } - - semanticVersion = new SemanticVersion - { - Major = versionInBranch.Item2.Major, - Minor = versionInBranch.Item2.Minor, - Patch = versionInBranch.Item2.Patch, - PreReleaseTag = semanticVersionPreReleaseTag, - BuildMetaData = new SemanticVersionBuildMetaData(nbHotfixCommits, context.CurrentBranch.Name, context.CurrentCommit.Sha, context.CurrentCommit.When()) - }; - return true; - } - - Tuple GetVersionInBranch(GitVersionContext context) - { - var branchParts = context.CurrentBranch.Name.Split('/', '-'); - foreach (var part in branchParts) - { - SemanticVersion semanticVersion; - if (SemanticVersion.TryParse(part, context.Configuration.TagPrefix, out semanticVersion)) - { - return Tuple.Create(part, semanticVersion); - } - } - - return null; - } - - SemanticVersionPreReleaseTag CreateDefaultPreReleaseTag(GitVersionContext context, string versionString) - { - return context.CurrentBranch.Name - .Replace("/" + versionString, string.Empty) - .Replace("-" + versionString, string.Empty) + ".1"; - } - - } -} \ No newline at end of file diff --git a/GitVersionCore/GitHubFlow/VersionTaggedCommit.cs b/GitVersionCore/GitHubFlow/VersionTaggedCommit.cs deleted file mode 100644 index 48d5fd13eb..0000000000 --- a/GitVersionCore/GitHubFlow/VersionTaggedCommit.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace GitVersion -{ - using LibGit2Sharp; - - public class VersionTaggedCommit - { - public Commit Commit; - public SemanticVersion SemVer; - - public VersionTaggedCommit(Commit commit, SemanticVersion semVer) - { - Commit = commit; - SemVer = semVer; - } - } -} \ No newline at end of file diff --git a/GitVersionCore/GitVersionContext.cs b/GitVersionCore/GitVersionContext.cs index fc296612ab..63831f17a0 100644 --- a/GitVersionCore/GitVersionContext.cs +++ b/GitVersionCore/GitVersionContext.cs @@ -1,7 +1,9 @@ namespace GitVersion { + using System; using System.Collections.Generic; using System.Linq; + using System.Text.RegularExpressions; using LibGit2Sharp; /// @@ -9,71 +11,162 @@ /// public class GitVersionContext { + readonly Config configuration; + public GitVersionContext(IRepository repository, Config configuration, bool isForTrackingBranchOnly = true) : this(repository, repository.Head, configuration, isForTrackingBranchOnly) { - Configuration = configuration; } - public GitVersionContext(IRepository repository, Branch currentBranch, Config configuration, bool isForTrackingBranchOnly = true) + public GitVersionContext(IRepository repository, Branch currentBranch, Config configuration, bool isForTrackingBranch = true) { Repository = repository; - Configuration = configuration; - IsContextForTrackedBranchesOnly = isForTrackingBranchOnly; + this.configuration = configuration; + OnlyEvaluateTrackedBranches = isForTrackingBranch; if (currentBranch == null) - return; + throw new InvalidOperationException("Need a branch to operate on"); CurrentCommit = currentBranch.Tip; + IsCurrentCommitTagged = repository.Tags.Any(t => t.Target == CurrentCommit); - if (repository != null && currentBranch.IsDetachedHead()) + if (currentBranch.IsDetachedHead()) { - CurrentBranch = GetBranchesContainingCommit(CurrentCommit.Sha).OnlyOrDefault() ?? currentBranch; + CurrentBranch = CurrentCommit.GetBranchesContainingCommit(repository, OnlyEvaluateTrackedBranches).OnlyOrDefault() ?? currentBranch; } else { CurrentBranch = currentBranch; } + + CalculateEffectiveConfiguration(); } - public Config Configuration { get; private set; } + public bool OnlyEvaluateTrackedBranches { get; private set; } + public EffectiveConfiguration Configuration { get; private set; } public IRepository Repository { get; private set; } public Branch CurrentBranch { get; private set; } public Commit CurrentCommit { get; private set; } + public bool IsCurrentCommitTagged { get; private set; } - readonly bool IsContextForTrackedBranchesOnly = true; + void CalculateEffectiveConfiguration() + { + var currentBranchConfig = GetBranchConfiguration(CurrentBranch); + // Versioning mode drills down, if top level is specified then it takes priority + var versioningMode = configuration.VersioningMode ?? currentBranchConfig.Value.VersioningMode ?? VersioningMode.ContinuousDelivery; + + var tag = currentBranchConfig.Value.Tag ?? "useBranchName"; + var nextVersion = configuration.NextVersion; + var incrementStrategy = currentBranchConfig.Value.Increment ?? IncrementStrategy.Patch; + var preventIncrementForMergedBranchVersion = currentBranchConfig.Value.PreventIncrementOfMergedBranchVersion ?? false; + var assemblyVersioningScheme = configuration.AssemblyVersioningScheme; + var gitTagPrefix = configuration.TagPrefix; + Configuration = new EffectiveConfiguration(assemblyVersioningScheme, versioningMode, gitTagPrefix, tag, nextVersion, incrementStrategy, currentBranchConfig.Key, preventIncrementForMergedBranchVersion); + } - IEnumerable GetBranchesContainingCommit(string commitSha) + KeyValuePair GetBranchConfiguration(Branch currentBranch) { - var directBranchHasBeenFound = false; - foreach (var branch in Repository.Branches) + var matchingBranches = configuration.Branches.Where(b => Regex.IsMatch(currentBranch.Name, "^" + b.Key, RegexOptions.IgnoreCase)).ToArray(); + + if (matchingBranches.Length == 0) + { + return new KeyValuePair(string.Empty, new BranchConfig()); + } + if (matchingBranches.Length == 1) { - if (branch.Tip.Sha != commitSha || (IsContextForTrackedBranchesOnly && !branch.IsTracking)) + var keyValuePair = matchingBranches[0]; + var branchConfiguration = keyValuePair.Value; + + if (branchConfiguration.Increment == IncrementStrategy.Inherit) { - continue; + return InheritBranchConfiguration(currentBranch, keyValuePair, branchConfiguration); } - directBranchHasBeenFound = true; - yield return branch; + return keyValuePair; } - if (directBranchHasBeenFound) + const string format = "Multiple branch configurations match the current branch branchName of '{0}'. Matching configurations: '{1}'"; + throw new Exception(string.Format(format, currentBranch.Name, string.Join(", ", matchingBranches.Select(b => b.Key)))); + } + + KeyValuePair InheritBranchConfiguration(Branch currentBranch, KeyValuePair keyValuePair, BranchConfig branchConfiguration) + { + Logger.WriteInfo("Attempting to inherit branch configuration from parent branch"); + var excludedBranches = new Branch[0]; + // Check if we are a merge commit. If so likely we are a pull request + var parentCount = CurrentCommit.Parents.Count(); + if (parentCount == 2) { - yield break; + var parents = CurrentCommit.Parents.ToArray(); + var branch = Repository.Branches.SingleOrDefault(b => !b.IsRemote && b.Tip == parents[1]) ; + if (branch != null) + { + excludedBranches = new[] + { + currentBranch, + branch + }; + currentBranch = branch; + } + else + { + currentBranch = Repository.Branches.SingleOrDefault(b => !b.IsRemote && b.Tip == parents[0]) ?? currentBranch; + } + + Logger.WriteInfo("HEAD is merge commit, this is likely a pull request using " + currentBranch.Name + " as base"); } - foreach (var branch in Repository.Branches) - { - var commits = Repository.Commits.QueryBy(new CommitFilter { Since = branch }).Where(c => c.Sha == commitSha); + var branchPoint = currentBranch.FindCommitBranchWasBranchedFrom(Repository, OnlyEvaluateTrackedBranches, excludedBranches); - if (!commits.Any()) + List possibleParents; + if (branchPoint.Sha == CurrentCommit.Sha) + { + possibleParents = ListBranchesContaininingCommit(Repository, CurrentCommit.Sha, excludedBranches).Except(new[] { - continue; - } + currentBranch + }).ToList(); + } + else + { + var branches = ListBranchesContaininingCommit(Repository, branchPoint.Sha, excludedBranches).ToArray(); + var currentTipBranches = ListBranchesContaininingCommit(Repository, CurrentCommit.Sha, excludedBranches).ToArray(); + possibleParents = branches + .Except(currentTipBranches) + .ToList(); + } - yield return branch; + Logger.WriteInfo("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.Name))); + + // If it comes down to master and something, master is always first so we pick other branch + if (possibleParents.Count == 2 && possibleParents.Any(p => p.Name == "master")) + { + possibleParents.Remove(possibleParents.Single(p => p.Name == "master")); } + + if (possibleParents.Count == 1) + { + return new KeyValuePair( + keyValuePair.Key, + new BranchConfig(branchConfiguration) + { + Increment = GetBranchConfiguration(possibleParents[0]).Value.Increment + }); + } + + if (possibleParents.Count == 0) + throw new Exception("Failed to inherit Increment branch configuration, no branches found"); + + throw new Exception("Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.Name))); + } + + static IEnumerable ListBranchesContaininingCommit(IRepository repo, string commitSha, Branch[] excludedBranches) + { + return from branch in repo.Branches.Except(excludedBranches) + where !branch.IsRemote + let commits = repo.Commits.QueryBy(new CommitFilter { Since = branch }).Where(c => c.Sha == commitSha) + where commits.Any() + select branch; } } } \ No newline at end of file diff --git a/GitVersionCore/GitVersionCore.csproj b/GitVersionCore/GitVersionCore.csproj index fb4eea75ed..d43fd97433 100644 --- a/GitVersionCore/GitVersionCore.csproj +++ b/GitVersionCore/GitVersionCore.csproj @@ -71,39 +71,44 @@ + - + + + + + - + + + - + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - @@ -114,7 +119,6 @@ - @@ -122,7 +126,6 @@ - @@ -134,6 +137,7 @@ + diff --git a/GitVersionCore/GitVersionFinder.cs b/GitVersionCore/GitVersionFinder.cs index 418c934ec7..78431981b8 100644 --- a/GitVersionCore/GitVersionFinder.cs +++ b/GitVersionCore/GitVersionFinder.cs @@ -1,6 +1,9 @@ namespace GitVersion { + using System; + using System.IO; using System.Linq; + using GitVersion.VersionCalculation; using LibGit2Sharp; public class GitVersionFinder @@ -10,19 +13,13 @@ public SemanticVersion FindVersion(GitVersionContext context) Logger.WriteInfo("Running against branch: " + context.CurrentBranch.Name); EnsureMainTopologyConstraints(context); - if (ShouldGitHubFlowVersioningSchemeApply(context.Repository)) + var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt"); + if (File.Exists(filePath)) { - Logger.WriteInfo("GitHubFlow version strategy will be used"); - return new GitHubFlowVersionFinder().FindVersion(context); + throw new Exception("NextVersion.txt has been depreciated. See https://github.com/ParticularLabs/GitVersion/wiki/GitVersionConfig.yaml-Configuration-File for replacement"); } - Logger.WriteInfo("GitFlow version strategy will be used"); - return new GitFlowVersionFinder().FindVersion(context); - } - - static bool ShouldGitHubFlowVersioningSchemeApply(IRepository repo) - { - return repo.FindBranch("develop") == null; + return new NewNextVersionCalculator().FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) diff --git a/GitVersionExe/ProcessHelper.cs b/GitVersionCore/Helpers/ProcessHelper.cs similarity index 98% rename from GitVersionExe/ProcessHelper.cs rename to GitVersionCore/Helpers/ProcessHelper.cs index 77822bff81..9d1a231c3e 100644 --- a/GitVersionExe/ProcessHelper.cs +++ b/GitVersionCore/Helpers/ProcessHelper.cs @@ -1,4 +1,4 @@ -namespace GitVersion +namespace GitVersion.Helpers { using System; using System.Collections.Generic; @@ -7,7 +7,7 @@ namespace GitVersion using System.Runtime.InteropServices; using System.Threading; - static class ProcessHelper + public static class ProcessHelper { static volatile object lockObject = new object(); diff --git a/GitVersionCore/LastMinorVersionFinder.cs b/GitVersionCore/LastMinorVersionFinder.cs deleted file mode 100644 index e92ca41522..0000000000 --- a/GitVersionCore/LastMinorVersionFinder.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Linq; -using LibGit2Sharp; - -namespace GitVersion -{ - using System; - using System.Collections.Generic; - - public class LastMinorVersionFinder - { - public static DateTimeOffset Execute(IRepository repo, Config configuration, Commit commit) - { - // Release/Develop = current - // Hotfix/Master/Support = walk back current branch until previous commits till a merge commit (or tag) has a patch with a 0 - if ( - repo.Head.IsMaster() || - repo.Head.IsHotfix() || - repo.Head.IsSupport() - ) - { - var fromTag = GetTimeStampFromTag(repo, configuration, commit); - - if (fromTag != DateTimeOffset.MinValue) - { - return fromTag; - } - } - return commit.When(); - } - - - static DateTimeOffset GetTimeStampFromTag(IRepository repository, Config configuration, Commit targetCommit) - { - var allMajorMinorTags = repository.Tags - .Where(x => SemanticVersion.Parse(x.Name, configuration.TagPrefix).Patch == 0) - .ToDictionary(x => x.PeeledTarget(), x => x); - var olderThan = targetCommit.When(); - foreach (var commit in repository.Head.Commits.Where(x => x.When() <= olderThan)) - { - if (IsMajorMinor(commit, allMajorMinorTags, configuration)) - { - return commit.When(); - } - } - return DateTimeOffset.MinValue; - } - - static bool IsMajorMinor(Commit commit, Dictionary allMajorMinorTags, Config configuration) - { - SemanticVersion version; - if (MergeMessageParser.TryParse(commit, configuration, out version)) - { - if (version.Patch == 0) - { - return true; - } - } - return allMajorMinorTags.ContainsKey(commit); - } - } -} \ No newline at end of file diff --git a/GitVersionCore/LibGitExtensions.cs b/GitVersionCore/LibGitExtensions.cs index b91357c8b1..ebe289f8e4 100644 --- a/GitVersionCore/LibGitExtensions.cs +++ b/GitVersionCore/LibGitExtensions.cs @@ -24,6 +24,46 @@ public static Branch FindBranch(this IRepository repository, string branchName) return repository.Branches.FirstOrDefault(x => x.Name == "origin/" + branchName); } + public static Commit FindCommitBranchWasBranchedFrom(this Branch branch, IRepository repository, bool onlyTrackedBranches, params Branch[] excludedBranches) + { + var currentBranches = branch.Tip.GetBranchesContainingCommit(repository, onlyTrackedBranches).ToList(); + var tips = repository.Branches.Except(excludedBranches).Where(b => b != branch && !b.IsRemote).Select(b => b.Tip).ToList(); + var branchPoint = branch.Commits.FirstOrDefault(c => tips.Contains(c) || c.GetBranchesContainingCommit(repository, onlyTrackedBranches).Count() > currentBranches.Count); + return branchPoint ?? branch.Tip; + } + + public static IEnumerable GetBranchesContainingCommit(this Commit commit, IRepository repository, bool onlyTrackedBranches) + { + var directBranchHasBeenFound = false; + foreach (var branch in repository.Branches) + { + if (branch.Tip.Sha != commit.Sha || (onlyTrackedBranches && !branch.IsTracking)) + { + continue; + } + + directBranchHasBeenFound = true; + yield return branch; + } + + if (directBranchHasBeenFound) + { + yield break; + } + + foreach (var branch in repository.Branches) + { + var commits = repository.Commits.QueryBy(new CommitFilter { Since = branch }).Where(c => c.Sha == commit.Sha); + + if (!commits.Any()) + { + continue; + } + + yield return branch; + } + } + public static IEnumerable TagsByDate(this IRepository repository, Commit commit) { return repository.Tags @@ -39,12 +79,12 @@ public static IEnumerable TagsByDate(this IRepository repository, Commit co }); } - public static IEnumerable SemVerTagsRelatedToVersion(this IRepository repository, Config configuration, SemanticVersion version) + public static IEnumerable SemVerTagsRelatedToVersion(this IRepository repository, EffectiveConfiguration configuration, SemanticVersion version) { foreach (var tag in repository.Tags) { SemanticVersion tagVersion; - if (SemanticVersion.TryParse(tag.Name, configuration.TagPrefix, out tagVersion)) + if (SemanticVersion.TryParse(tag.Name, configuration.GitTagPrefix, out tagVersion)) { if (version.Major == tagVersion.Major && version.Minor == tagVersion.Minor && diff --git a/GitVersionCore/MergeMessageParser.cs b/GitVersionCore/MergeMessageParser.cs index c3ff90b209..a477a4da27 100644 --- a/GitVersionCore/MergeMessageParser.cs +++ b/GitVersionCore/MergeMessageParser.cs @@ -6,14 +6,14 @@ namespace GitVersion static class MergeMessageParser { - public static bool TryParse(Commit mergeCommit, Config configuration, out SemanticVersion shortVersion) + public static bool TryParse(Commit mergeCommit, EffectiveConfiguration configuration, out SemanticVersion semanticVersion) { string versionPart; if (Inner(mergeCommit, out versionPart)) { - return SemanticVersion.TryParse(versionPart, configuration.TagPrefix, out shortVersion); + return SemanticVersion.TryParse(versionPart, configuration.GitTagPrefix, out semanticVersion); } - shortVersion = null; + semanticVersion = null; return false; } diff --git a/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs b/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs index e5994075be..989cf8389f 100644 --- a/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs +++ b/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs @@ -4,11 +4,11 @@ public static class BuildOutputFormatter { - public static IEnumerable GenerateBuildLogOutput(SemanticVersion semanticVersion, IBuildServer buildServer) + public static IEnumerable GenerateBuildLogOutput(IBuildServer buildServer, VersionVariables variables) { var output = new List(); - foreach (var variable in VariableProvider.GetVariablesFor(semanticVersion, new Config())) + foreach (var variable in variables) { output.AddRange(buildServer.GenerateSetParameterMessage(variable.Key, variable.Value)); } diff --git a/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs b/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs index 583d2e7595..f9204c1db2 100644 --- a/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs +++ b/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs @@ -1,12 +1,11 @@ namespace GitVersion { - using System.Collections.Generic; using System.Linq; using System.Text; public static class JsonOutputFormatter { - public static string ToJson(Dictionary variables) + public static string ToJson(VersionVariables variables) { var builder = new StringBuilder(); builder.AppendLine("{"); diff --git a/GitVersionCore/OutputVariables/CiFeedFormatter.cs b/GitVersionCore/OutputVariables/CiFeedFormatter.cs deleted file mode 100644 index e69d45064c..0000000000 --- a/GitVersionCore/OutputVariables/CiFeedFormatter.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace GitVersion -{ - using System; - - public class CiFeedFormatter : IFormatProvider, ICustomFormatter - { - public object GetFormat(Type formatType) - { - if (formatType == typeof(SemanticVersion)) - return this; - - return null; - } - - public string Format(string format, object arg, IFormatProvider formatProvider) - { - var semanticVersion = (SemanticVersion) arg; - - switch (format) - { - case "s": - case "sp": - case "f": - case "fp": - return string.Format("{0}.{1}{2}", semanticVersion.ToString("j"), - semanticVersion.BuildMetaData.CommitsSinceTag ?? 0, - semanticVersion.PreReleaseTag.HasTag() ? "-" + semanticVersion.PreReleaseTag.Name: null); - default: - return semanticVersion.ToString(format); - } - } - } -} \ No newline at end of file diff --git a/GitVersionCore/OutputVariables/CommitsAsFourthVersionPartFormatter.cs b/GitVersionCore/OutputVariables/CommitsAsFourthVersionPartFormatter.cs new file mode 100644 index 0000000000..5a6af3787e --- /dev/null +++ b/GitVersionCore/OutputVariables/CommitsAsFourthVersionPartFormatter.cs @@ -0,0 +1,30 @@ +namespace GitVersion +{ + using System; + + public class CommitsAsFourthVersionPartFormatter : IFormatProvider, ICustomFormatter + { + public object GetFormat(Type formatType) + { + if (formatType == typeof(SemanticVersion)) + return this; + + return null; + } + + public string Format(string format, object arg, IFormatProvider formatProvider) + { + var semanticVersion = (SemanticVersion)arg; + var metaData = new SemanticVersionBuildMetaData(semanticVersion.BuildMetaData) + { + CommitsSinceTag = null + }.ToString(format.ToLower() == "i" ? "f" : null); + + return string.Format("{0}.{1}{2}{3}", + semanticVersion.ToString("j"), + semanticVersion.BuildMetaData.CommitsSinceTag, + semanticVersion.PreReleaseTag.HasTag() ? "-" + semanticVersion.PreReleaseTag.ToString(format) : string.Empty, + !string.IsNullOrEmpty(metaData) ? "+" + metaData : string.Empty); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/OutputVariables/VariableProvider.cs b/GitVersionCore/OutputVariables/VariableProvider.cs index 1ffd3feb8f..544fff726b 100644 --- a/GitVersionCore/OutputVariables/VariableProvider.cs +++ b/GitVersionCore/OutputVariables/VariableProvider.cs @@ -1,70 +1,47 @@ namespace GitVersion { using System; - using System.Collections.Generic; public static class VariableProvider { - public const string Major = "Major"; - public const string Minor = "Minor"; - public const string Patch = "Patch"; - public const string BuildMetaData = "BuildMetaData"; - public const string FullBuildMetaData = "FullBuildMetaData"; - public const string BranchName = "BranchName"; - public const string Sha = "Sha"; - public const string MajorMinorPatch = "MajorMinorPatch"; - public const string SemVer = "SemVer"; - public const string LegacySemVer = "LegacySemVer"; - public const string LegacySemVerPadded = "LegacySemVerPadded"; - public const string FullSemVer = "FullSemVer"; - public const string AssemblySemVer = "AssemblySemVer"; - public const string AssemblyFileSemVer = "AssemblyFileSemVer"; - public const string ClassicVersion = "ClassicVersion"; - public const string ClassicVersionWithTag = "ClassicVersionWithTag"; - public const string PreReleaseTag = "PreReleaseTag"; - public const string PreReleaseTagWithDash = "PreReleaseTagWithDash"; - public const string InformationalVersion = "InformationalVersion"; - public const string OriginalRelease = "OriginalRelease"; - - // Synonyms - public const string NuGetVersionV2 = "NuGetVersionV2"; - public const string NuGetVersionV3 = "NuGetVersionV3"; - public const string NuGetVersion = "NuGetVersion"; - - public static Dictionary GetVariablesFor(SemanticVersion semanticVersion, Config configuration) + public static VersionVariables GetVariablesFor(SemanticVersion semanticVersion, AssemblyVersioningScheme assemblyVersioningScheme, VersioningMode mode) { var bmd = semanticVersion.BuildMetaData; - var formatter = bmd.Branch == "develop" ? new CiFeedFormatter() : null; - - var variables = new Dictionary(StringComparer.InvariantCultureIgnoreCase) + IFormatProvider formatProvider = null; + if (mode == VersioningMode.ContinuousDeployment) { - {Major, semanticVersion.Major.ToString()}, - {Minor, semanticVersion.Minor.ToString()}, - {Patch, semanticVersion.Patch.ToString()}, - {PreReleaseTag, semanticVersion.PreReleaseTag}, - {PreReleaseTagWithDash, semanticVersion.PreReleaseTag.HasTag() ? "-" + semanticVersion.PreReleaseTag : null}, - {BuildMetaData, bmd}, - {FullBuildMetaData, bmd.ToString("f")}, - {MajorMinorPatch, string.Format("{0}.{1}.{2}", semanticVersion.Major, semanticVersion.Minor, semanticVersion.Patch)}, - {SemVer, semanticVersion.ToString(null, formatter)}, - {LegacySemVer, semanticVersion.ToString("l", formatter)}, - {LegacySemVerPadded, semanticVersion.ToString("lp", formatter)}, - {AssemblySemVer, semanticVersion.GetAssemblyVersion(configuration.AssemblyVersioningScheme)}, - {AssemblyFileSemVer, semanticVersion.GetAssemblyFileVersion(configuration.AssemblyVersioningScheme)}, - {FullSemVer, semanticVersion.ToString("f", formatter)}, - {InformationalVersion, semanticVersion.ToString("i", formatter)}, - {ClassicVersion, string.Format("{0}.{1}", semanticVersion.ToString("j"), (bmd.CommitsSinceTag ?? 0))}, - {ClassicVersionWithTag, string.Format("{0}.{1}{2}", semanticVersion.ToString("j"), - bmd.CommitsSinceTag ?? 0, - semanticVersion.PreReleaseTag.HasTag() ? "-" + semanticVersion.PreReleaseTag : null)}, - {BranchName, bmd.Branch}, - {Sha, bmd.Sha}, - }; + // For continuous deployment the commits since tag gets promoted to the pre-release number + semanticVersion = new SemanticVersion(semanticVersion); + if (semanticVersion.PreReleaseTag.HasTag()) + { + var oldPreReleaseNumber = semanticVersion.PreReleaseTag.Number; + semanticVersion.PreReleaseTag.Number = semanticVersion.BuildMetaData.CommitsSinceTag; + semanticVersion.BuildMetaData.CommitsSinceTag = oldPreReleaseNumber; + } + else + { + // When there is no pre-release tag we will make the version a 4 part number + formatProvider = new CommitsAsFourthVersionPartFormatter(); + } + } - // Use ToLower() to fix a bug where Beta and beta are different in NuGet - variables[NuGetVersionV2] = variables[LegacySemVerPadded].ToLower(); - //variables[NuGetVersionV3] = variables[LegacySemVerPadded].ToLower(); // TODO: when v3 is released, determine what to use - variables[NuGetVersion] = variables[NuGetVersionV2]; + var variables = new VersionVariables( + major: semanticVersion.Major.ToString(), + minor: semanticVersion.Minor.ToString(), + patch: semanticVersion.Patch.ToString(), + preReleaseTag: semanticVersion.PreReleaseTag, + preReleaseTagWithDash: semanticVersion.PreReleaseTag.HasTag() ? "-" + semanticVersion.PreReleaseTag : null, + buildMetaData: bmd, + fullBuildMetaData: bmd.ToString("f"), + majorMinorPatch: string.Format("{0}.{1}.{2}", semanticVersion.Major, semanticVersion.Minor, semanticVersion.Patch), + semVer: semanticVersion.ToString(null, formatProvider), + legacySemVer: semanticVersion.ToString("l", formatProvider), + legacySemVerPadded: semanticVersion.ToString("lp", formatProvider), + assemblySemVer: semanticVersion.GetAssemblyVersion(assemblyVersioningScheme), + fullSemVer: semanticVersion.ToString("f", formatProvider), + informationalVersion: semanticVersion.ToString("i", formatProvider), + branchName: bmd.Branch, + sha: bmd.Sha); return variables; } diff --git a/GitVersionCore/OutputVariables/VersionVariables.cs b/GitVersionCore/OutputVariables/VersionVariables.cs new file mode 100644 index 0000000000..d1f4254f7e --- /dev/null +++ b/GitVersionCore/OutputVariables/VersionVariables.cs @@ -0,0 +1,93 @@ +namespace GitVersion +{ + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + public class VersionVariables : IEnumerable> + { + public VersionVariables(string major, string minor, string patch, string buildMetaData, string fullBuildMetaData, string branchName, string sha, string majorMinorPatch, string semVer, string legacySemVer, string legacySemVerPadded, string fullSemVer, string assemblySemVer, string preReleaseTag, string preReleaseTagWithDash, string informationalVersion) + { + Major = major; + Minor = minor; + Patch = patch; + BuildMetaData = buildMetaData; + FullBuildMetaData = fullBuildMetaData; + BranchName = branchName; + Sha = sha; + MajorMinorPatch = majorMinorPatch; + SemVer = semVer; + LegacySemVer = legacySemVer; + LegacySemVerPadded = legacySemVerPadded; + FullSemVer = fullSemVer; + AssemblySemVer = assemblySemVer; + PreReleaseTag = preReleaseTag; + PreReleaseTagWithDash = preReleaseTagWithDash; + InformationalVersion = informationalVersion; + } + + public string Major { get; private set; } + public string Minor { get; private set; } + public string Patch { get; private set; } + public string PreReleaseTag { get; private set; } + public string PreReleaseTagWithDash { get; private set; } + public string BuildMetaData { get; private set; } + public string FullBuildMetaData { get; private set; } + public string MajorMinorPatch { get; private set; } + public string SemVer { get; private set; } + public string LegacySemVer { get; private set; } + public string LegacySemVerPadded { get; private set; } + public string AssemblySemVer { get; private set; } + public string FullSemVer { get; private set; } + public string InformationalVersion { get; private set; } + public string BranchName { get; private set; } + public string Sha { get; private set; } + + // Synonyms + // TODO When NuGet 3 is released: public string NuGetVersionV3 { get { return ??; } } + public string NuGetVersionV2 { get { return LegacySemVerPadded.ToLower(); } } + public string NuGetVersion { get { return NuGetVersionV2; } } + + public IEnumerable AvailableVariables + { + get { return typeof(VersionVariables).GetProperties().Select(p => p.Name).OrderBy(a => a); } + } + + public IEnumerator> GetEnumerator() + { + var type = typeof(string); + return typeof(VersionVariables) + .GetProperties() + .Where(p => p.PropertyType == type && !p.GetIndexParameters().Any()) + .Select(p => new KeyValuePair(p.Name, (string) p.GetValue(this, null))) + .GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public string this [string variable] + { + get { return (string) typeof(VersionVariables).GetProperty(variable).GetValue(this, null); } + } + + public bool TryGetValue(string variable, out string variableValue) + { + if (ContainsKey(variable)) + { + variableValue = this[variable]; + return true; + } + + variableValue = null; + return false; + } + + public bool ContainsKey(string variable) + { + return typeof(VersionVariables).GetProperty(variable) != null; + } + } +} \ No newline at end of file diff --git a/GitVersionCore/SemanticVersion.cs b/GitVersionCore/SemanticVersion.cs index d52a0adad3..0877a3b87b 100644 --- a/GitVersionCore/SemanticVersion.cs +++ b/GitVersionCore/SemanticVersion.cs @@ -17,12 +17,25 @@ public class SemanticVersion : IFormattable, IComparable public SemanticVersionPreReleaseTag PreReleaseTag; public SemanticVersionBuildMetaData BuildMetaData; - public SemanticVersion() + public SemanticVersion(int major = 0, int minor = 0, int patch = 0) { + Major = major; + Minor = minor; + Patch = patch; PreReleaseTag = new SemanticVersionPreReleaseTag(); BuildMetaData = new SemanticVersionBuildMetaData(); } + public SemanticVersion(SemanticVersion semanticVersion) + { + Major = semanticVersion.Major; + Minor = semanticVersion.Minor; + Patch = semanticVersion.Patch; + + PreReleaseTag = new SemanticVersionPreReleaseTag(semanticVersion.PreReleaseTag); + BuildMetaData = new SemanticVersionBuildMetaData(semanticVersion.BuildMetaData); + } + public bool Equals(SemanticVersion obj) { if (obj == null) diff --git a/GitVersionCore/SemanticVersionBuildMetaData.cs b/GitVersionCore/SemanticVersionBuildMetaData.cs index b3db9d8e2a..68776a6914 100644 --- a/GitVersionCore/SemanticVersionBuildMetaData.cs +++ b/GitVersionCore/SemanticVersionBuildMetaData.cs @@ -22,14 +22,23 @@ public SemanticVersionBuildMetaData() { } - public SemanticVersionBuildMetaData(int? commitsSinceTag, string branch, string commitSha,DateTimeOffset commitDate) + public SemanticVersionBuildMetaData(int? commitsSinceTag, string branch, string commitSha, DateTimeOffset commitDate, string otherMetadata = null) { Sha = commitSha; CommitsSinceTag = commitsSinceTag; Branch = branch; CommitDate = commitDate; + OtherMetaData = otherMetadata; } + public SemanticVersionBuildMetaData(SemanticVersionBuildMetaData buildMetaData) + { + Sha = buildMetaData.Sha; + CommitsSinceTag = buildMetaData.CommitsSinceTag; + Branch = buildMetaData.Branch; + CommitDate = buildMetaData.CommitDate; + OtherMetaData = buildMetaData.OtherMetaData; + } public override bool Equals(object obj) { diff --git a/GitVersionCore/SemanticVersionExtensions.cs b/GitVersionCore/SemanticVersionExtensions.cs index 0cf71f9653..5780f97c0d 100644 --- a/GitVersionCore/SemanticVersionExtensions.cs +++ b/GitVersionCore/SemanticVersionExtensions.cs @@ -4,11 +4,10 @@ public static class SemanticVersionExtensions { - public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, IRepository repository, Config configuration) + public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, IRepository repository, EffectiveConfiguration configuration) { - var nextVersionTxtFileFinder = new NextVersionTxtFileFinder(repository.GetRepositoryDirectory(), configuration); - SemanticVersion manualNextVersion ; - if (nextVersionTxtFileFinder.TryGetNextVersion(out manualNextVersion)) + SemanticVersion manualNextVersion; + if (!string.IsNullOrEmpty(configuration.NextVersion) && SemanticVersion.TryParse(configuration.NextVersion, configuration.GitTagPrefix, out manualNextVersion)) { if (manualNextVersion > version) { diff --git a/GitVersionCore/SemanticVersionPreReleaseTag.cs b/GitVersionCore/SemanticVersionPreReleaseTag.cs index f24b0a13f9..a0f1b6a593 100644 --- a/GitVersionCore/SemanticVersionPreReleaseTag.cs +++ b/GitVersionCore/SemanticVersionPreReleaseTag.cs @@ -18,6 +18,13 @@ public SemanticVersionPreReleaseTag(string name, int? number) Name = name; Number = number; } + + public SemanticVersionPreReleaseTag(SemanticVersionPreReleaseTag preReleaseTag) + { + Name = preReleaseTag.Name; + Number = preReleaseTag.Number; + } + public string Name { get; set; } public int? Number { get; set; } diff --git a/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs b/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs new file mode 100644 index 0000000000..5ad6897f0d --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs @@ -0,0 +1,46 @@ +namespace GitVersion.VersionCalculation +{ + using System.Linq; + using BaseVersionCalculators; + + public class BaseVersionCalculator : IBaseVersionCalculator + { + readonly BaseVersionStrategy[] strategies; + + public BaseVersionCalculator(params BaseVersionStrategy[] strategies) + { + this.strategies = strategies; + } + + public BaseVersion GetBaseVersion(GitVersionContext context) + { + Logger.WriteInfo("Base Versions:"); + + var baseVersion = strategies + .Select(s => s.GetVersion(context)) + .Where(v => + { + if (v != null) + { + Logger.WriteInfo(v.ToString()); + return true; + } + + return false; + }) + .Aggregate((v1, v2) => + { + if (v1.SemanticVersion > v2.SemanticVersion) + { + return new BaseVersion(v1.Source, v1.ShouldIncrement, v1.ShouldUpdateTag, v1.SemanticVersion, v1.BaseVersionSource ?? v2.BaseVersionSource, v1.BranchNameOverride); + } + + return new BaseVersion(v2.Source, v2.ShouldIncrement, v2.ShouldUpdateTag, v2.SemanticVersion, v2.BaseVersionSource ?? v1.BaseVersionSource, v2.BranchNameOverride); + }); + + Logger.WriteInfo(string.Format("Base version used: {0}", baseVersion)); + + return baseVersion; + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs b/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs new file mode 100644 index 0000000000..3ecf755580 --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs @@ -0,0 +1,34 @@ +namespace GitVersion.VersionCalculation.BaseVersionCalculators +{ + using LibGit2Sharp; + + public class BaseVersion + { + public BaseVersion(string source, bool shouldIncrement, bool shouldUpdateTag, SemanticVersion semanticVersion, Commit baseVersionSource, string branchNameOverride) + { + Source = source; + ShouldIncrement = shouldIncrement; + ShouldUpdateTag = shouldUpdateTag; + SemanticVersion = semanticVersion; + BaseVersionSource = baseVersionSource; + BranchNameOverride = branchNameOverride; + } + + public string Source { get; private set; } + + public bool ShouldIncrement { get; private set; } + + public bool ShouldUpdateTag { get; private set; } + + public SemanticVersion SemanticVersion { get; private set; } + + public Commit BaseVersionSource { get; private set; } + + public string BranchNameOverride { get; private set; } + + public override string ToString() + { + return string.Format("{0}: {1} from commit {2}", Source, SemanticVersion.ToString("f"), BaseVersionSource == null ? "External Source" : BaseVersionSource.Sha); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionBaseVersionStrategy.cs b/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionBaseVersionStrategy.cs new file mode 100644 index 0000000000..8c5c99da2e --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionBaseVersionStrategy.cs @@ -0,0 +1,13 @@ +namespace GitVersion.VersionCalculation.BaseVersionCalculators +{ + public class ConfigNextVersionBaseVersionStrategy : BaseVersionStrategy + { + public override BaseVersion GetVersion(GitVersionContext context) + { + if (string.IsNullOrEmpty(context.Configuration.NextVersion) || context.IsCurrentCommitTagged) + return null; + var semanticVersion = SemanticVersion.Parse(context.Configuration.NextVersion, context.Configuration.GitTagPrefix); + return new BaseVersion("NextVersion in GitVersionConfig.yaml", false, true, semanticVersion, null, null); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/BaseVersionCalculators/LastTagBaseVersionStrategy.cs b/GitVersionCore/VersionCalculation/BaseVersionCalculators/LastTagBaseVersionStrategy.cs new file mode 100644 index 0000000000..29fe2b7e03 --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionCalculators/LastTagBaseVersionStrategy.cs @@ -0,0 +1,61 @@ +namespace GitVersion.VersionCalculation.BaseVersionCalculators +{ + using System.Linq; + using LibGit2Sharp; + + public class LastTagBaseVersionStrategy : BaseVersionStrategy + { + public override BaseVersion GetVersion(GitVersionContext context) + { + VersionTaggedCommit version; + if (GetVersion(context, out version)) + { + var shouldUpdateVersion = version.Commit.Sha != context.CurrentCommit.Sha; + return new BaseVersion(string.Format("Git tag '{0}'", version.Tag), shouldUpdateVersion, shouldUpdateVersion, version.SemVer, version.Commit, null); + } + + return null; + } + + bool GetVersion(GitVersionContext context, out VersionTaggedCommit versionTaggedCommit) + { + var tags = context.Repository.Tags.Select(t => + { + SemanticVersion version; + if (SemanticVersion.TryParse(t.Name, context.Configuration.GitTagPrefix, out version)) + { + return new VersionTaggedCommit((Commit)t.Target, version, t.Name); + } + return null; + }) + .Where(a => a != null) + .ToArray(); + var olderThan = context.CurrentCommit.When(); + var lastTaggedCommit = + context.CurrentBranch.Commits.FirstOrDefault(c => c.When() <= olderThan && tags.Any(a => a.Commit == c)); + + if (lastTaggedCommit != null) + { + versionTaggedCommit = tags.Last(a => a.Commit.Sha == lastTaggedCommit.Sha); + return true; + } + + versionTaggedCommit = null; + return false; + } + + class VersionTaggedCommit + { + public string Tag; + public Commit Commit; + public SemanticVersion SemVer; + + public VersionTaggedCommit(Commit commit, SemanticVersion semVer, string tag) + { + Tag = tag; + Commit = commit; + SemVer = semVer; + } + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs b/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs new file mode 100644 index 0000000000..39e74e1f87 --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs @@ -0,0 +1,31 @@ +namespace GitVersion.VersionCalculation.BaseVersionCalculators +{ + using System.Linq; + + public class MergeMessageBaseVersionStrategy : BaseVersionStrategy + { + public override BaseVersion GetVersion(GitVersionContext context) + { + var commitsPriorToThan = context.CurrentBranch + .CommitsPriorToThan(context.CurrentCommit.When()); + var baseVersions = commitsPriorToThan + .SelectMany(c => + { + SemanticVersion semanticVersion; + // TODO when this approach works, inline the other class into here + if (MergeMessageParser.TryParse(c, context.Configuration, out semanticVersion)) + { + var shouldIncrement = !context.Configuration.PreventIncrementForMergedBranchVersion; + return new[] + { + new BaseVersion(string.Format("Merge message '{0}'", c.Message.Trim()), shouldIncrement, true, semanticVersion, c, null) + }; + } + return Enumerable.Empty(); + }) + .ToArray(); + + return baseVersions.Length > 1 ? baseVersions.Aggregate((x, y) => x.SemanticVersion > y.SemanticVersion ? x : y) : baseVersions.SingleOrDefault(); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchBaseVersionStrategy.cs b/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchBaseVersionStrategy.cs new file mode 100644 index 0000000000..5cbf22cc83 --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchBaseVersionStrategy.cs @@ -0,0 +1,35 @@ +namespace GitVersion.VersionCalculation.BaseVersionCalculators +{ + using System; + + public class VersionInBranchBaseVersionStrategy : BaseVersionStrategy + { + public override BaseVersion GetVersion(GitVersionContext context) + { + var versionInBranch = GetVersionInBranch(context); + if (versionInBranch != null) + { + var commitBranchWasBranchedFrom = context.CurrentBranch.FindCommitBranchWasBranchedFrom(context.Repository, context.OnlyEvaluateTrackedBranches); + var branchNameOverride = context.CurrentBranch.Name.RegexReplace("[-/]" + versionInBranch.Item1, string.Empty); + return new BaseVersion("Version in branch name", false, true, versionInBranch.Item2, commitBranchWasBranchedFrom, branchNameOverride); + } + + return null; + } + + Tuple GetVersionInBranch(GitVersionContext context) + { + var branchParts = context.CurrentBranch.Name.Split('/', '-'); + foreach (var part in branchParts) + { + SemanticVersion semanticVersion; + if (SemanticVersion.TryParse(part, context.Configuration.GitTagPrefix, out semanticVersion)) + { + return Tuple.Create(part, semanticVersion); + } + } + + return null; + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/BaseVersionStrategy.cs b/GitVersionCore/VersionCalculation/BaseVersionStrategy.cs new file mode 100644 index 0000000000..855d4cbc3a --- /dev/null +++ b/GitVersionCore/VersionCalculation/BaseVersionStrategy.cs @@ -0,0 +1,9 @@ +namespace GitVersion.VersionCalculation +{ + using GitVersion.VersionCalculation.BaseVersionCalculators; + + public abstract class BaseVersionStrategy + { + public abstract BaseVersion GetVersion(GitVersionContext context); + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/FallbackBaseVersionStrategy.cs b/GitVersionCore/VersionCalculation/FallbackBaseVersionStrategy.cs new file mode 100644 index 0000000000..f6aa89897a --- /dev/null +++ b/GitVersionCore/VersionCalculation/FallbackBaseVersionStrategy.cs @@ -0,0 +1,13 @@ +namespace GitVersion.VersionCalculation +{ + using System.Linq; + using GitVersion.VersionCalculation.BaseVersionCalculators; + + public class FallbackBaseVersionStrategy : BaseVersionStrategy + { + public override BaseVersion GetVersion(GitVersionContext context) + { + return new BaseVersion("Fallback base version", false, true, new SemanticVersion(minor: 1), context.CurrentBranch.Commits.Last(), null); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/IBaseVersionCalculator.cs b/GitVersionCore/VersionCalculation/IBaseVersionCalculator.cs new file mode 100644 index 0000000000..b6e8f3d67a --- /dev/null +++ b/GitVersionCore/VersionCalculation/IBaseVersionCalculator.cs @@ -0,0 +1,9 @@ +namespace GitVersion.VersionCalculation +{ + using GitVersion.VersionCalculation.BaseVersionCalculators; + + public interface IBaseVersionCalculator + { + BaseVersion GetBaseVersion(GitVersionContext context); + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs b/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs new file mode 100644 index 0000000000..967baf8528 --- /dev/null +++ b/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs @@ -0,0 +1,9 @@ +namespace GitVersion.VersionCalculation +{ + using LibGit2Sharp; + + public interface IMetaDataCalculator + { + SemanticVersionBuildMetaData Create(Commit baseVersionSource, GitVersionContext context); + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/MetaDataCalculator.cs b/GitVersionCore/VersionCalculation/MetaDataCalculator.cs new file mode 100644 index 0000000000..37bfdde0d3 --- /dev/null +++ b/GitVersionCore/VersionCalculation/MetaDataCalculator.cs @@ -0,0 +1,27 @@ +namespace GitVersion.VersionCalculation +{ + using System.Linq; + using LibGit2Sharp; + + public class MetaDataCalculator : IMetaDataCalculator + { + public SemanticVersionBuildMetaData Create(Commit baseVersionSource, GitVersionContext context) + { + var qf = new CommitFilter + { + Since = context.CurrentCommit, + Until = baseVersionSource, + SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time + }; + + var commitLog = context.Repository.Commits.QueryBy(qf); + var commitsSinceTag = commitLog.Count(); + + return new SemanticVersionBuildMetaData( + commitsSinceTag, + context.CurrentBranch.Name, + context.CurrentCommit.Sha, + context.CurrentCommit.When()); + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersionCalculation/NewNextVersionCalculator.cs b/GitVersionCore/VersionCalculation/NewNextVersionCalculator.cs new file mode 100644 index 0000000000..81cd7d135f --- /dev/null +++ b/GitVersionCore/VersionCalculation/NewNextVersionCalculator.cs @@ -0,0 +1,105 @@ +namespace GitVersion.VersionCalculation +{ + using System; + using System.Text.RegularExpressions; + using BaseVersionCalculators; + + public class NewNextVersionCalculator + { + IBaseVersionCalculator baseVersionFinder; + IMetaDataCalculator metaDataCalculator; + LastTagBaseVersionStrategy lastTagBaseVersionStrategy; + + public NewNextVersionCalculator(IBaseVersionCalculator baseVersionCalculator = null, IMetaDataCalculator metaDataCalculator = null) + { + this.metaDataCalculator = metaDataCalculator ?? new MetaDataCalculator(); + lastTagBaseVersionStrategy = new LastTagBaseVersionStrategy(); + baseVersionFinder = baseVersionCalculator ?? + new BaseVersionCalculator( + new FallbackBaseVersionStrategy(), + new ConfigNextVersionBaseVersionStrategy(), + lastTagBaseVersionStrategy, + new MergeMessageBaseVersionStrategy(), + new VersionInBranchBaseVersionStrategy()); + } + + public SemanticVersion FindVersion(GitVersionContext context) + { + var baseVersion = baseVersionFinder.GetBaseVersion(context); + + if (baseVersion.ShouldIncrement) IncrementVersion(context, baseVersion); + else Logger.WriteInfo("Skipping version increment"); + + if (baseVersion.ShouldUpdateTag && !baseVersion.SemanticVersion.PreReleaseTag.HasTag() && !string.IsNullOrEmpty(context.Configuration.Tag)) + { + var tagToUse = context.Configuration.Tag; + if (tagToUse == "useBranchName") + { + Logger.WriteInfo("Using branch name to calculate version tag"); + var name = baseVersion.BranchNameOverride ?? context.CurrentBranch.Name; + tagToUse = name.RegexReplace(context.Configuration.BranchPrefixToTrim, string.Empty, RegexOptions.IgnoreCase); + } + int? number = 1; + var lastTag = lastTagBaseVersionStrategy.GetVersion(context); + if (lastTag != null && + !context.IsCurrentCommitTagged && + MajorMinorPatchEqual(lastTag.SemanticVersion, baseVersion.SemanticVersion) && + lastTag.SemanticVersion.PreReleaseTag.HasTag()) + { + number = lastTag.SemanticVersion.PreReleaseTag.Number + 1; + } + + baseVersion.SemanticVersion.PreReleaseTag = new SemanticVersionPreReleaseTag(tagToUse, number); + } + + baseVersion.SemanticVersion.BuildMetaData = metaDataCalculator.Create(baseVersion.BaseVersionSource, context); + + return baseVersion.SemanticVersion; + } + + static bool MajorMinorPatchEqual(SemanticVersion lastTag, SemanticVersion baseVersion) + { + return lastTag.Major == baseVersion.Major && + lastTag.Minor == baseVersion.Minor && + lastTag.Patch == baseVersion.Patch; + } + + static void IncrementVersion(GitVersionContext context, BaseVersion baseVersion) + { + if (!baseVersion.SemanticVersion.PreReleaseTag.HasTag()) + { + switch (context.Configuration.Increment) + { + case IncrementStrategy.None: + Logger.WriteInfo("Skipping version increment"); + break; + case IncrementStrategy.Major: + Logger.WriteInfo("Incrementing Major Version"); + baseVersion.SemanticVersion.Major++; + baseVersion.SemanticVersion.Minor = 0; + baseVersion.SemanticVersion.Patch = 0; + break; + case IncrementStrategy.Minor: + baseVersion.SemanticVersion.Minor++; + baseVersion.SemanticVersion.Patch = 0; + Logger.WriteInfo("Incrementing Minor Version"); + break; + case IncrementStrategy.Patch: + baseVersion.SemanticVersion.Patch++; + Logger.WriteInfo("Incrementing Patch Version"); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + else + { + if (baseVersion.SemanticVersion.PreReleaseTag.Number != null) + { + baseVersion.SemanticVersion.PreReleaseTag.Number = baseVersion.SemanticVersion.PreReleaseTag.Number; + baseVersion.SemanticVersion.PreReleaseTag.Number++; + } + } + } + } +} \ No newline at end of file diff --git a/GitVersionCore/GitFlow/BranchFinders/RecentTagVersionExtractor.cs b/GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs similarity index 56% rename from GitVersionCore/GitFlow/BranchFinders/RecentTagVersionExtractor.cs rename to GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs index 09f7fc1088..b6b5e1b694 100644 --- a/GitVersionCore/GitFlow/BranchFinders/RecentTagVersionExtractor.cs +++ b/GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs @@ -1,23 +1,22 @@ -namespace GitVersion +namespace GitVersion.VersioningModes { using System.Collections.Generic; using System.Linq; using LibGit2Sharp; - class RecentTagVersionExtractor + public class ContinuousDeliveryMode : VersioningModeBase { - internal static SemanticVersionPreReleaseTag RetrieveMostRecentOptionalTagVersion(GitVersionContext context, SemanticVersion matchVersion) + public override SemanticVersionPreReleaseTag GetPreReleaseTag(GitVersionContext context, List possibleCommits, int numberOfCommits) { - var tagsInDescendingOrder = context.Repository.SemVerTagsRelatedToVersion(context.Configuration, matchVersion).OrderByDescending(tag => SemanticVersion.Parse(tag.Name, context.Configuration.TagPrefix)); - return RetrieveMostRecentOptionalTagVersion(context, tagsInDescendingOrder.ToList()); + return RetrieveMostRecentOptionalTagVersion(context, possibleCommits) ?? context.Configuration.Tag + ".1"; } - internal static SemanticVersionPreReleaseTag RetrieveMostRecentOptionalTagVersion(GitVersionContext context, List applicableTagsInDescendingOrder) + static SemanticVersionPreReleaseTag RetrieveMostRecentOptionalTagVersion(GitVersionContext context, List applicableTagsInDescendingOrder) { if (applicableTagsInDescendingOrder.Any()) { var taggedCommit = applicableTagsInDescendingOrder.First().Target; - var preReleaseVersion = applicableTagsInDescendingOrder.Select(tag => SemanticVersion.Parse(tag.Name, context.Configuration.TagPrefix)).FirstOrDefault(); + var preReleaseVersion = applicableTagsInDescendingOrder.Select(tag => SemanticVersion.Parse(tag.Name, context.Configuration.GitTagPrefix)).FirstOrDefault(); if (preReleaseVersion != null) { if (taggedCommit != context.CurrentCommit) @@ -30,4 +29,4 @@ internal static SemanticVersionPreReleaseTag RetrieveMostRecentOptionalTagVersio return null; } } -} \ No newline at end of file +} diff --git a/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs b/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs new file mode 100644 index 0000000000..9b7c038d7d --- /dev/null +++ b/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs @@ -0,0 +1,14 @@ +namespace GitVersion.VersioningModes +{ + using System.Collections.Generic; + + using LibGit2Sharp; + + public class ContinuousDeploymentMode : VersioningModeBase + { + public override SemanticVersionPreReleaseTag GetPreReleaseTag(GitVersionContext context, List possibleTags, int numberOfCommits) + { + return context.Configuration.Tag + "." + numberOfCommits; + } + } +} \ No newline at end of file diff --git a/GitVersionCore/VersioningModes/VersioningMode.cs b/GitVersionCore/VersioningModes/VersioningMode.cs new file mode 100644 index 0000000000..d3d97c0632 --- /dev/null +++ b/GitVersionCore/VersioningModes/VersioningMode.cs @@ -0,0 +1,8 @@ +namespace GitVersion +{ + public enum VersioningMode + { + ContinuousDelivery, + ContinuousDeployment + } +} diff --git a/GitVersionCore/VersioningModes/VersioningModeBase.cs b/GitVersionCore/VersioningModes/VersioningModeBase.cs new file mode 100644 index 0000000000..98f15ca9a3 --- /dev/null +++ b/GitVersionCore/VersioningModes/VersioningModeBase.cs @@ -0,0 +1,11 @@ +namespace GitVersion.VersioningModes +{ + using System.Collections.Generic; + + using LibGit2Sharp; + + public abstract class VersioningModeBase + { + public abstract SemanticVersionPreReleaseTag GetPreReleaseTag(GitVersionContext context, List possibleTags, int numberOfCommits); + } +} diff --git a/GitVersionCore/VersioningModes/VersioningModeExtension.cs b/GitVersionCore/VersioningModes/VersioningModeExtension.cs new file mode 100644 index 0000000000..a0d604529e --- /dev/null +++ b/GitVersionCore/VersioningModes/VersioningModeExtension.cs @@ -0,0 +1,21 @@ +namespace GitVersion +{ + using System; + using GitVersion.VersioningModes; + + public static class VersioningModeExtension + { + public static VersioningModeBase GetInstance(this VersioningMode _this) + { + switch (_this) + { + case VersioningMode.ContinuousDelivery: + return new ContinuousDeliveryMode(); + case VersioningMode.ContinuousDeployment: + return new ContinuousDeploymentMode(); + default: + throw new ArgumentException("No instance exists for this versioning mode."); + } + } + } +} \ No newline at end of file diff --git a/GitVersionExe.Tests/AssemblyInfoFileUpdateTests.cs b/GitVersionExe.Tests/AssemblyInfoFileUpdateTests.cs index 2e6aad4724..6580fcb089 100644 --- a/GitVersionExe.Tests/AssemblyInfoFileUpdateTests.cs +++ b/GitVersionExe.Tests/AssemblyInfoFileUpdateTests.cs @@ -1,5 +1,4 @@  using System; - using System.Collections.Generic; using System.IO; using GitVersion; using GitVersion.Helpers; @@ -14,10 +13,8 @@ public void ShouldStartSearchFromWorkingDirectory() { var fileSystem = Substitute.For(); const string workingDir = "C:\\Testing"; - using (new AssemblyInfoFileUpdate(new Arguments - { - UpdateAssemblyInfo = true - }, workingDir, new Dictionary(), fileSystem)) + var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), AssemblyVersioningScheme.MajorMinorPatch, VersioningMode.ContinuousDelivery); + using (new AssemblyInfoFileUpdate(new Arguments{ UpdateAssemblyInfo = true }, workingDir, variables, fileSystem)) { fileSystem.Received().DirectoryGetFiles(Arg.Is(workingDir), Arg.Any(), Arg.Any()); } @@ -46,7 +43,7 @@ public void ShouldReplaceAssemblyVersion() { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch }; - var variable = VariableProvider.GetVariablesFor(version, config); + var variable = VariableProvider.GetVariablesFor(version, config.AssemblyVersioningScheme, VersioningMode.ContinuousDelivery); var args = new Arguments { UpdateAssemblyInfo = true, @@ -84,7 +81,7 @@ public void ShouldReplaceAssemblyVersionWithStar() { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch }; - var variable = VariableProvider.GetVariablesFor(version, config); + var variable = VariableProvider.GetVariablesFor(version, config.AssemblyVersioningScheme, VersioningMode.ContinuousDelivery); var args = new Arguments { UpdateAssemblyInfo = true, diff --git a/GitVersionExe.Tests/ExecutionResults.cs b/GitVersionExe.Tests/ExecutionResults.cs index 7b4d04ad9c..450011df24 100644 --- a/GitVersionExe.Tests/ExecutionResults.cs +++ b/GitVersionExe.Tests/ExecutionResults.cs @@ -1,5 +1,8 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Linq; using System.Web.Script.Serialization; +using GitVersion; public class ExecutionResults { @@ -14,8 +17,18 @@ public ExecutionResults(int exitCode, string output, string logContents) public string Output { get; private set; } public string Log { get; private set; } - public virtual Dictionary OutputVariables + public virtual VersionVariables OutputVariables { - get { return new JavaScriptSerializer().Deserialize>(Output); } + get + { + var outputVariables = new JavaScriptSerializer().Deserialize>(Output); + var type = typeof(VersionVariables); + var ctor = type.GetConstructors().Single(); + var ctorArgs = ctor.GetParameters() + .Select(p => outputVariables.Single(v => v.Key.ToLower() == p.Name.ToLower()).Value) + .Cast() + .ToArray(); + return (VersionVariables) Activator.CreateInstance(type, ctorArgs); + } } } \ No newline at end of file diff --git a/GitVersionExe.Tests/GitVersionHelper.cs b/GitVersionExe.Tests/GitVersionHelper.cs index f48b5f0d86..70a5e2d0da 100644 --- a/GitVersionExe.Tests/GitVersionHelper.cs +++ b/GitVersionExe.Tests/GitVersionHelper.cs @@ -2,8 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Text; -using GitVersion; -using LibGit2Sharp; +using GitVersion.Helpers; public static class GitVersionHelper { @@ -62,10 +61,4 @@ static ExecutionResults ExecuteIn(ArgumentBuilder arguments) return new ExecutionResults(exitCode, output.ToString(), logContents); } - - public static void AddNextVersionTxtFile(this IRepository repository, string version) - { - var nextVersionFile = Path.Combine(repository.Info.WorkingDirectory, "NextVersion.txt"); - File.WriteAllText(nextVersionFile, version); - } } \ No newline at end of file diff --git a/GitVersionExe.Tests/PullRequestInTeamCityTest.cs b/GitVersionExe.Tests/PullRequestInTeamCityTest.cs index d056a7eea4..81bd671351 100644 --- a/GitVersionExe.Tests/PullRequestInTeamCityTest.cs +++ b/GitVersionExe.Tests/PullRequestInTeamCityTest.cs @@ -41,7 +41,7 @@ public void GivenARemoteWithATagOnMaster_AndAPullRequestWithTwoCommits_AndBuildI var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, isTeamCity: true); result.ExitCode.ShouldBe(0); - result.OutputVariables[VariableProvider.FullSemVer].ShouldBe("1.0.4-PullRequest.5+3"); + result.OutputVariables.FullSemVer.ShouldBe("1.0.4-PullRequest.5+3"); // Cleanup repository files DirectoryHelper.DeleteDirectory(remoteRepositoryPath); diff --git a/GitVersionExe/AssemblyInfoFileUpdate.cs b/GitVersionExe/AssemblyInfoFileUpdate.cs index 6f42aa6cef..9582f7e54a 100644 --- a/GitVersionExe/AssemblyInfoFileUpdate.cs +++ b/GitVersionExe/AssemblyInfoFileUpdate.cs @@ -10,7 +10,7 @@ class AssemblyInfoFileUpdate : IDisposable List restoreBackupTasks = new List(); List cleanupBackupTasks = new List(); - public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, Dictionary variables, IFileSystem fileSystem) + public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, VersionVariables variables, IFileSystem fileSystem) { if (!args.UpdateAssemblyInfo) return; @@ -39,11 +39,11 @@ public AssemblyInfoFileUpdate(Arguments args, string workingDirectory, Dictionar } else { - assemblyVersion = string.Format("{0}.{1}.0.0", variables[VariableProvider.Major], variables[VariableProvider.Minor]); + assemblyVersion = string.Format("{0}.{1}.0.0", variables.Major, variables.Minor); } - var assemblyInfoVersion = variables[VariableProvider.InformationalVersion]; - var assemblyFileVersion = variables[VariableProvider.AssemblySemVer]; + var assemblyInfoVersion = variables.InformationalVersion; + var assemblyFileVersion = variables.AssemblySemVer; var fileContents = fileSystem.ReadAllText(assemblyInfoFile) .RegexReplace(@"AssemblyVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyVersion(\"{0}\")", assemblyVersion)) .RegexReplace(@"AssemblyInformationalVersion\(""\d+.\d+.\d+(.(\d+|\*))?""\)", string.Format("AssemblyInformationalVersion(\"{0}\")", assemblyInfoVersion)) diff --git a/GitVersionExe/GitVersionExe.csproj b/GitVersionExe/GitVersionExe.csproj index 97245bfcbc..5651a2811d 100644 --- a/GitVersionExe/GitVersionExe.csproj +++ b/GitVersionExe/GitVersionExe.csproj @@ -58,7 +58,6 @@ - diff --git a/GitVersionExe/Program.cs b/GitVersionExe/Program.cs index 97aa965388..34a1bb518c 100644 --- a/GitVersionExe/Program.cs +++ b/GitVersionExe/Program.cs @@ -85,24 +85,24 @@ static int Run() { buildServer.PerformPreProcessingSteps(gitDirectory); } - SemanticVersion semanticVersion; + VersionVariables variables; var versionFinder = new GitVersionFinder(); var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); using (var repo = RepositoryLoader.GetRepo(gitDirectory)) { var gitVersionContext = new GitVersionContext(repo, configuration); - semanticVersion = versionFinder.FindVersion(gitVersionContext); + var semanticVersion = versionFinder.FindVersion(gitVersionContext); + variables = VariableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration.AssemblyVersioningScheme, gitVersionContext.Configuration.VersioningMode); } if (arguments.Output == OutputType.BuildServer) { foreach (var buildServer in applicableBuildServers) { - buildServer.WriteIntegration(semanticVersion, Console.WriteLine); + buildServer.WriteIntegration(Console.WriteLine, variables); } } - var variables = VariableProvider.GetVariablesFor(semanticVersion, configuration); if (arguments.Output == OutputType.Json) { switch (arguments.VersionPart) @@ -124,9 +124,9 @@ static int Run() if (!string.IsNullOrWhiteSpace(arguments.AssemblyVersionFormat) && !variables.ContainsKey(arguments.AssemblyVersionFormat)) { - Console.WriteLine("Unrecognised AssemblyVersionFormat argument. Valid values for this argument are: {0}", string.Join(" ", variables.Keys.OrderBy(a => a))); + Console.WriteLine("Unrecognised AssemblyVersionFormat argument. Valid values for this argument are: {0}", string.Join(" ", variables.AvailableVariables)); HelpWriter.Write(); - return 1; + return 1; } @@ -225,7 +225,7 @@ static List GetArgumentsWithoutExeName() .ToList(); } - static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, Dictionary variables) + static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) { if (string.IsNullOrEmpty(args.Proj)) return false; @@ -241,7 +241,7 @@ static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, Dictiona return true; } - static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, Dictionary variables) + static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) { if (string.IsNullOrEmpty(args.Exec)) return false; @@ -256,7 +256,7 @@ static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, Dict return true; } - static KeyValuePair[] GetEnvironmentalVariables(Dictionary variables) + static KeyValuePair[] GetEnvironmentalVariables(VersionVariables variables) { return variables .Select(v => new KeyValuePair("GitVersion_" + v.Key, v.Value)) diff --git a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_Major.approved.txt b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_Major.approved.txt index ade1204d39..5b713f2e15 100644 --- a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_Major.approved.txt +++ b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_Major.approved.txt @@ -3,19 +3,17 @@ using System; using System.Reflection; [assembly: AssemblyVersion("2.0.0.0")] -[assembly: AssemblyFileVersion("2.3.4.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.3.4+5.Branch.master.Sha.commitSha")] -[assembly: ReleaseDate("2014-03-01", "2014-03-06")] +[assembly: ReleaseDate("2014-03-06")] [System.Runtime.CompilerServices.CompilerGenerated] sealed class ReleaseDateAttribute : System.Attribute { - public string OriginalDate { get; private set; } public string Date { get; private set; } - public ReleaseDateAttribute(string originalDate, string date) + public ReleaseDateAttribute(string date) { - OriginalDate = originalDate; Date = date; } } @@ -35,11 +33,8 @@ static class GitVersionInformation public static string LegacySemVer = "2.3.4"; public static string LegacySemVerPadded = "2.3.4"; public static string AssemblySemVer = "2.0.0.0"; - public static string AssemblyFileSemVer = "2.3.4.0"; public static string FullSemVer = "2.3.4+5"; public static string InformationalVersion = "2.3.4+5.Branch.master.Sha.commitSha"; - public static string ClassicVersion = "2.3.4.5"; - public static string ClassicVersionWithTag = "2.3.4.5"; public static string BranchName = "master"; public static string Sha = "commitSha"; public static string NuGetVersionV2 = "2.3.4"; diff --git a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinor.approved.txt b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinor.approved.txt index c15597f387..fd72432035 100644 --- a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinor.approved.txt +++ b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinor.approved.txt @@ -3,19 +3,17 @@ using System; using System.Reflection; [assembly: AssemblyVersion("2.3.0.0")] -[assembly: AssemblyFileVersion("2.3.4.0")] +[assembly: AssemblyFileVersion("2.3.0.0")] [assembly: AssemblyInformationalVersion("2.3.4+5.Branch.master.Sha.commitSha")] -[assembly: ReleaseDate("2014-03-01", "2014-03-06")] +[assembly: ReleaseDate("2014-03-06")] [System.Runtime.CompilerServices.CompilerGenerated] sealed class ReleaseDateAttribute : System.Attribute { - public string OriginalDate { get; private set; } public string Date { get; private set; } - public ReleaseDateAttribute(string originalDate, string date) + public ReleaseDateAttribute(string date) { - OriginalDate = originalDate; Date = date; } } @@ -35,11 +33,8 @@ static class GitVersionInformation public static string LegacySemVer = "2.3.4"; public static string LegacySemVerPadded = "2.3.4"; public static string AssemblySemVer = "2.3.0.0"; - public static string AssemblyFileSemVer = "2.3.4.0"; public static string FullSemVer = "2.3.4+5"; public static string InformationalVersion = "2.3.4+5.Branch.master.Sha.commitSha"; - public static string ClassicVersion = "2.3.4.5"; - public static string ClassicVersionWithTag = "2.3.4.5"; public static string BranchName = "master"; public static string Sha = "commitSha"; public static string NuGetVersionV2 = "2.3.4"; diff --git a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatch.approved.txt b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatch.approved.txt index d07d1cd893..8b5c86bcdc 100644 --- a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatch.approved.txt +++ b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatch.approved.txt @@ -5,17 +5,15 @@ using System.Reflection; [assembly: AssemblyVersion("2.3.4.0")] [assembly: AssemblyFileVersion("2.3.4.0")] [assembly: AssemblyInformationalVersion("2.3.4+5.Branch.master.Sha.commitSha")] -[assembly: ReleaseDate("2014-03-01", "2014-03-06")] +[assembly: ReleaseDate("2014-03-06")] [System.Runtime.CompilerServices.CompilerGenerated] sealed class ReleaseDateAttribute : System.Attribute { - public string OriginalDate { get; private set; } public string Date { get; private set; } - public ReleaseDateAttribute(string originalDate, string date) + public ReleaseDateAttribute(string date) { - OriginalDate = originalDate; Date = date; } } @@ -35,11 +33,8 @@ static class GitVersionInformation public static string LegacySemVer = "2.3.4"; public static string LegacySemVerPadded = "2.3.4"; public static string AssemblySemVer = "2.3.4.0"; - public static string AssemblyFileSemVer = "2.3.4.0"; public static string FullSemVer = "2.3.4+5"; public static string InformationalVersion = "2.3.4+5.Branch.master.Sha.commitSha"; - public static string ClassicVersion = "2.3.4.5"; - public static string ClassicVersionWithTag = "2.3.4.5"; public static string BranchName = "master"; public static string Sha = "commitSha"; public static string NuGetVersionV2 = "2.3.4"; diff --git a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatchMetadata.approved.txt b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatchMetadata.approved.txt index 116e52c2a3..e3c6ccf659 100644 --- a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatchMetadata.approved.txt +++ b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyAssemblyVersion_MajorMinorPatchMetadata.approved.txt @@ -5,17 +5,15 @@ using System.Reflection; [assembly: AssemblyVersion("2.3.4.5")] [assembly: AssemblyFileVersion("2.3.4.5")] [assembly: AssemblyInformationalVersion("2.3.4+5.Branch.master.Sha.commitSha")] -[assembly: ReleaseDate("2014-03-01", "2014-03-06")] +[assembly: ReleaseDate("2014-03-06")] [System.Runtime.CompilerServices.CompilerGenerated] sealed class ReleaseDateAttribute : System.Attribute { - public string OriginalDate { get; private set; } public string Date { get; private set; } - public ReleaseDateAttribute(string originalDate, string date) + public ReleaseDateAttribute(string date) { - OriginalDate = originalDate; Date = date; } } @@ -35,11 +33,8 @@ static class GitVersionInformation public static string LegacySemVer = "2.3.4"; public static string LegacySemVerPadded = "2.3.4"; public static string AssemblySemVer = "2.3.4.5"; - public static string AssemblyFileSemVer = "2.3.4.5"; public static string FullSemVer = "2.3.4+5"; public static string InformationalVersion = "2.3.4+5.Branch.master.Sha.commitSha"; - public static string ClassicVersion = "2.3.4.5"; - public static string ClassicVersionWithTag = "2.3.4.5"; public static string BranchName = "master"; public static string Sha = "commitSha"; public static string NuGetVersionV2 = "2.3.4"; diff --git a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyCreatedCode.approved.txt b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyCreatedCode.approved.txt index 264848e2cf..836e58cd54 100644 --- a/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyCreatedCode.approved.txt +++ b/GitVersionTask.Tests/AssemblyInfoBuilderTests.VerifyCreatedCode.approved.txt @@ -5,17 +5,15 @@ using System.Reflection; [assembly: AssemblyVersion("1.2.3.0")] [assembly: AssemblyFileVersion("1.2.3.0")] [assembly: AssemblyInformationalVersion("1.2.3-unstable.4+5.Branch.feature1.Sha.commitSha")] -[assembly: ReleaseDate("2014-03-01", "2014-03-06")] +[assembly: ReleaseDate("2014-03-06")] [System.Runtime.CompilerServices.CompilerGenerated] sealed class ReleaseDateAttribute : System.Attribute { - public string OriginalDate { get; private set; } public string Date { get; private set; } - public ReleaseDateAttribute(string originalDate, string date) + public ReleaseDateAttribute(string date) { - OriginalDate = originalDate; Date = date; } } @@ -35,11 +33,8 @@ static class GitVersionInformation public static string LegacySemVer = "1.2.3-unstable4"; public static string LegacySemVerPadded = "1.2.3-unstable0004"; public static string AssemblySemVer = "1.2.3.0"; - public static string AssemblyFileSemVer = "1.2.3.0"; public static string FullSemVer = "1.2.3-unstable.4+5"; public static string InformationalVersion = "1.2.3-unstable.4+5.Branch.feature1.Sha.commitSha"; - public static string ClassicVersion = "1.2.3.5"; - public static string ClassicVersionWithTag = "1.2.3.5-unstable.4"; public static string BranchName = "feature1"; public static string Sha = "commitSha"; public static string NuGetVersionV2 = "1.2.3-unstable0004"; diff --git a/GitVersionTask.Tests/AssemblyInfoBuilderTests.cs b/GitVersionTask.Tests/AssemblyInfoBuilderTests.cs index a61561c0ce..04aefd128b 100644 --- a/GitVersionTask.Tests/AssemblyInfoBuilderTests.cs +++ b/GitVersionTask.Tests/AssemblyInfoBuilderTests.cs @@ -4,6 +4,7 @@ using System.Runtime.CompilerServices; using ApprovalTests; using GitVersion; +using GitVersionCore.Tests; using NUnit.Framework; using Roslyn.Compilers; using Roslyn.Compilers.CSharp; @@ -22,20 +23,19 @@ public void VerifyCreatedCode() Patch = 3, PreReleaseTag = "unstable4", BuildMetaData = new SemanticVersionBuildMetaData(5, - "feature1","commitSha",DateTimeOffset.Parse("2014-03-06 23:59:59Z")) + "feature1", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; var assemblyInfoBuilder = new AssemblyInfoBuilder + { + CachedVersion = new CachedVersion { - CachedVersion = new CachedVersion - { - SemanticVersion = semanticVersion, - MasterReleaseDate = DateTimeOffset.Parse("2014-03-01 00:00:01Z"), - } - }; - var assemblyInfoText = assemblyInfoBuilder.GetAssemblyInfoText(new Config()); + SemanticVersion = semanticVersion + } + }; + var assemblyInfoText = assemblyInfoBuilder.GetAssemblyInfoText(new TestEffectiveConfiguration()); Approvals.Verify(assemblyInfoText); var syntaxTree = SyntaxTree.ParseText(assemblyInfoText); - var references = new[] {new MetadataFileReference(typeof(object).Assembly.Location)}; + var references = new[] { new MetadataFileReference(typeof(object).Assembly.Location) }; var compilation = Compilation.Create("Greeter.dll", new CompilationOptions(OutputKind.NetModule), new[] { syntaxTree }, references); var emitResult = compilation.Emit(new MemoryStream()); Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Info))); @@ -77,21 +77,20 @@ static void VerifyAssemblyVersion(AssemblyVersioningScheme avs) Minor = 3, Patch = 4, BuildMetaData = new SemanticVersionBuildMetaData(5, - "master","commitSha",DateTimeOffset.Parse("2014-03-06 23:59:59Z")), + "master", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")), }; var assemblyInfoBuilder = new AssemblyInfoBuilder { CachedVersion = new CachedVersion { - SemanticVersion = semanticVersion, - MasterReleaseDate = DateTimeOffset.Parse("2014-03-01 00:00:01Z") + SemanticVersion = semanticVersion }, }; - var assemblyInfoText = assemblyInfoBuilder.GetAssemblyInfoText(new Config { AssemblyVersioningScheme = avs }); + var assemblyInfoText = assemblyInfoBuilder.GetAssemblyInfoText(new TestEffectiveConfiguration(assemblyVersioningScheme: avs)); Approvals.Verify(assemblyInfoText); var syntaxTree = SyntaxTree.ParseText(assemblyInfoText); - var references = new[] { new MetadataFileReference(typeof(object).Assembly.Location)}; + var references = new[] { new MetadataFileReference(typeof(object).Assembly.Location) }; var compilation = Compilation.Create("Greeter.dll", new CompilationOptions(OutputKind.NetModule), new[] { syntaxTree }, references); var emitResult = compilation.Emit(new MemoryStream()); Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Info))); diff --git a/GitVersionTask.Tests/BranchClassifierTests.cs b/GitVersionTask.Tests/BranchClassifierTests.cs deleted file mode 100644 index 8e31219fa6..0000000000 --- a/GitVersionTask.Tests/BranchClassifierTests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using GitVersion; -using NUnit.Framework; - -[TestFixture] -public class BranchClassifierTests -{ - - [Test] - public void IsHotfix() - { - Assert.IsTrue(new MockBranch("hotfix-1").IsHotfix()); - Assert.IsTrue(new MockBranch("hotfix/1").IsHotfix()); - Assert.IsTrue(new MockBranch("Hotfix-1").IsHotfix()); - Assert.IsTrue(new MockBranch("Hotfix/1").IsHotfix()); - Assert.IsFalse(new MockBranch("hotfix1").IsHotfix()); - } - [Test] - public void IsRelease() - { - Assert.IsTrue(new MockBranch("release-1").IsRelease()); - Assert.IsTrue(new MockBranch("release/1").IsRelease()); - Assert.IsTrue(new MockBranch("Release-1").IsRelease()); - Assert.IsTrue(new MockBranch("Release/1").IsRelease()); - Assert.IsFalse(new MockBranch("release").IsRelease()); - } - [Test] - public void IsSupport() - { - Assert.IsTrue(new MockBranch("support-1").IsSupport()); - Assert.IsTrue(new MockBranch("support/1").IsSupport()); - Assert.IsTrue(new MockBranch("Support-1").IsSupport()); - Assert.IsTrue(new MockBranch("Support/1").IsSupport()); - Assert.IsFalse(new MockBranch("release").IsRelease()); - } - [Test] - public void IsDevelop() - { - Assert.IsTrue(new MockBranch("develop").IsDevelop()); - Assert.IsTrue(new MockBranch("Develop").IsDevelop()); - Assert.IsFalse(new MockBranch("hotfix1").IsDevelop()); - } - [Test] - public void IsMaster() - { - Assert.IsTrue(new MockBranch("master").IsMaster()); - Assert.IsTrue(new MockBranch("Master").IsMaster()); - Assert.IsFalse(new MockBranch("hotfix1").IsMaster()); - } - [Test] - public void IsPullRequest() - { - Assert.IsTrue(new MockBranch("fix for issue xxx","/pull/4").IsPullRequest()); - Assert.IsFalse(new MockBranch("hotfix1","").IsPullRequest()); - } -} diff --git a/GitVersionTask.Tests/BranchFinders/DevelopTests.Commit_on_develop_and_previous_commit_on_master_has_a_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/DevelopTests.Commit_on_develop_and_previous_commit_on_master_has_a_tag.approved.txt deleted file mode 100644 index bf9d4a3a0c..0000000000 --- a/GitVersionTask.Tests/BranchFinders/DevelopTests.Commit_on_develop_and_previous_commit_on_master_has_a_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 2, - "Patch": 0, - "PreReleaseTag": { - "Name": "unstable", - "Number": 1 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "develop", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/DevelopTests.Commit_on_develop_and_previous_commit_on_master_is_a_hotfix.approved.txt b/GitVersionTask.Tests/BranchFinders/DevelopTests.Commit_on_develop_and_previous_commit_on_master_is_a_hotfix.approved.txt deleted file mode 100644 index bf9d4a3a0c..0000000000 --- a/GitVersionTask.Tests/BranchFinders/DevelopTests.Commit_on_develop_and_previous_commit_on_master_is_a_hotfix.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 2, - "Patch": 0, - "PreReleaseTag": { - "Name": "unstable", - "Number": 1 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "develop", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/DevelopTests.Multiple_minor_versions_on_master.approved.txt b/GitVersionTask.Tests/BranchFinders/DevelopTests.Multiple_minor_versions_on_master.approved.txt deleted file mode 100644 index 5012ac8759..0000000000 --- a/GitVersionTask.Tests/BranchFinders/DevelopTests.Multiple_minor_versions_on_master.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 4, - "Patch": 0, - "PreReleaseTag": { - "Name": "unstable", - "Number": 2 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "develop", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/DevelopTests.cs b/GitVersionTask.Tests/BranchFinders/DevelopTests.cs deleted file mode 100644 index 2d73412448..0000000000 --- a/GitVersionTask.Tests/BranchFinders/DevelopTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -using FluentDate; -using FluentDateTimeOffset; -using GitVersion; -using NUnit.Framework; -using ObjectApproval; - -[TestFixture] -public class DevelopTests -{ - [Test] - [Ignore] //TODO Delete? - public void Commit_on_develop_and_previous_commit_on_master_is_a_hotfix() - { - var commitOnDevelop = new MockCommit - { - CommitterEx = 1.Seconds().Ago().ToSignature() - }; - var finder = new DevelopVersionFinder(); - var mockBranch = new MockBranch("develop") - { - commitOnDevelop - }; - var repository = new MockRepository - { - Branches = new MockBranchCollection - { - new MockBranch("master") - { - new MockMergeCommit - { - MessageEx = "hotfix-0.1.1", - CommitterEx = 2.Seconds().Ago().ToSignature() - } - }, - mockBranch - }, - }; - var version = finder.FindVersion(new GitVersionContext(repository, mockBranch, new Config())); - Assert.AreEqual(2, version.Minor, "Minor should be master.Minor+1"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - - [Test] - [Ignore] //TODO Delete? - public void Commit_on_develop_and_previous_commit_on_master_has_a_tag() - { - var commitOnDevelop = new MockCommit - { - CommitterEx = 1.Seconds().Ago().ToSignature() - }; - var commitOnMaster = new MockCommit - { - CommitterEx = 2.Seconds().Ago().ToSignature() - }; - var finder = new DevelopVersionFinder(); - var develop = new MockBranch("develop") - { - commitOnDevelop - }; - var repository = new MockRepository - { - Branches = new MockBranchCollection - { - new MockBranch("master") - { - commitOnMaster - }, - develop - }, - Tags = new MockTagCollection - { - new MockTag - { - TargetEx = commitOnMaster, - NameEx = "0.1.0" - } - } - }; - var context = new GitVersionContext(repository, develop, new Config()); - - var version = finder.FindVersion(context); - Assert.AreEqual(2, version.Minor, "Minor should be master.Minor+1"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_1_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_1_commit.approved.txt deleted file mode 100644 index 8f81073aa6..0000000000 --- a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_1_commit.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 1, - "Minor": 1, - "Patch": 0, - "PreReleaseTag": { - "Name": "featureWithOneCommit", - "Number": null - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "featureWithOneCommit", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_2_commits.approved.txt b/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_2_commits.approved.txt deleted file mode 100644 index 8dd2f6d0fa..0000000000 --- a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_2_commits.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 1, - "Minor": 1, - "Patch": 0, - "PreReleaseTag": { - "Name": "featureWithOneCommit", - "Number": null - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "featureWithOneCommit", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_2_commits_but_building_an_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_2_commits_but_building_an_commit.approved.txt deleted file mode 100644 index 8dd2f6d0fa..0000000000 --- a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_2_commits_but_building_an_commit.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 1, - "Minor": 1, - "Patch": 0, - "PreReleaseTag": { - "Name": "featureWithOneCommit", - "Number": null - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "featureWithOneCommit", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_no_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_no_commit.approved.txt deleted file mode 100644 index 4751b59285..0000000000 --- a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.Feature_branch_with_no_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 1, - "Minor": 1, - "Patch": 0, - "PreReleaseTag": { - "Name": "unstable", - "Number": 3 - }, - "BuildMetaData": { - "CommitsSinceTag": 3, - "Branch": "featureWithNoCommits", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "2013-11-17T12:59:39Z", - "ReleaseDate": "2013-11-17T12:59:39Z", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.cs b/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.cs deleted file mode 100644 index 0360e5cd32..0000000000 --- a/GitVersionTask.Tests/BranchFinders/FeatureBranchTests.cs +++ /dev/null @@ -1,116 +0,0 @@ -using GitVersion; -using LibGit2Sharp; -using NUnit.Framework; -using ObjectApproval; - -[TestFixture] -public class FeatureBranchTests : Lg2sHelperBase -{ - [Test] - [Ignore] //TODO Delete? - public void Feature_branch_with_no_commit() - { - //this scenario should redirect to the develop finder since there is no diff btw this branch and the develop branch - - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - var branchingCommit = repo.Branches["develop"].Tip; - var featureBranch = repo.Branches.Add("featureWithNoCommits", branchingCommit); - - var finder = new FeatureVersionFinder(); - - var configuration = new Config(); - var version = finder.FindVersion(new GitVersionContext(repo, featureBranch, configuration)); - - var masterVersion = FindersHelper.RetrieveMasterVersion(repo, configuration); - - Assert.AreEqual(masterVersion.Minor + 1, version.Minor, "Minor should be master.Minor+1"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidScrubber); - } - } - - [Test] - public void Feature_branch_with_1_commit() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - // Create a feature branch from the parent of current develop tip - repo.Branches.Add("featureWithOneCommit", "develop~").ForceCheckout(); - //var branchingCommit = repo.Head.Tip; - - AddOneCommitToHead(repo, "feature"); - - var featureBranch = repo.Branches["featureWithOneCommit"]; - - var finder = new FeatureVersionFinder(); - - var configuration = new Config(); - var version = finder.FindVersion(new GitVersionContext(repo, featureBranch, configuration)); - - var masterVersion = FindersHelper.RetrieveMasterVersion(repo, configuration); - - Assert.AreEqual(masterVersion.Minor + 1, version.Minor, "Minor should be master.Minor+1"); - //TODO Assert.AreEqual(branchingCommit.Prefix(), version.Version.Suffix, "Suffix should be the develop commit it was branched from"); - - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - } - - [Test] - public void Feature_branch_with_2_commits() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - // Create a feature branch from the parent of current develop tip - repo.Branches.Add("featureWithOneCommit", "develop~").ForceCheckout(); - //var branchingCommit = repo.Head.Tip; - - AddOneCommitToHead(repo, "feature"); - AddOneCommitToHead(repo, "feature"); - - var featureBranch = repo.Branches["featureWithOneCommit"]; - - var finder = new FeatureVersionFinder(); - - var configuration = new Config(); - var version = finder.FindVersion(new GitVersionContext(repo, featureBranch, configuration)); - - var masterVersion = FindersHelper.RetrieveMasterVersion(repo, configuration); - - Assert.AreEqual(masterVersion.Minor + 1, version.Minor, "Minor should be master.Minor+1"); - //TODO Assert.AreEqual(branchingCommit.Prefix(), version.Version.Suffix, "Suffix should be the develop commit it was branched from"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - } - - [Test] - public void Feature_branch_with_2_commits_but_building_an_commit() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - // Create a feature branch from the parent of current develop tip - repo.Branches.Add("featureWithOneCommit", "develop~").ForceCheckout(); - //var branchingCommit = repo.Head.Tip; - - AddOneCommitToHead(repo, "feature"); - AddOneCommitToHead(repo, "feature"); - - var featureBranch = repo.Branches["featureWithOneCommit"]; - - var finder = new FeatureVersionFinder(); - - var configuration = new Config(); - var version = finder.FindVersion(new GitVersionContext(repo, featureBranch, configuration)); - - var masterVersion = FindersHelper.RetrieveMasterVersion(repo, configuration); - - Assert.AreEqual(masterVersion.Minor + 1, version.Minor, "Minor should be master.Minor+1"); - //TODO Assert.AreEqual(branchingCommit.Prefix(), version.Version.Suffix, "Suffix should be the develop commit it was branched from"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/HotfixTests.First_commit_with_tag_pointing_at_branching_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/HotfixTests.First_commit_with_tag_pointing_at_branching_commit.approved.txt deleted file mode 100644 index 43c024e187..0000000000 --- a/GitVersionTask.Tests/BranchFinders/HotfixTests.First_commit_with_tag_pointing_at_branching_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 1, - "Patch": 3, - "PreReleaseTag": { - "Name": "beta", - "Number": 5 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "hotfix-0.1.3", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/HotfixTests.No_commits_with_no_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/HotfixTests.No_commits_with_no_tag.approved.txt deleted file mode 100644 index f27de07300..0000000000 --- a/GitVersionTask.Tests/BranchFinders/HotfixTests.No_commits_with_no_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 1, - "Patch": 4, - "PreReleaseTag": { - "Name": "hotfix", - "Number": 0 - }, - "BuildMetaData": { - "CommitsSinceTag": 0, - "Branch": "hotfix-0.1.4", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "2013-11-17T12:51:40Z", - "ReleaseDate": "2013-11-17T12:58:35Z", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_no_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_no_tag.approved.txt deleted file mode 100644 index 9039e9d445..0000000000 --- a/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_no_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 1, - "Patch": 3, - "PreReleaseTag": { - "Name": "hotfix", - "Number": 0 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "hotfix-0.1.3", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_tag_pointing_at_first_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_tag_pointing_at_first_commit.approved.txt deleted file mode 100644 index 1e42edd551..0000000000 --- a/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_tag_pointing_at_first_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 1, - "Patch": 3, - "PreReleaseTag": { - "Name": "alpha", - "Number": 6 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "hotfix-0.1.3", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_tag_pointing_at_first_commit_and_unrelated_one_at_second_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_tag_pointing_at_first_commit_and_unrelated_one_at_second_commit.approved.txt deleted file mode 100644 index 1e42edd551..0000000000 --- a/GitVersionTask.Tests/BranchFinders/HotfixTests.Second_commit_with_tag_pointing_at_first_commit_and_unrelated_one_at_second_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 1, - "Patch": 3, - "PreReleaseTag": { - "Name": "alpha", - "Number": 6 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "hotfix-0.1.3", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/MasterTests.Hotfix_merge.approved.txt b/GitVersionTask.Tests/BranchFinders/MasterTests.Hotfix_merge.approved.txt deleted file mode 100644 index 93c9c3f1e5..0000000000 --- a/GitVersionTask.Tests/BranchFinders/MasterTests.Hotfix_merge.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 0, - "Minor": 1, - "Patch": 5, - "PreReleaseTag": { - "Name": null, - "Number": null - }, - "BuildMetaData": { - "CommitsSinceTag": null, - "Branch": "master", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/MasterTests.Override_using_tag_with_a_stable_release.approved.txt b/GitVersionTask.Tests/BranchFinders/MasterTests.Override_using_tag_with_a_stable_release.approved.txt deleted file mode 100644 index 9826785aac..0000000000 --- a/GitVersionTask.Tests/BranchFinders/MasterTests.Override_using_tag_with_a_stable_release.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 0, - "Minor": 2, - "Patch": 0, - "PreReleaseTag": { - "Name": null, - "Number": null - }, - "BuildMetaData": { - "CommitsSinceTag": null, - "Branch": "master", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/MasterTests.Release_merge.approved.txt b/GitVersionTask.Tests/BranchFinders/MasterTests.Release_merge.approved.txt deleted file mode 100644 index 9826785aac..0000000000 --- a/GitVersionTask.Tests/BranchFinders/MasterTests.Release_merge.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 0, - "Minor": 2, - "Patch": 0, - "PreReleaseTag": { - "Name": null, - "Number": null - }, - "BuildMetaData": { - "CommitsSinceTag": null, - "Branch": "master", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/MasterTests.cs b/GitVersionTask.Tests/BranchFinders/MasterTests.cs deleted file mode 100644 index fbe25a6858..0000000000 --- a/GitVersionTask.Tests/BranchFinders/MasterTests.cs +++ /dev/null @@ -1,162 +0,0 @@ -using FluentDate; -using FluentDateTimeOffset; -using GitVersion; -using NUnit.Framework; -using ObjectApproval; - -[TestFixture] -public class MasterTests -{ - - [Test] - public void Should_throw_if_head_isnt_a_merge_commit_and_no_override_tag_is_found() - { - var commit = new MockCommit - { - MessageEx = "Not a merge commit", - CommitterEx = 2.Seconds().Ago().ToSignature() - }; - var finder = new MasterVersionFinder(); - - var mockBranch = new MockBranch("master") - { - commit - }; - var mockRepository = new MockRepository - { - Branches = new MockBranchCollection - { - mockBranch, - } - }; - var exception = Assert.Throws(() => - { - finder.FindVersion(new GitVersionContext(mockRepository, mockBranch, new Config())); - }); - Assert.AreEqual("The head of master should always be a merge commit if you follow gitflow. Please create one or work around this by tagging the commit with SemVer compatible Id.", exception.Message); - } - - [Test] - public void Commit_in_front_of_tag_should_return_tag_as_version() - { - //should throw - } - - [Test] - public void Hotfix_merge() - { - var hotfixMergeCommit = new MockMergeCommit - { - MessageEx = "Merge branch 'hotfix-0.1.5'", - CommitterEx = 2.Seconds().Ago().ToSignature() - }; - var finder = new MasterVersionFinder(); - var mockBranch = new MockBranch("master") - { - hotfixMergeCommit - }; - var mockRepository = new MockRepository - { - Branches = new MockBranchCollection - { - mockBranch, - } - }; - var version = finder.FindVersion(new GitVersionContext(mockRepository, mockBranch, new Config())); - - Assert.AreEqual(5, version.Patch, "Should set the patch version to the patch of the latest hotfix merge commit"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - - [Test] - public void Override_using_tag_with_a_stable_release() - { - var commit = new MockCommit - { - CommitterEx = 2.Seconds().Ago().ToSignature() - }; - var finder = new MasterVersionFinder(); - var mockBranch = new MockBranch("master") - { - commit - }; - var mockRepository = new MockRepository - { - Branches = new MockBranchCollection - { - mockBranch, - }, - Tags = new MockTagCollection - { - new MockTag - { - NameEx = "0.2.0", - TargetEx = commit - } - } - }; - var version = finder.FindVersion(new GitVersionContext(mockRepository, mockBranch, new Config())); - Assert.AreEqual(0, version.Patch, "Should set the patch version to the patch of the latest hotfix merge commit"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - - [Test] - [Ignore("should we support overriding with a beta?")] - public void Override_using_tag_with_a_prerelease() - { - var commit = new MockCommit - { - CommitterEx = 2.Seconds().Ago().ToSignature() - }; - var finder = new MasterVersionFinder(); - var mockBranch = new MockBranch("master") - { - commit - }; - var mockRepository = new MockRepository - { - Branches = new MockBranchCollection - { - mockBranch - }, - Tags = new MockTagCollection - { - new MockTag - { - NameEx = "0.1.0-beta1", - TargetEx = commit - } - } - }; - var version = finder.FindVersion(new GitVersionContext(mockRepository, mockBranch, new Config())); - Assert.AreEqual(0, version.Patch, "Should set the patch version to the patch of the latest hotfix merge commit"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidScrubber); - } - - - [Test] - public void Release_merge() - { - var commit = new MockMergeCommit - { - CommitterEx = 2.Seconds().Ago().ToSignature(), - MessageEx = "Merge branch 'release-0.2.0'" - }; - var finder = new MasterVersionFinder(); - var mockBranch = new MockBranch("master") - { - commit - }; - var mockRepository = new MockRepository - { - Branches = new MockBranchCollection - { - mockBranch - }, - }; - var version = finder.FindVersion(new GitVersionContext(mockRepository, mockBranch, new Config())); - Assert.AreEqual(0, version.Patch, "Should set the patch version to 0"); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/PullBranchTests.Pull_branch_with_1_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/PullBranchTests.Pull_branch_with_1_commit.approved.txt deleted file mode 100644 index aeeb7076a6..0000000000 --- a/GitVersionTask.Tests/BranchFinders/PullBranchTests.Pull_branch_with_1_commit.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 1, - "Minor": 1, - "Patch": 0, - "PreReleaseTag": { - "Name": "PullRequest", - "Number": 1735 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "pull/1735/merge", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/PullBranchTests.Pull_branch_with_2_commits.approved.txt b/GitVersionTask.Tests/BranchFinders/PullBranchTests.Pull_branch_with_2_commits.approved.txt deleted file mode 100644 index a4909a65d4..0000000000 --- a/GitVersionTask.Tests/BranchFinders/PullBranchTests.Pull_branch_with_2_commits.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 1, - "Minor": 1, - "Patch": 0, - "PreReleaseTag": { - "Name": "PullRequest", - "Number": 1735 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "pull/1735/merge", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/PullBranchTests.cs b/GitVersionTask.Tests/BranchFinders/PullBranchTests.cs deleted file mode 100644 index d6ec86fb36..0000000000 --- a/GitVersionTask.Tests/BranchFinders/PullBranchTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -using GitVersion; -using LibGit2Sharp; -using NUnit.Framework; -using ObjectApproval; - -[TestFixture] -public class PullBranchTests : Lg2sHelperBase -{ - [Test, Ignore("Not valid since Github wont allow empty pulls")] - public void Pull_request_with_no_commit() - { - } - - [Test] - public void Invalid_pull_branch_name() - { - AssertInvalidPullBranchName("pull"); - AssertInvalidPullBranchName("pull/1735"); - AssertInvalidPullBranchName("pull/merge"); - AssertInvalidPullBranchName("pull/1735/a/merge"); - AssertInvalidPullBranchName("pull/1735-a/merge"); - AssertInvalidPullBranchName("pull/-1735/merge"); - AssertInvalidPullBranchName("pull/1735.1/merge"); - AssertInvalidPullBranchName("pull/merge/1735"); - AssertInvalidPullBranchName("merge/1735/pull"); - } - - void AssertInvalidPullBranchName(string invalidFakePullBranchName) - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - var branchingCommit = repo.Branches["develop"].Tip; - var pullBranch = repo.Branches.Add(invalidFakePullBranchName, branchingCommit); - - var finder = new PullVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, pullBranch, new Config()))); - } - } - - [Test] - public void Pull_branch_with_1_commit() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - // Create a pull request branch from the parent of current develop tip - repo.Branches.Add("pull/1735/merge", "develop~").ForceCheckout(); - - AddOneCommitToHead(repo, "code"); - - var pullBranch = repo.Head; - - var finder = new PullVersionFinder(); - - var configuration = new Config(); - var version = finder.FindVersion(new GitVersionContext(repo, pullBranch, configuration)); - - var masterVersion = FindersHelper.RetrieveMasterVersion(repo, configuration); - - Assert.AreEqual(masterVersion.Minor + 1, version.Minor, "Minor should be master.Minor+1"); - Assert.AreEqual(1735, version.PreReleaseTag.Number); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - } - - [Test] - public void Pull_branch_with_2_commits() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - // Create a pull request branch from the parent of current develop tip - repo.Branches.Add("pull/1735/merge", "develop~").ForceCheckout(); - - AddOneCommitToHead(repo, "code"); - AddOneCommitToHead(repo, "more code"); - - var pullBranch = repo.Head; - - var finder = new PullVersionFinder(); - - var configuration = new Config(); - var version = finder.FindVersion(new GitVersionContext(repo, pullBranch, configuration)); - - var masterVersion = FindersHelper.RetrieveMasterVersion(repo, configuration); - - Assert.AreEqual(masterVersion.Minor + 1, version.Minor, "Minor should be master.Minor+1"); - Assert.AreEqual(1735, version.PreReleaseTag.Number); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_no_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_no_tag.approved.txt deleted file mode 100644 index ccb14b0979..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_no_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 5, - "Patch": 0, - "PreReleaseTag": { - "Name": "beta", - "Number": 0 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "release-0.5.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_with_tag_on_branching_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_with_tag_on_branching_commit.approved.txt deleted file mode 100644 index 25fec5529a..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_with_tag_on_branching_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 5, - "Patch": 0, - "PreReleaseTag": { - "Name": "alpha", - "Number": 5 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "release-0.5.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_with_tag_on_new_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_with_tag_on_new_commit.approved.txt deleted file mode 100644 index 25fec5529a..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.First_commit_with_tag_on_new_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 5, - "Patch": 0, - "PreReleaseTag": { - "Name": "alpha", - "Number": 5 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "release-0.5.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.No_commits_with_no_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.No_commits_with_no_tag.approved.txt deleted file mode 100644 index 570a2d486a..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.No_commits_with_no_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 3, - "Patch": 0, - "PreReleaseTag": { - "Name": "beta", - "Number": 0 - }, - "BuildMetaData": { - "CommitsSinceTag": 0, - "Branch": "release-0.3.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "2013-11-17T12:59:39Z", - "ReleaseDate": "2013-11-17T12:59:39Z", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.No_commits_with_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.No_commits_with_tag.approved.txt deleted file mode 100644 index 9eef422d1a..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.No_commits_with_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 3, - "Patch": 0, - "PreReleaseTag": { - "Name": "alpha", - "Number": 5 - }, - "BuildMetaData": { - "CommitsSinceTag": 0, - "Branch": "release-0.3.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "2013-11-17T12:59:39Z", - "ReleaseDate": "2013-11-17T12:59:39Z", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Override_stage_using_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.Override_stage_using_tag.approved.txt deleted file mode 100644 index ea932eb5a1..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Override_stage_using_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 4, - "Patch": 0, - "PreReleaseTag": { - "Name": "RC", - "Number": 4 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "release-0.4.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Second_commit.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.Second_commit.approved.txt deleted file mode 100644 index affb055522..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Second_commit.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 4, - "Patch": 0, - "PreReleaseTag": { - "Name": "alpha", - "Number": 5 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "release-0.4.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Second_commit_with_no_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.Second_commit_with_no_tag.approved.txt deleted file mode 100644 index 3a5c9c2c02..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Second_commit_with_no_tag.approved.txt +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Major": 0, - "Minor": 4, - "Patch": 0, - "PreReleaseTag": { - "Name": "beta", - "Number": 0 - }, - "BuildMetaData": { - "CommitsSinceTag": 2, - "Branch": "release-0.4.0", - "Sha": "000000000000000000000000000000000000000", - "OriginalReleaseDate": "", - "ReleaseDate": "", - "OtherMetaData": null - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Tag_on_commit_should_be_exact_tag.approved.txt b/GitVersionTask.Tests/BranchFinders/ReleaseTests.Tag_on_commit_should_be_exact_tag.approved.txt deleted file mode 100644 index 089ae71ab9..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.Tag_on_commit_should_be_exact_tag.approved.txt +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Major": 5, - "Minor": 0, - "Patch": 0, - "PreReleaseTag": { - "Name": "beta", - "Number": 2 - }, - "BuildMetaData": { - "CommitsSinceTag": 1, - "Branch": "release-5.0.0", - "Sha": "000000000000000000000000000000000000000", - "OtherMetaData": null, - "CommitDate": "" - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/BranchFinders/ReleaseTests.cs b/GitVersionTask.Tests/BranchFinders/ReleaseTests.cs deleted file mode 100644 index 57d4e3ba79..0000000000 --- a/GitVersionTask.Tests/BranchFinders/ReleaseTests.cs +++ /dev/null @@ -1,44 +0,0 @@ -using GitVersion; -using LibGit2Sharp; -using NUnit.Framework; -using ObjectApproval; - -[TestFixture] -public class ReleaseTests : Lg2sHelperBase -{ - [Test] - public void EnsureAReleaseBranchNameDoesNotExposeAPatchSegment() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - const string branchName = "release-0.3.1"; - - var branchingCommit = repo.Branches["develop"].Tip; - var releaseBranch = repo.Branches.Add(branchName, branchingCommit); - - var finder = new ReleaseVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, releaseBranch, new Config()))); - } - } - - [Test] - public void Tag_on_commit_should_be_exact_tag() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - // Create a release branch from the parent of current develop tip - repo.Branches.Add("release-5.0.0", "develop~").ForceCheckout(); - - AddOneCommitToHead(repo, "code"); - AddTag(repo, "5.0.0-beta2"); - - var finder = new ReleaseVersionFinder(); - - var version = finder.FindVersion(new GitVersionContext(repo, repo.Head, new Config())); - ObjectApprover.VerifyWithJson(version, Scrubbers.GuidAndDateScrubber); - } - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/GetVersionTaskTests.cs b/GitVersionTask.Tests/GetVersionTaskTests.cs index 9c1c57280f..ed3e452a77 100644 --- a/GitVersionTask.Tests/GetVersionTaskTests.cs +++ b/GitVersionTask.Tests/GetVersionTaskTests.cs @@ -1,9 +1,9 @@ -using System; -using System.Linq; +using System.Linq; using GitVersion; using GitVersionTask; using Microsoft.Build.Framework; using NUnit.Framework; +using Shouldly; [TestFixture] public class GetVersionTaskTests @@ -11,18 +11,15 @@ public class GetVersionTaskTests [Test] public void OutputsShouldMatchVariableProvider() { - var taskType = typeof(GetVersion); - var properties = taskType.GetProperties() + var taskProperties = typeof(GetVersion) + .GetProperties() .Where(p => p.GetCustomAttributes(typeof(OutputAttribute), false).Any()) .Select(p => p.Name); - var variables = VariableProvider.GetVariablesFor(new SemanticVersion - { - Major = 1, - Minor = 2, - Patch = 3, - BuildMetaData = new SemanticVersionBuildMetaData(5, "develop", "commitSha",DateTimeOffset.Parse("2014-03-06 23:59:59Z")) - }, new Config()).Keys; - CollectionAssert.AreEquivalent(properties, variables); + var variablesProperties = typeof(VersionVariables) + .GetProperties() + .Select(p => p.Name); + + taskProperties.ShouldBe(variablesProperties, ignoreOrder: true); } } diff --git a/GitVersionTask.Tests/GitFlow/GitFlowVersionFinderTests.cs b/GitVersionTask.Tests/GitFlow/GitFlowVersionFinderTests.cs index b935ee3d94..7512a99248 100644 --- a/GitVersionTask.Tests/GitFlow/GitFlowVersionFinderTests.cs +++ b/GitVersionTask.Tests/GitFlow/GitFlowVersionFinderTests.cs @@ -1,5 +1,4 @@ -using System.IO; -using GitVersion; +using GitVersion; using LibGit2Sharp; using NUnit.Framework; using ObjectApproval; @@ -23,85 +22,6 @@ public void RequiresALocalMasterBranch() } } - [Test, Ignore("Need a way to enforce this check")] - public void RequiresALocalDevelopBranch() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - repo.Branches["feature/one"].ForceCheckout(); - - repo.Branches.Remove("develop"); - - var finder = new GitVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, new Config()))); - } - } - - [Test] - public void AFeatureBranchIsRequiredToBranchOffOfDevelopBranch() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - const string branchName = "feature/unborn"; - - // Create a new unborn feature branch sharing no history with "develop" - repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName); - - AddOneCommitToHead(repo, "feature"); - - var feature = repo.Branches[branchName]; - - var finder = new GitVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, feature, new Config()))); - } - } - - [Test] - public void AHotfixBranchIsRequiredToBranchOffOfMasterBranch() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - const string branchName = "hotfix/1.0.2"; - - // Create a new unborn hotfix branch sharing no history with "master" - repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName); - - AddOneCommitToHead(repo, "hotfix"); - - var feature = repo.Branches[branchName]; - - var finder = new GitVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, feature, new Config()))); - } - } - - [Test] - public void APullRequestBranchIsRequiredToBranchOffOfDevelopBranch() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - const string branchName = "pull/1735/merge"; - - // Create a new unborn pull request branch sharing no history with "develop" - repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName); - - AddOneCommitToHead(repo, "code"); - - var pull = repo.Branches[branchName]; - - var finder = new GitVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, pull, new Config()))); - } - } - [Test] public void AFeatureBranchDoesNotRequireASpecificPrefix() { @@ -143,30 +63,4 @@ public void AFeatureBranchPrefixIsNotIncludedInTag() ObjectApprover.VerifyWithJson(versionAndBranch, Scrubbers.GuidAndDateScrubber); } } - - [Test] - public void AReleaseBranchIsRequiredToBranchOffOfDevelopBranch() - { - var repoPath = Clone(ASBMTestRepoWorkingDirPath); - using (var repo = new Repository(repoPath)) - { - const string branchName = "release/1.2.0"; - - // Create a new unborn release branch sharing no history with "develop" - repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName); - - var path = Path.Combine(repo.Info.WorkingDirectory, "README"); - File.AppendAllText(path, "Release\n"); - - repo.Index.Stage(path); - var sign = SignatureBuilder.SignatureNow(); - repo.Commit("release unborn", sign, sign); - - var feature = repo.Branches[branchName]; - - var finder = new GitVersionFinder(); - - Assert.Throws(() => finder.FindVersion(new GitVersionContext(repo, feature, new Config()))); - } - } } \ No newline at end of file diff --git a/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchDoesNotRequireASpecificPrefix.approved.txt b/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchDoesNotRequireASpecificPrefix.approved.txt index 838ceacca0..31e0f9e5d3 100644 --- a/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchDoesNotRequireASpecificPrefix.approved.txt +++ b/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchDoesNotRequireASpecificPrefix.approved.txt @@ -1,10 +1,10 @@ { "Major": 1, - "Minor": 1, - "Patch": 0, + "Minor": 0, + "Patch": 2, "PreReleaseTag": { "Name": "every-feature-is-welcome", - "Number": null + "Number": 1 }, "BuildMetaData": { "CommitsSinceTag": 1, diff --git a/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchPrefixIsNotIncludedInTag.approved.txt b/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchPrefixIsNotIncludedInTag.approved.txt index a7a459f70c..11a2f20b3a 100644 --- a/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchPrefixIsNotIncludedInTag.approved.txt +++ b/GitVersionTask.Tests/GitFlow/GitVersionFinderTests.AFeatureBranchPrefixIsNotIncludedInTag.approved.txt @@ -4,7 +4,7 @@ "Patch": 0, "PreReleaseTag": { "Name": "ABC-1234_SomeDescription", - "Number": null + "Number": 1 }, "BuildMetaData": { "CommitsSinceTag": 1, diff --git a/GitVersionTask.Tests/GitHubFlow/MergedBranchesWithVersionFinderTests.cs b/GitVersionTask.Tests/GitHubFlow/MergedBranchesWithVersionFinderTests.cs deleted file mode 100644 index 643b28096f..0000000000 --- a/GitVersionTask.Tests/GitHubFlow/MergedBranchesWithVersionFinderTests.cs +++ /dev/null @@ -1,26 +0,0 @@ -using GitVersion; -using NUnit.Framework; -using Shouldly; - -public class MergedBranchesWithVersionFinderTests -{ - [Test] - public void ShouldFindMergeCommit() - { - var currentBranch = new MockBranch("master") - { - new MockCommit(), - new MockCommit(), - new MockMergeCommit - { - MessageEx = "Merge branch 'release-2.0.0'" - } - }; - var sut = new MergedBranchesWithVersionFinder(new GitVersionContext(null, currentBranch, new Config())); - - SemanticVersion version; - sut.TryGetVersion(out version); - - version.ToString().ShouldBe("2.0.0"); - } -} \ No newline at end of file diff --git a/GitVersionTask.Tests/GitVersionTask.Tests.csproj b/GitVersionTask.Tests/GitVersionTask.Tests.csproj index 67963f08af..b9c62939ea 100644 --- a/GitVersionTask.Tests/GitVersionTask.Tests.csproj +++ b/GitVersionTask.Tests/GitVersionTask.Tests.csproj @@ -86,49 +86,22 @@ - - - - - - + - - - - - - - - - - - - - - - - - - - - - - diff --git a/GitVersionTask.Tests/Helpers/Constants.cs b/GitVersionTask.Tests/Helpers/Constants.cs deleted file mode 100644 index 031f210299..0000000000 --- a/GitVersionTask.Tests/Helpers/Constants.cs +++ /dev/null @@ -1,6 +0,0 @@ - -public static class Constants -{ - public const string TemporaryReposPath = "TestRepos"; - -} \ No newline at end of file diff --git a/GitVersionTask.Tests/Helpers/FindersHelper.cs b/GitVersionTask.Tests/Helpers/FindersHelper.cs deleted file mode 100644 index 7627a8b6c9..0000000000 --- a/GitVersionTask.Tests/Helpers/FindersHelper.cs +++ /dev/null @@ -1,12 +0,0 @@ -using GitVersion; -using LibGit2Sharp; - -public static class FindersHelper -{ - public static SemanticVersion RetrieveMasterVersion(Repository repo, Config configuration) - { - var masterFinder = new MasterVersionFinder(); - var masterVersion = masterFinder.FindVersion(new GitVersionContext(repo, repo.Branches["master"], configuration)); - return masterVersion; - } -} diff --git a/GitVersionTask.Tests/Helpers/Lg2sHelperBase.cs b/GitVersionTask.Tests/Helpers/Lg2sHelperBase.cs index 913529e86b..64d7bdcdff 100644 --- a/GitVersionTask.Tests/Helpers/Lg2sHelperBase.cs +++ b/GitVersionTask.Tests/Helpers/Lg2sHelperBase.cs @@ -8,6 +8,7 @@ public abstract class Lg2sHelperBase : IPostTestDirectoryRemover { + public const string TemporaryReposPath = "TestRepos"; List directories; [TestFixtureSetUp] @@ -30,9 +31,9 @@ static Lg2sHelperBase() // Do the set up in the static ctor so it only happens once SetUpTestEnvironment(); - if (Directory.Exists(Constants.TemporaryReposPath)) + if (Directory.Exists(TemporaryReposPath)) { - DirectoryHelper.DeleteSubDirectories(Constants.TemporaryReposPath); + DirectoryHelper.DeleteSubDirectories(TemporaryReposPath); } } @@ -58,7 +59,7 @@ static void SetUpTestEnvironment() protected SelfCleaningDirectory BuildSelfCleaningDirectory() { - return new SelfCleaningDirectory(this); + return new SelfCleaningDirectory(this, BuildTempPath()); } protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path) @@ -66,6 +67,11 @@ protected SelfCleaningDirectory BuildSelfCleaningDirectory(string path) return new SelfCleaningDirectory(this, path); } + protected static string BuildTempPath() + { + return Path.Combine(TemporaryReposPath, Guid.NewGuid().ToString().Substring(0, 8)); + } + protected string Clone(string sourceDirectoryPath, params string[] additionalSourcePaths) { var scd = BuildSelfCleaningDirectory(); @@ -101,7 +107,7 @@ protected static Commit AddOneCommitToHead(Repository repo, string type) { var randomFile = Path.Combine(repo.Info.WorkingDirectory, Guid.NewGuid().ToString()); File.WriteAllText(randomFile, string.Empty); - repo.Index.Stage(randomFile); + repo.Stage(randomFile); var sign = SignatureBuilder.SignatureNow(); return repo.Commit(type + " commit", sign, sign); } @@ -110,7 +116,7 @@ protected static void AddTag(Repository repo, string tagName) { var randomFile = Path.Combine(repo.Info.WorkingDirectory, Guid.NewGuid().ToString()); File.WriteAllText(randomFile, string.Empty); - repo.Index.Stage(randomFile); + repo.Stage(randomFile); var sign = SignatureBuilder.SignatureNow(); repo.ApplyTag(tagName, repo.Head.Tip.Id.Sha, sign, "foo"); } diff --git a/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs b/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs index 4f6fd14268..465d6b6219 100644 --- a/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs +++ b/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs @@ -3,11 +3,6 @@ public class SelfCleaningDirectory { - public SelfCleaningDirectory(IPostTestDirectoryRemover directoryRemover) - : this(directoryRemover, BuildTempPath()) - { - } - public SelfCleaningDirectory(IPostTestDirectoryRemover directoryRemover, string path) { if (Directory.Exists(path)) @@ -20,9 +15,4 @@ public SelfCleaningDirectory(IPostTestDirectoryRemover directoryRemover, string } public string DirectoryPath; - - protected static string BuildTempPath() - { - return Path.Combine(Constants.TemporaryReposPath, Guid.NewGuid().ToString().Substring(0, 8)); - } } \ No newline at end of file diff --git a/GitVersionTask.Tests/IntegrationTests.cs b/GitVersionTask.Tests/IntegrationTests.cs index 3b417cca80..3687e8c0d9 100644 --- a/GitVersionTask.Tests/IntegrationTests.cs +++ b/GitVersionTask.Tests/IntegrationTests.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Linq; using GitVersion; +using GitVersionCore.Tests; using LibGit2Sharp; using NUnit.Framework; @@ -17,7 +18,7 @@ public void ProcessAllTheCommits() foreach (var commit in branch.Commits) { SemanticVersion version; - if (MergeMessageParser.TryParse(commit, new Config(), out version)) + if (MergeMessageParser.TryParse(commit, new TestEffectiveConfiguration(), out version)) { Debug.WriteLine("{0}.{1}.{2}", version.Major, version.Minor, version.Patch); } diff --git a/GitVersionTask.Tests/MergeMessageParserTests.cs b/GitVersionTask.Tests/MergeMessageParserTests.cs index caf2de3210..9b5972cf2e 100644 --- a/GitVersionTask.Tests/MergeMessageParserTests.cs +++ b/GitVersionTask.Tests/MergeMessageParserTests.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using GitVersion; +using GitVersionCore.Tests; using LibGit2Sharp; using NUnit.Framework; using Shouldly; @@ -49,7 +50,7 @@ static void AssertMereMessage(string message, string expectedVersion, List(() => task.InnerExecute()); - Assert.AreEqual("Unexpected assembly versioning scheme 'Boom'.", exception.Message); - } - [SetUp] public void SetUp() { diff --git a/GitVersionTask.Tests/VersionAndBranchFinderTests.cs b/GitVersionTask.Tests/VersionAndBranchFinderTests.cs index 8028558365..ea7d089cf3 100644 --- a/GitVersionTask.Tests/VersionAndBranchFinderTests.cs +++ b/GitVersionTask.Tests/VersionAndBranchFinderTests.cs @@ -1,4 +1,5 @@ -using GitVersion; +using System; +using GitVersion; using LibGit2Sharp; using NUnit.Framework; @@ -17,7 +18,8 @@ public void ShouldBeAbleGetVersionFromGitDir() AddOneCommitToHead(repo, "code"); } - CachedVersion versionAndBranch; + + Tuple versionAndBranch; VersionAndBranchFinder.TryGetVersion(ASBMTestRepoWorkingDirPath, out versionAndBranch, new Config()); Assert.IsNotNull(versionAndBranch); } diff --git a/GitVersionTask.Tests/VersionOnMasterFinderTests.cs b/GitVersionTask.Tests/VersionOnMasterFinderTests.cs deleted file mode 100644 index 53252f9291..0000000000 --- a/GitVersionTask.Tests/VersionOnMasterFinderTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using FluentDate; -using FluentDateTimeOffset; -using GitVersion; -using LibGit2Sharp; -using NUnit.Framework; -using ObjectApproval; - -[TestFixture] -public class VersionOnMasterFinderTests -{ - [Test] - public void Should_find_previous_commit_that_was_at_least_a_minor_bump() - { - var finder = new VersionOnMasterFinder(); - - var dateTime = new DateTimeOffset(2000, 10, 10, 0, 0, 0, new TimeSpan(0)); - var signature = 2.Seconds().Before(dateTime).ToSignature(); - - const string sha = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"; - - var repository = new MockRepository - { - Branches = new MockBranchCollection - { - new MockBranch("master") - { - new MockMergeCommit(new ObjectId(sha)) - { - MessageEx = "Merge branch 'hotfix-0.3.0'", - CommitterEx = signature - }, - new MockMergeCommit - { - MessageEx = "Merge branch 'hotfix-0.3.1'", - CommitterEx = signature, - }, - new MockMergeCommit - { - MessageEx = "Merge branch 'hotfix-0.2.0'", - CommitterEx = signature - }, - }, - } - }; - var version = finder.Execute(new GitVersionContext(repository, null, new Config()), 1.Seconds().Ago()); - ObjectApprover.VerifyWithJson(version); - } -} \ No newline at end of file diff --git a/GitVersionTask/AssemblyInfoBuilder/AssemblyInfoBuilder.cs b/GitVersionTask/AssemblyInfoBuilder/AssemblyInfoBuilder.cs index 2d81db02ef..dac9193ea8 100644 --- a/GitVersionTask/AssemblyInfoBuilder/AssemblyInfoBuilder.cs +++ b/GitVersionTask/AssemblyInfoBuilder/AssemblyInfoBuilder.cs @@ -6,10 +6,10 @@ public class AssemblyInfoBuilder { public CachedVersion CachedVersion; - public string GetAssemblyInfoText(Config configuration) + public string GetAssemblyInfoText(EffectiveConfiguration configuration) { var semanticVersion = CachedVersion.SemanticVersion; - var vars = VariableProvider.GetVariablesFor(semanticVersion, configuration); + var vars = VariableProvider.GetVariablesFor(semanticVersion, configuration.AssemblyVersioningScheme, configuration.VersioningMode); var assemblyInfo = string.Format(@" using System; using System.Reflection; @@ -17,17 +17,15 @@ public string GetAssemblyInfoText(Config configuration) [assembly: AssemblyVersion(""{0}"")] [assembly: AssemblyFileVersion(""{1}"")] [assembly: AssemblyInformationalVersion(""{2}"")] -[assembly: ReleaseDate(""{3}"", ""{4}"")] +[assembly: ReleaseDate(""{3}"")] [System.Runtime.CompilerServices.CompilerGenerated] sealed class ReleaseDateAttribute : System.Attribute {{ - public string OriginalDate {{ get; private set; }} public string Date {{ get; private set; }} - public ReleaseDateAttribute(string originalDate, string date) + public ReleaseDateAttribute(string date) {{ - OriginalDate = originalDate; Date = date; }} }} @@ -35,14 +33,13 @@ public ReleaseDateAttribute(string originalDate, string date) [System.Runtime.CompilerServices.CompilerGenerated] static class GitVersionInformation {{ -{5} +{4} }} -", vars[VariableProvider.AssemblySemVer], - vars[VariableProvider.AssemblyFileSemVer], +", vars.AssemblySemVer, + vars.AssemblySemVer, semanticVersion.ToString("i"), - CachedVersion.MasterReleaseDate.UtcDateTime.ToString("yyyy-MM-dd"), semanticVersion.BuildMetaData.CommitDate.UtcDateTime.ToString("yyyy-MM-dd"), GenerateVariableMembers(vars)); diff --git a/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs b/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs index e5d12f2b41..90ece7366e 100644 --- a/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs +++ b/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs @@ -10,16 +10,6 @@ public class UpdateAssemblyInfo : Task { - public string AssemblyVersioningScheme { get; set; } - - public string DevelopBranchTag { get; set; } - - public string ReleaseBranchTag { get; set; } - - public string TagPrefix { get; set; } - - public string NextVersion { get; set; } - [Required] public string SolutionDirectory { get; set; } @@ -72,7 +62,6 @@ public override bool Execute() public void InnerExecute() { - TempFileTracker.DeleteTempFiles(); InvalidFileChecker.CheckForInvalidFiles(CompileFiles, ProjectFile); @@ -82,51 +71,16 @@ public void InnerExecute() return; var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); - if (!string.IsNullOrEmpty(AssemblyVersioningScheme)) - { - AssemblyVersioningScheme versioningScheme; - if (Enum.TryParse(AssemblyVersioningScheme, true, out versioningScheme)) - { - configuration.AssemblyVersioningScheme = versioningScheme; - } - else - { - throw new WarningException(string.Format("Unexpected assembly versioning scheme '{0}'.", AssemblyVersioningScheme)); - } - } - - // TODO This should be covered by tests - // TODO would be good to not have to duplicate this in both msbuild tasks - // Null is intentional. Empty string means the user has set the value to an empty string and wants to clear the tag - if (DevelopBranchTag != null) - { - configuration.DevelopBranchTag = DevelopBranchTag; - } - - if (ReleaseBranchTag != null) - { - configuration.ReleaseBranchTag = ReleaseBranchTag; - } - - if (TagPrefix != null) - { - configuration.TagPrefix = TagPrefix; - } - - if (NextVersion != null) - { - configuration.NextVersion = NextVersion; - } - CachedVersion semanticVersion; + Tuple semanticVersion; if (!VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out semanticVersion, configuration)) { return; } - CreateTempAssemblyInfo(semanticVersion, configuration); + CreateTempAssemblyInfo(semanticVersion.Item1, semanticVersion.Item2.Configuration); } - void CreateTempAssemblyInfo(CachedVersion semanticVersion, Config configuration) + void CreateTempAssemblyInfo(CachedVersion semanticVersion, EffectiveConfiguration configuration) { var assemblyInfoBuilder = new AssemblyInfoBuilder { diff --git a/GitVersionTask/CachedVersion.cs b/GitVersionTask/CachedVersion.cs index a52c011a29..c20c0d2ed7 100644 --- a/GitVersionTask/CachedVersion.cs +++ b/GitVersionTask/CachedVersion.cs @@ -1,9 +1,7 @@ -using System; -using GitVersion; +using GitVersion; public class CachedVersion { public SemanticVersion SemanticVersion; public long Timestamp; - public DateTimeOffset MasterReleaseDate; } \ No newline at end of file diff --git a/GitVersionTask/GetVersion.cs b/GitVersionTask/GetVersion.cs index 5e5d44f866..dcea962664 100644 --- a/GitVersionTask/GetVersion.cs +++ b/GitVersionTask/GetVersion.cs @@ -48,21 +48,12 @@ public class GetVersion : Task [Output] public string AssemblySemVer { get; set; } - [Output] - public string AssemblyFileSemVer { get; set; } - [Output] public string FullSemVer { get; set; } [Output] public string InformationalVersion { get; set; } - [Output] - public string ClassicVersion { get; set; } - - [Output] - public string ClassicVersionWithTag { get; set; } - [Output] public string BranchName { get; set; } @@ -75,14 +66,6 @@ public class GetVersion : Task [Output] public string NuGetVersion { get; set; } - public string DevelopBranchTag { get; set; } - - public string ReleaseBranchTag { get; set; } - - public string TagPrefix { get; set; } - - public string NextVersion { get; set; } - TaskLogger logger; IFileSystem fileSystem; @@ -98,36 +81,16 @@ public override bool Execute() { try { - CachedVersion versionAndBranch; + Tuple versionAndBranch; var gitDirectory = GitDirFinder.TreeWalkForGitDir(SolutionDirectory); var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); - // TODO This should be covered by tests - // Null is intentional. Empty string means the user has set the value to an empty string and wants to clear the tag - if (DevelopBranchTag != null) - { - configuration.DevelopBranchTag = DevelopBranchTag; - } - - if (ReleaseBranchTag != null) - { - configuration.ReleaseBranchTag = ReleaseBranchTag; - } - - if (TagPrefix != null) - { - configuration.TagPrefix = TagPrefix; - } - - if (NextVersion != null) - { - configuration.NextVersion = NextVersion; - } - if (VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out versionAndBranch, configuration)) { var thisType = typeof(GetVersion); - var variables = VariableProvider.GetVariablesFor(versionAndBranch.SemanticVersion, configuration); + var cachedVersion = versionAndBranch.Item1; + var effectiveConfiguration = versionAndBranch.Item2.Configuration; + var variables = VariableProvider.GetVariablesFor(cachedVersion.SemanticVersion, effectiveConfiguration.AssemblyVersioningScheme, effectiveConfiguration.VersioningMode); foreach (var variable in variables) { thisType.GetProperty(variable.Key).SetValue(this, variable.Value, null); diff --git a/GitVersionTask/VersionAndBranchFinder.cs b/GitVersionTask/VersionAndBranchFinder.cs index 180696064c..81ee90e302 100644 --- a/GitVersionTask/VersionAndBranchFinder.cs +++ b/GitVersionTask/VersionAndBranchFinder.cs @@ -1,10 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using GitVersion; public static class VersionAndBranchFinder { static List processedDirectories = new List(); - public static bool TryGetVersion(string directory, out CachedVersion versionAndBranch, Config configuration) + public static bool TryGetVersion(string directory, out Tuple versionAndBranch, Config configuration) { var gitDirectory = GitDirFinder.TreeWalkForGitDir(directory); diff --git a/GitVersionTask/VersionCache.cs b/GitVersionTask/VersionCache.cs index 93e7b831b6..2ed7654d8c 100644 --- a/GitVersionTask/VersionCache.cs +++ b/GitVersionTask/VersionCache.cs @@ -1,11 +1,12 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using GitVersion; public static class VersionCache { - static Dictionary versionCacheVersions = new Dictionary(); + static Dictionary> versionCacheVersions = new Dictionary>(); - public static CachedVersion GetVersion(string gitDirectory, Config configuration) + public static Tuple GetVersion(string gitDirectory, Config configuration) { using (var repo = RepositoryLoader.GetRepo(gitDirectory)) { @@ -13,26 +14,24 @@ public static CachedVersion GetVersion(string gitDirectory, Config configuration var context = new GitVersionContext(repo, configuration); var ticks = DirectoryDateFinder.GetLastDirectoryWrite(gitDirectory); var key = string.Format("{0}:{1}:{2}", repo.Head.CanonicalName, repo.Head.Tip.Sha, ticks); - CachedVersion cachedVersion; - if (versionCacheVersions.TryGetValue(key, out cachedVersion)) + + Tuple result; + if (versionCacheVersions.TryGetValue(key, out result)) { - if (cachedVersion.Timestamp != ticks) + if (result.Item1.Timestamp != ticks) { Logger.WriteInfo("Change detected. flushing cache."); - cachedVersion.SemanticVersion = versionFinder.FindVersion(context); - cachedVersion.MasterReleaseDate = LastMinorVersionFinder.Execute(repo, new Config(), repo.Head.Tip); + result.Item1.SemanticVersion = versionFinder.FindVersion(context); } - return cachedVersion; + return result; } Logger.WriteInfo("Version not in cache. Calculating version."); - return versionCacheVersions[key] = new CachedVersion + return versionCacheVersions[key] = Tuple.Create(new CachedVersion { SemanticVersion = versionFinder.FindVersion(context), - MasterReleaseDate = LastMinorVersionFinder.Execute(repo, new Config(), repo.Head.Tip), Timestamp = ticks - }; - + }, context); } } diff --git a/GitVersionTask/WriteVersionInfoToBuildLog.cs b/GitVersionTask/WriteVersionInfoToBuildLog.cs index 67b08e1ec4..14a6baa08c 100644 --- a/GitVersionTask/WriteVersionInfoToBuildLog.cs +++ b/GitVersionTask/WriteVersionInfoToBuildLog.cs @@ -49,26 +49,32 @@ public override bool Execute() public void InnerExecute() { - CachedVersion semanticVersion; + Tuple result; var gitDirectory = GitDirFinder.TreeWalkForGitDir(SolutionDirectory); var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); - if (!VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out semanticVersion, configuration)) + if (!VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out result, configuration)) { return; } var authentication = new Authentication(); - WriteIntegrationParameters(semanticVersion, BuildServerList.GetApplicableBuildServers(authentication)); + + var cachedVersion = result.Item1; + var assemblyVersioningScheme = result.Item2.Configuration.AssemblyVersioningScheme; + var versioningMode = result.Item2.Configuration.VersioningMode; + + var variablesFor = VariableProvider.GetVariablesFor(cachedVersion.SemanticVersion, assemblyVersioningScheme, versioningMode); + WriteIntegrationParameters(cachedVersion, BuildServerList.GetApplicableBuildServers(authentication), variablesFor); } - public void WriteIntegrationParameters(CachedVersion cachedVersion, IEnumerable applicableBuildServers) + public void WriteIntegrationParameters(CachedVersion cachedVersion, IEnumerable applicableBuildServers, VersionVariables variables) { foreach (var buildServer in applicableBuildServers) { logger.LogInfo(string.Format("Executing GenerateSetVersionMessage for '{0}'.", buildServer.GetType().Name)); logger.LogInfo(buildServer.GenerateSetVersionMessage(cachedVersion.SemanticVersion.ToString())); logger.LogInfo(string.Format("Executing GenerateBuildLogOutput for '{0}'.", buildServer.GetType().Name)); - foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(cachedVersion.SemanticVersion, buildServer)) + foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(buildServer, variables)) { logger.LogInfo(buildParameter); }