diff --git a/src/GitVersionCore.Tests/Approved/cs/AssemblyInfoFileUpdaterTests.Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt b/src/GitVersionCore.Tests/Approved/cs/AssemblyInfoFileUpdaterTests.Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt similarity index 100% rename from src/GitVersionCore.Tests/Approved/cs/AssemblyInfoFileUpdaterTests.Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt rename to src/GitVersionCore.Tests/Approved/cs/AssemblyInfoFileUpdaterTests.Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt diff --git a/src/GitVersionCore.Tests/Approved/fs/AssemblyInfoFileUpdaterTests.Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt b/src/GitVersionCore.Tests/Approved/fs/AssemblyInfoFileUpdaterTests.Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt similarity index 100% rename from src/GitVersionCore.Tests/Approved/fs/AssemblyInfoFileUpdaterTests.Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt rename to src/GitVersionCore.Tests/Approved/fs/AssemblyInfoFileUpdaterTests.Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt diff --git a/src/GitVersionCore.Tests/Approved/vb/AssemblyInfoFileUpdaterTests.Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt b/src/GitVersionCore.Tests/Approved/vb/AssemblyInfoFileUpdaterTests.Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt similarity index 100% rename from src/GitVersionCore.Tests/Approved/vb/AssemblyInfoFileUpdaterTests.Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt rename to src/GitVersionCore.Tests/Approved/vb/AssemblyInfoFileUpdaterTests.Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes.approved.txt diff --git a/src/GitVersionCore.Tests/AssemblyFileVersionTests.cs b/src/GitVersionCore.Tests/AssemblyFileVersionTests.cs index fd24245b48..71deae8190 100644 --- a/src/GitVersionCore.Tests/AssemblyFileVersionTests.cs +++ b/src/GitVersionCore.Tests/AssemblyFileVersionTests.cs @@ -1,7 +1,7 @@ -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.Extensions; +using GitVersion; namespace GitVersionCore.Tests { @@ -26,4 +26,4 @@ public void ValidateAssemblyFileVersionBuilder(AssemblyFileVersioningScheme asse assemblyFileVersion.ShouldBe(versionString); } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs b/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs index bc1e8ecd6a..36eed16543 100644 --- a/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs +++ b/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs @@ -1,15 +1,15 @@ using System; using System.Collections.Generic; using System.IO; -using GitVersion; using NSubstitute; using NUnit.Framework; using Shouldly; using GitVersion.OutputVariables; using GitVersion.Extensions; using GitVersion.Extensions.VersionAssemblyInfoResources; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests { @@ -25,7 +25,11 @@ public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); log = new NullLog(); - variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + variableProvider = new VariableProvider(nextVersionCalculator); } [TestCase("cs")] @@ -398,7 +402,7 @@ public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile [TestCase("vb", "\r\n\r\n' comment\r\n")] [Category("NoMono")] [Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] - public void Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes(string fileExtension, string assemblyFileContent) + public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes(string fileExtension, string assemblyFileContent) { var workingDir = Path.GetTempPath(); var assemblyInfoFile = "AssemblyInfo." + fileExtension; diff --git a/src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs index 400f087676..ef23326ac6 100644 --- a/src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs @@ -1,7 +1,7 @@ using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers @@ -9,8 +9,8 @@ namespace GitVersionCore.Tests.BuildServers [TestFixture] public class AzurePipelinesBuildNumberTests : TestBase { - private string key = "BUILD_BUILDNUMBER"; - private string logPrefix = "##vso[build.updatebuildnumber]"; + private readonly string key = "BUILD_BUILDNUMBER"; + private readonly string logPrefix = "##vso[build.updatebuildnumber]"; private AzurePipelines versionBuilder; private IEnvironment environment; diff --git a/src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs index d63402ac5d..77855b4439 100644 --- a/src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs @@ -1,7 +1,7 @@ using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers @@ -9,7 +9,7 @@ namespace GitVersionCore.Tests.BuildServers [TestFixture] public class AzurePipelinesTests : TestBase { - private string key = "BUILD_BUILDNUMBER"; + private readonly string key = "BUILD_BUILDNUMBER"; private IEnvironment environment; private ILog log; @@ -29,7 +29,7 @@ public void ClearEnvironmentVariableForTest() } [Test] - public void Develop_branch() + public void DevelopBranch() { var versionBuilder = new AzurePipelines(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); diff --git a/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs b/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs index 3dc9640a95..0d0b350e1b 100644 --- a/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.OutputVariables; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests.BuildServers { @@ -22,7 +22,11 @@ public void SetUp() { environment = new TestEnvironment(); log = new NullLog(); - variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + variableProvider = new VariableProvider(nextVersionCalculator); } [Test] diff --git a/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs b/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs index 7c016a7b30..39b85df0c8 100644 --- a/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs @@ -2,13 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Reflection; -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.OutputVariables; using GitVersion.Logging; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests.BuildServers { @@ -25,7 +25,11 @@ public void SetUp() log = new NullLog(); environment = new TestEnvironment(); - variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + variableProvider = new VariableProvider(nextVersionCalculator); } [Test] diff --git a/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs b/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs index 3aeb25b101..126c74b99a 100644 --- a/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs @@ -1,6 +1,6 @@ using NUnit.Framework; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers diff --git a/src/GitVersionCore.Tests/BuildServers/DroneTests.cs b/src/GitVersionCore.Tests/BuildServers/DroneTests.cs index 6890d23a9e..8eb0e97b68 100644 --- a/src/GitVersionCore.Tests/BuildServers/DroneTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/DroneTests.cs @@ -1,5 +1,5 @@ using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; using NUnit.Framework; using Shouldly; @@ -27,7 +27,7 @@ public void TearDown() } [Test] - public void CanApplyToCurrentContext_ShouldBeTrue_WhenEnvironmentVariableIsSet() + public void CanApplyToCurrentContextShouldBeTrueWhenEnvironmentVariableIsSet() { // Arrange var buildServer = new Drone(environment, log); @@ -40,7 +40,7 @@ public void CanApplyToCurrentContext_ShouldBeTrue_WhenEnvironmentVariableIsSet() } [Test] - public void CanApplyToCurrentContext_ShouldBeFalse_WhenEnvironmentVariableIsNotSet() + public void CanApplyToCurrentContextShouldBeFalseWhenEnvironmentVariableIsNotSet() { // Arrange environment.SetEnvironmentVariable("DRONE", ""); @@ -54,7 +54,7 @@ public void CanApplyToCurrentContext_ShouldBeFalse_WhenEnvironmentVariableIsNotS } [Test] - public void GetCurrentBranch_ShouldDroneBranch_InCaseOfPush() + public void GetCurrentBranchShouldDroneBranchInCaseOfPush() { // Arrange const string droneBranch = "droneBranch"; @@ -72,7 +72,7 @@ public void GetCurrentBranch_ShouldDroneBranch_InCaseOfPush() } [Test] - public void GetCurrentBranch_ShouldUseDroneSourceBranch_InCaseOfPullRequestAndNonEmptyDroneSourceBranch() + public void GetCurrentBranchShouldUseDroneSourceBranchInCaseOfPullRequestAndNonEmptyDroneSourceBranch() { // Arrange const string droneSourceBranch = "droneSourceBranch"; @@ -89,13 +89,13 @@ public void GetCurrentBranch_ShouldUseDroneSourceBranch_InCaseOfPullRequestAndNo } [Test] - public void GetCurrentBranch_ShouldUseSourceBranchFromCiCommitRefSpec_InCaseOfPullRequestAndEmptyDroneSourceBranch() + public void GetCurrentBranchShouldUseSourceBranchFromCiCommitRefSpecInCaseOfPullRequestAndEmptyDroneSourceBranch() { // Arrange const string droneSourceBranch = "droneSourceBranch"; const string droneDestinationBranch = "droneDestinationBranch"; - string ciCommitRefSpec = $"{droneSourceBranch}:{droneDestinationBranch}"; + var ciCommitRefSpec = $"{droneSourceBranch}:{droneDestinationBranch}"; environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); @@ -111,7 +111,7 @@ public void GetCurrentBranch_ShouldUseSourceBranchFromCiCommitRefSpec_InCaseOfPu } [Test] - public void GetCurrentBranch_ShouldUseDroneBranch_InCaseOfPullRequestAndEmptyDroneSourceBranchAndCiCommitRefSpec() + public void GetCurrentBranchShouldUseDroneBranchInCaseOfPullRequestAndEmptyDroneSourceBranchAndCiCommitRefSpec() { // Arrange const string droneBranch = "droneBranch"; @@ -131,14 +131,14 @@ public void GetCurrentBranch_ShouldUseDroneBranch_InCaseOfPullRequestAndEmptyDro } [Test] - public void GetCurrentBranch_ShouldUseDroneBranch_InCaseOfPullRequestAndEmptyDroneSourceBranchAndInvalidFormatOfCiCommitRefSpec() + public void GetCurrentBranchShouldUseDroneBranchInCaseOfPullRequestAndEmptyDroneSourceBranchAndInvalidFormatOfCiCommitRefSpec() { // Arrange const string droneBranch = "droneBranch"; const string droneSourceBranch = "droneSourceBranch"; const string droneDestinationBranch = "droneDestinationBranch"; - string ciCommitRefSpec = $"{droneSourceBranch};{droneDestinationBranch}"; + var ciCommitRefSpec = $"{droneSourceBranch};{droneDestinationBranch}"; environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); diff --git a/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs b/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs index 7a66db7d0c..1f45238178 100644 --- a/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs @@ -2,7 +2,7 @@ using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers @@ -36,17 +36,17 @@ public void ClearEnvironmentVariableForTest() [Test] public void CanApplyToCurrentContext() { - EnvRun envrun = new EnvRun(environment, log); - bool applys = envrun.CanApplyToCurrentContext(); + var envrun = new EnvRun(environment, log); + var applys = envrun.CanApplyToCurrentContext(); applys.ShouldBeTrue(); } [Test] - public void CanApplyToCurrentContext_EnvironmentVariableNotSet() + public void CanApplyToCurrentContextEnvironmentVariableNotSet() { environment.SetEnvironmentVariable(EnvVarName, null); - EnvRun envrun = new EnvRun(environment, log); - bool applys = envrun.CanApplyToCurrentContext(); + var envrun = new EnvRun(environment, log); + var applys = envrun.CanApplyToCurrentContext(); applys.ShouldBeFalse(); } @@ -54,7 +54,7 @@ public void CanApplyToCurrentContext_EnvironmentVariableNotSet() [TestCase("1.2.3-rc4")] public void GenerateSetVersionMessage(string fullSemVer) { - EnvRun envrun = new EnvRun(environment, log); + var envrun = new EnvRun(environment, log); var vars = new TestableVersionVariables(fullSemVer: fullSemVer); var version = envrun.GenerateSetVersionMessage(vars); version.ShouldBe(fullSemVer); @@ -64,7 +64,7 @@ public void GenerateSetVersionMessage(string fullSemVer) [TestCase("Version", "1.2.3-rc4", "@@envrun[set name='GitVersion_Version' value='1.2.3-rc4']")] public void GenerateSetParameterMessage(string name, string value, string expected) { - EnvRun envrun = new EnvRun(environment, log); + var envrun = new EnvRun(environment, log); var output = envrun.GenerateSetParameterMessage(name, value); output.ShouldHaveSingleItem(); output[0].ShouldBe(expected); diff --git a/src/GitVersionCore.Tests/BuildServers/EnvironmentVariableJenkinsTests.cs b/src/GitVersionCore.Tests/BuildServers/EnvironmentVariableJenkinsTests.cs index bf715f40e1..94e81f5fa1 100644 --- a/src/GitVersionCore.Tests/BuildServers/EnvironmentVariableJenkinsTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/EnvironmentVariableJenkinsTests.cs @@ -1,7 +1,7 @@ using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers @@ -9,10 +9,10 @@ namespace GitVersionCore.Tests.BuildServers [TestFixture] public class EnvironmentVariableJenkinsTests : TestBase { - private string key = "JENKINS_URL"; - private string branch = "GIT_BRANCH"; - private string localBranch = "GIT_LOCAL_BRANCH"; - private string pipelineBranch = "BRANCH_NAME"; + private readonly string key = "JENKINS_URL"; + private readonly string branch = "GIT_BRANCH"; + private readonly string localBranch = "GIT_LOCAL_BRANCH"; + private readonly string pipelineBranch = "BRANCH_NAME"; private IEnvironment environment; private ILog log; @@ -54,8 +54,8 @@ public void CanNotApplyCurrentContextWhenenvironmentVariableIsNotSet() public void JenkinsTakesLocalBranchNameNotRemoteName() { // Save original values so they can be restored - string branchOrig = environment.GetEnvironmentVariable(branch); - string localBranchOrig = environment.GetEnvironmentVariable(localBranch); + var branchOrig = environment.GetEnvironmentVariable(branch); + var localBranchOrig = environment.GetEnvironmentVariable(localBranch); // Set GIT_BRANCH for testing environment.SetEnvironmentVariable(branch, "origin/master"); @@ -79,9 +79,9 @@ public void JenkinsTakesLocalBranchNameNotRemoteName() public void JenkinsTakesBranchNameInPipelineAsCode() { // Save original values so they can be restored - string branchOrig = environment.GetEnvironmentVariable(branch); - string localBranchOrig = environment.GetEnvironmentVariable(localBranch); - string pipelineBranchOrig = environment.GetEnvironmentVariable(pipelineBranch); + var branchOrig = environment.GetEnvironmentVariable(branch); + var localBranchOrig = environment.GetEnvironmentVariable(localBranch); + var pipelineBranchOrig = environment.GetEnvironmentVariable(pipelineBranch); // Set BRANCH_NAME in pipeline mode environment.SetEnvironmentVariable(pipelineBranch, "master"); diff --git a/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs b/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs index 87e2e5651a..9e107798f9 100755 --- a/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs +++ b/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs @@ -2,13 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Reflection; -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; using GitVersion.OutputVariables; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests.BuildServers { @@ -24,11 +24,15 @@ public void SetUp() { environment = new TestEnvironment(); log = new NullLog(); - variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + variableProvider = new VariableProvider(nextVersionCalculator); } [Test] - public void GenerateSetVersionMessageReturnsVersionAsIs_AlthoughThisIsNotUsedByJenkins() + public void GenerateSetVersionMessageReturnsVersionAsIsAlthoughThisIsNotUsedByJenkins() { var j = new GitLabCi(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); diff --git a/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs b/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs index 55d0ebb51b..ded4c8e058 100644 --- a/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs @@ -2,13 +2,13 @@ using System.Collections.Generic; using System.IO; using System.Reflection; -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; using GitVersion.OutputVariables; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests.BuildServers { @@ -24,11 +24,15 @@ public void SetUp() { environment = new TestEnvironment(); log = new NullLog(); - variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + variableProvider = new VariableProvider(nextVersionCalculator); } [Test] - public void GenerateSetVersionMessageReturnsVersionAsIs_AlthoughThisIsNotUsedByJenkins() + public void GenerateSetVersionMessageReturnsVersionAsIsAlthoughThisIsNotUsedByJenkins() { var j = new Jenkins(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); diff --git a/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs b/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs index 79b0539dd4..670f6d9a5c 100644 --- a/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs @@ -1,6 +1,6 @@ using NUnit.Framework; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers @@ -19,7 +19,7 @@ public void SetUp() } [Test] - public void Develop_branch() + public void DevelopBranch() { var versionBuilder = new MyGet(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); diff --git a/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs b/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs index 832c6ca275..433e2d3e7f 100644 --- a/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs @@ -1,6 +1,6 @@ using NUnit.Framework; using GitVersion.BuildServers; -using GitVersion.Common; +using GitVersion; using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers @@ -19,7 +19,7 @@ public void SetUp() } [Test] - public void Develop_branch() + public void DevelopBranch() { var versionBuilder = new TeamCity(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); diff --git a/src/GitVersionCore.Tests/ConfigProviderTests.cs b/src/GitVersionCore.Tests/ConfigProviderTests.cs index f5b10b5a31..fe3068bff0 100644 --- a/src/GitVersionCore.Tests/ConfigProviderTests.cs +++ b/src/GitVersionCore.Tests/ConfigProviderTests.cs @@ -10,8 +10,10 @@ using GitVersion.Configuration; using GitVersion.VersioningModes; using GitVersion.Extensions; -using GitVersion.Common; +using GitVersion; +using GitVersion.Configuration.Init.Wizard; using GitVersion.Logging; +using Microsoft.Extensions.Options; namespace GitVersionCore.Tests { @@ -23,15 +25,22 @@ public class ConfigProviderTests : TestBase private string repoPath; private IFileSystem fileSystem; private IConfigFileLocator configFileLocator; + private IConfigProvider configProvider; + private IConfigInitWizard configInitWizard; [SetUp] public void Setup() { fileSystem = new TestFileSystem(); var log = new NullLog(); + var stepFactory = new ConfigInitStepFactory(); + configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); configFileLocator = new DefaultConfigFileLocator(fileSystem, log); repoPath = DefaultRepoPath; + var gitPreparer = new GitPreparer(log, Options.Create(new Arguments { TargetPath = repoPath })); + configProvider = new ConfigProvider(fileSystem, log, configFileLocator, gitPreparer, configInitWizard); + ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); } @@ -53,7 +62,7 @@ public void CanReadOldDocument() tag: rc "; SetupConfigFileContent(text); - var error = Should.Throw(() => ConfigurationProvider.Provide(repoPath, configFileLocator)); + var error = Should.Throw(() => configProvider.Provide(repoPath)); error.Message.ShouldContainWithoutWhitespace(@"GitVersion configuration file contains old configuration, please fix the following errors: GitVersion branch configs no longer are keyed by regexes, update: dev(elop)?(ment)?$ -> develop @@ -66,7 +75,7 @@ assemblyVersioningScheme has been replaced by assembly-versioning-scheme [Test] public void OverwritesDefaultsWithProvidedConfig() { - var defaultConfig = ConfigurationProvider.Provide(repoPath, configFileLocator); + var defaultConfig = configProvider.Provide(repoPath); const string text = @" next-version: 2.0.0 branches: @@ -74,7 +83,7 @@ public void OverwritesDefaultsWithProvidedConfig() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment); @@ -87,7 +96,7 @@ public void AllBranchesModeWhenUsingMainline() { const string text = @"mode: Mainline"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); var branches = config.Branches.Select(x => x.Value); branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true); } @@ -101,7 +110,7 @@ public void CanRemoveTag() release: tag: """""; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["release"].Tag.ShouldBe(string.Empty); @@ -116,7 +125,7 @@ public void RegexIsRequired() bug: tag: bugfix"; SetupConfigFileContent(text); - var ex = Should.Throw(() => ConfigurationProvider.Provide(repoPath, configFileLocator)); + var ex = Should.Throw(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe("Branch configuration 'bug' is missing required configuration 'regex'\n\n" + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); } @@ -131,7 +140,7 @@ public void SourceBranchIsRequired() regex: 'bug[/-]' tag: bugfix"; SetupConfigFileContent(text); - var ex = Should.Throw(() => ConfigurationProvider.Provide(repoPath, configFileLocator)); + var ex = Should.Throw(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe("Branch configuration 'bug' is missing required configuration 'source-branches'\n\n" + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); } @@ -147,7 +156,7 @@ public void CanProvideConfigForNewBranch() tag: bugfix source-branches: []"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.Branches["bug"].Regex.ShouldBe("bug[/-]"); config.Branches["bug"].Tag.ShouldBe("bugfix"); @@ -158,7 +167,7 @@ public void NextVersionCanBeInteger() { const string text = "next-version: 2"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0"); } @@ -168,7 +177,7 @@ public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.118998723"); } @@ -178,7 +187,7 @@ public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.12.654651698"); } @@ -189,9 +198,9 @@ public void NextVersionCanHavePatch() [Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void CanWriteOutEffectiveConfiguration() { - var config = ConfigurationProvider.GetEffectiveConfigAsString(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); - config.ShouldMatchApproved(); + config.ToString().ShouldMatchApproved(); } [Test] @@ -204,7 +213,7 @@ public void CanUpdateAssemblyInformationalVersioningScheme() SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}"); @@ -220,7 +229,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables( SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}"); @@ -239,7 +248,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}"); @@ -250,13 +259,13 @@ public void CanReadDefaultDocument() { const string text = ""; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe(null); config.Branches["develop"].Tag.ShouldBe("alpha"); config.Branches["release"].Tag.ShouldBe("beta"); - config.TagPrefix.ShouldBe(ConfigurationProvider.DefaultTagPrefix); + config.TagPrefix.ShouldBe(Config.DefaultTagPrefix); config.NextVersion.ShouldBe(null); } @@ -284,8 +293,11 @@ public void NoWarnOnGitVersionYmlFile() var log = new Log(logAppender); var defaultConfigFileLocator = new DefaultConfigFileLocator(fileSystem, log); + var gitPreparer = new GitPreparer(log, Options.Create(new Arguments { TargetPath = repoPath })); + + configProvider = new ConfigProvider(fileSystem, log, defaultConfigFileLocator, gitPreparer, configInitWizard); - ConfigurationProvider.Provide(repoPath, defaultConfigFileLocator); + configProvider.Provide(repoPath); stringLogger.Length.ShouldBe(0); } @@ -314,7 +326,7 @@ public void ShouldUseSpecifiedSourceBranchesForDevelop() source-branches: ['develop'] tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List { "develop" }); } @@ -329,7 +341,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List()); } @@ -345,7 +357,7 @@ public void ShouldUseSpecifiedSourceBranchesForFeature() source-branches: ['develop', 'release'] tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.Branches["feature"].SourceBranches.ShouldBe(new List { "develop", "release" }); } @@ -360,7 +372,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, configFileLocator); + var config = configProvider.Provide(repoPath); config.Branches["feature"].SourceBranches.ShouldBe( new List { "develop", "master", "release", "feature", "support", "hotfix" }); diff --git a/src/GitVersionCore.Tests/Configuration/IgnoreConfigTests.cs b/src/GitVersionCore.Tests/Configuration/IgnoreConfigTests.cs index c59b4c75f1..40bd5a3ff8 100644 --- a/src/GitVersionCore.Tests/Configuration/IgnoreConfigTests.cs +++ b/src/GitVersionCore.Tests/Configuration/IgnoreConfigTests.cs @@ -23,8 +23,8 @@ public void CanDeserialize() var config = ConfigSerialiser.Read(reader); config.Ignore.ShouldNotBeNull(); - config.Ignore.SHAs.ShouldNotBeEmpty(); - config.Ignore.SHAs.ShouldBe(new[] { "b6c0c9fda88830ebcd563e500a5a7da5a1658e98" }); + config.Ignore.ShAs.ShouldNotBeEmpty(); + config.Ignore.ShAs.ShouldBe(new[] { "b6c0c9fda88830ebcd563e500a5a7da5a1658e98" }); config.Ignore.Before.ShouldBe(DateTimeOffset.Parse("2015-10-23T12:23:15")); } @@ -42,8 +42,8 @@ public void ShouldSupportsOtherSequenceFormat() var config = ConfigSerialiser.Read(reader); config.Ignore.ShouldNotBeNull(); - config.Ignore.SHAs.ShouldNotBeEmpty(); - config.Ignore.SHAs.ShouldBe(new[] { "b6c0c9fda88830ebcd563e500a5a7da5a1658e98", "6c19c7c219ecf8dbc468042baefa73a1b213e8b1" }); + config.Ignore.ShAs.ShouldNotBeEmpty(); + config.Ignore.ShAs.ShouldBe(new[] { "b6c0c9fda88830ebcd563e500a5a7da5a1658e98", "6c19c7c219ecf8dbc468042baefa73a1b213e8b1" }); } [Test] @@ -57,7 +57,7 @@ public void WhenNotInConfigShouldHaveDefaults() var config = ConfigSerialiser.Read(reader); config.Ignore.ShouldNotBeNull(); - config.Ignore.SHAs.ShouldBeEmpty(); + config.Ignore.ShAs.ShouldBeEmpty(); config.Ignore.Before.ShouldBeNull(); } diff --git a/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs b/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs index ea83cd7083..5943441757 100644 --- a/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs @@ -4,8 +4,10 @@ using Shouldly; using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.Common; +using GitVersion; +using GitVersion.Configuration.Init.Wizard; using GitVersion.Logging; +using Microsoft.Extensions.Options; namespace GitVersionCore.Tests { @@ -69,7 +71,7 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, workingPath); - WarningException exception = Should.Throw(() => + var exception = Should.Throw(() => { WithDefaultConfigFileLocator(configFileLocator => { @@ -88,7 +90,15 @@ public void NoWarnOnGitVersionYmlFile() var output = WithDefaultConfigFileLocator(configFileLocator => { - ConfigurationProvider.Provide(repoPath, configFileLocator); + var log = new NullLog(); + var defaultConfigFileLocator = new DefaultConfigFileLocator(fileSystem, log); + var gitPreparer = new GitPreparer(log, Options.Create(new Arguments { TargetPath = repoPath })); + var stepFactory = new ConfigInitStepFactory(); + var configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + + var configurationProvider = new ConfigProvider(fileSystem, log, defaultConfigFileLocator, gitPreparer, configInitWizard); + + configurationProvider.Provide(repoPath); }); output.Length.ShouldBe(0); @@ -117,7 +127,7 @@ public void WarnOnObsoleteIsDevelopBranchConfigurationSetting() tag: beta is-develop: true"; - OldConfigurationException exception = Should.Throw(() => + var exception = Should.Throw(() => { LegacyConfigNotifier.Notify(new StringReader(text)); }); diff --git a/src/GitVersionCore.Tests/DynamicRepositoryTests.cs b/src/GitVersionCore.Tests/DynamicRepositoryTests.cs index db2bdd0ae3..9f6243ba62 100644 --- a/src/GitVersionCore.Tests/DynamicRepositoryTests.cs +++ b/src/GitVersionCore.Tests/DynamicRepositoryTests.cs @@ -1,7 +1,14 @@ using System.IO; using GitVersion; +using GitVersion.Cache; +using GitVersion.Configuration; +using GitVersion.Configuration.Init.Wizard; using NUnit.Framework; using GitVersion.Logging; +using GitVersion.OutputVariables; +using GitVersion.VersionCalculation; +using GitVersionCore.Tests.VersionCalculation; +using Microsoft.Extensions.Options; namespace GitVersionCore.Tests { @@ -61,14 +68,42 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran var root = Path.Combine(workDirectory, name); var dynamicDirectory = Path.Combine(root, "D"); // dynamic, keeping directory as short as possible var workingDirectory = Path.Combine(root, "W"); // working, keeping directory as short as possible + var arguments = new Arguments + { + TargetUrl = url, + DynamicRepositoryLocation = dynamicDirectory, + TargetBranch = targetBranch, + NoFetch = false, + TargetPath = workingDirectory, + CommitId = commitId + }; + var options = Options.Create(arguments); Directory.CreateDirectory(dynamicDirectory); Directory.CreateDirectory(workingDirectory); - var executeCore = new ExecuteCore(new TestFileSystem(), new TestEnvironment(), new NullLog()); + var testFileSystem = new TestFileSystem(); + var log = new NullLog(); + var configFileLocator = new DefaultConfigFileLocator(testFileSystem, log); + var gitVersionCache = new GitVersionCache(testFileSystem, log); + var buildServerResolver = new BuildServerResolver(null, log); + + var metadataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new TestBaseVersionStrategiesCalculator(log); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metadataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metadataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var gitVersionFinder = new GitVersionFinder(log, nextVersionCalculator); + + var gitPreparer = new GitPreparer(log, options); + var stepFactory = new ConfigInitStepFactory(); + var configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + + var configurationProvider = new ConfigProvider(testFileSystem, log, configFileLocator, gitPreparer, configInitWizard); + + var variableProvider = new VariableProvider(nextVersionCalculator); + var gitVersionCalculator = new GitVersionCalculator(testFileSystem, log, configFileLocator, configurationProvider, buildServerResolver, gitVersionCache, gitVersionFinder, gitPreparer, variableProvider, options); - var versionVariables = executeCore.ExecuteGitVersion(url, dynamicDirectory, null, targetBranch, - false, workingDirectory, commitId); + var versionVariables = gitVersionCalculator.CalculateVersionVariables(); Assert.AreEqual(expectedFullSemVer, versionVariables.FullSemVer); } diff --git a/src/GitVersionCore.Tests/ExecuteCoreTests.cs b/src/GitVersionCore.Tests/ExecuteCoreTests.cs deleted file mode 100644 index 0619f4a2a1..0000000000 --- a/src/GitVersionCore.Tests/ExecuteCoreTests.cs +++ /dev/null @@ -1,441 +0,0 @@ -using System; -using System.IO; -using System.Text; -using GitTools.Testing; -using GitVersion; -using NUnit.Framework; -using Shouldly; -using GitVersion.BuildServers; -using GitVersion.Configuration; -using GitVersion.OutputVariables; -using GitVersion.Cache; -using LibGit2Sharp; -using GitVersionCore.Tests.Helpers; -using GitVersion.Common; -using GitVersion.Logging; -using Environment = System.Environment; - -namespace GitVersionCore.Tests -{ - [TestFixture] - [Parallelizable(ParallelScope.None)] - public class ExecuteCoreTests : TestBase - { - private IFileSystem fileSystem; - private IEnvironment environment; - private ILog log; - - [SetUp] - public void SetUp() - { - fileSystem = new FileSystem(); - environment = new TestEnvironment(); - log = new NullLog(); - } - - [Test] - public void CacheKeySameAfterReNormalizing() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var targetBranch = "refs/head/master"; - var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, fixture.RepositoryPath); - var configFileLocator = new DefaultConfigFileLocator(fileSystem, log); - gitPreparer.Initialise(true, targetBranch); - var cacheKey1 = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, null, configFileLocator); - gitPreparer.Initialise(true, targetBranch); - var cacheKey2 = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, null, configFileLocator); - - cacheKey2.Value.ShouldBe(cacheKey1.Value); - }); - } - - [Test] - [Category("NoMono")] - [Description("LibGit2Sharp fails here when running under Mono")] - public void CacheKeyForWorktree() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString()); - try - { - // create a branch and a new worktree for it - var repo = new Repository(fixture.RepositoryPath); - repo.Worktrees.Add("worktree", worktreePath, false); - - var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, worktreePath); - var configFileLocator = new DefaultConfigFileLocator(fileSystem, log); - var cacheKey = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, null, configFileLocator); - cacheKey.Value.ShouldNotBeEmpty(); - } - finally - { - DirectoryHelper.DeleteDirectory(worktreePath); - } - }); - } - - [Test] - public void CacheFileExistsOnDisk() - { - const string versionCacheFileContent = @" -Major: 4 -Minor: 10 -Patch: 3 -PreReleaseTag: test.19 -PreReleaseTagWithDash: -test.19 -PreReleaseLabel: test -PreReleaseNumber: 19 -WeightedPreReleaseNumber: 19 -BuildMetaData: -BuildMetaDataPadded: -FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -MajorMinorPatch: 4.10.3 -SemVer: 4.10.3-test.19 -LegacySemVer: 4.10.3-test19 -LegacySemVerPadded: 4.10.3-test0019 -AssemblySemVer: 4.10.3.0 -AssemblySemFileVer: 4.10.3.0 -FullSemVer: 4.10.3-test.19 -InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -BranchName: feature/test -Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -ShortSha: dd2a29af -NuGetVersionV2: 4.10.3-test0019 -NuGetVersion: 4.10.3-test0019 -NuGetPreReleaseTagV2: test0019 -NuGetPreReleaseTag: test0019 -VersionSourceSha: 4.10.2 -CommitsSinceVersionSource: 19 -CommitsSinceVersionSourcePadded: 0019 -CommitDate: 2015-11-10 -"; - - var stringBuilder = new StringBuilder(); - void Action(string s) => stringBuilder.AppendLine(s); - - var logAppender = new TestLogAppender(Action); - log = new Log(logAppender); - - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); - vv = versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null); - vv.AssemblySemVer.ShouldBe("4.10.3.0"); - }); - - var logsMessages = stringBuilder.ToString(); - - logsMessages.ShouldContain("Deserializing version variables from cache file", () => logsMessages); - } - - - [Test] - public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDynamicallyCalculatedWithoutSavingInCache() - { - const string versionCacheFileContent = @" -Major: 4 -Minor: 10 -Patch: 3 -PreReleaseTag: test.19 -PreReleaseTagWithDash: -test.19 -PreReleaseLabel: test -PreReleaseNumber: 19 -BuildMetaData: -BuildMetaDataPadded: -FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -MajorMinorPatch: 4.10.3 -SemVer: 4.10.3-test.19 -LegacySemVer: 4.10.3-test19 -LegacySemVerPadded: 4.10.3-test0019 -AssemblySemVer: 4.10.3.0 -AssemblySemFileVer: 4.10.3.0 -FullSemVer: 4.10.3-test.19 -InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -BranchName: feature/test -Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -ShortSha: dd2a29af -NuGetVersionV2: 4.10.3-test0019 -NuGetVersion: 4.10.3-test0019 -NuGetPreReleaseTagV2: test0019 -NuGetPreReleaseTag: test0019 -CommitsSinceVersionSource: 19 -CommitsSinceVersionSourcePadded: 0019 -CommitDate: 2015-11-10 -"; - - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); - - var gitPreparer = new GitPreparer(log, null, null, null, false, fixture.RepositoryPath); - var cacheDirectory = GitVersionCache.GetCacheDirectory(gitPreparer); - - var cacheDirectoryTimestamp = fileSystem.GetLastDirectoryWrite(cacheDirectory); - - vv = versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null, new Config() { TagPrefix = "prefix" }); - - vv.AssemblySemVer.ShouldBe("0.1.0.0"); - - var cachedDirectoryTimestampAfter = fileSystem.GetLastDirectoryWrite(cacheDirectory); - cachedDirectoryTimestampAfter.ShouldBe(cacheDirectoryTimestamp, () => "Cache was updated when override config was set"); - }); - - // TODO info.ShouldContain("Override config from command line", () => info); - } - - [Test] - public void CacheFileIsMissing() - { - var stringBuilder = new StringBuilder(); - void Action(string s) => stringBuilder.AppendLine(s); - - var logAppender = new TestLogAppender(Action); - log = new Log(logAppender); - - var executeCore = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(executeCore); - var logsMessages = stringBuilder.ToString(); - logsMessages.ShouldContain("yml not found", () => logsMessages); - } - - - [Test] - public void ConfigChangeInvalidatesCache() - { - const string versionCacheFileContent = @" -Major: 4 -Minor: 10 -Patch: 3 -PreReleaseTag: test.19 -PreReleaseTagWithDash: -test.19 -PreReleaseLabel: test -PreReleaseNumber: 19 -WeightedPreReleaseNumber: 19 -BuildMetaData: -BuildMetaDataPadded: -FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -MajorMinorPatch: 4.10.3 -SemVer: 4.10.3-test.19 -LegacySemVer: 4.10.3-test19 -LegacySemVerPadded: 4.10.3-test0019 -AssemblySemVer: 4.10.3.0 -AssemblySemFileVer: 4.10.3.0 -FullSemVer: 4.10.3-test.19 -InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -BranchName: feature/test -Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -ShortSha: dd2a29af -NuGetVersionV2: 4.10.3-test0019 -NuGetVersion: 4.10.3-test0019 -NuGetPreReleaseTagV2: test0019 -NuGetPreReleaseTag: test0019 -VersionSourceSha: 4.10.2 -CommitsSinceVersionSource: 19 -CommitsSinceVersionSourcePadded: 0019 -CommitDate: 2015-11-10 -"; - - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); - vv = versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null); - vv.AssemblySemVer.ShouldBe("4.10.3.0"); - - var configPath = Path.Combine(fixture.RepositoryPath, "GitVersionConfig.yaml"); - fileSystem.WriteAllText(configPath, "next-version: 5.0"); - - vv = versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null); - vv.AssemblySemVer.ShouldBe("5.0.0.0"); - }); - } - - [Test] - public void NoCacheBypassesCache() - { - const string versionCacheFileContent = @" -Major: 4 -Minor: 10 -Patch: 3 -PreReleaseTag: test.19 -PreReleaseTagWithDash: -test.19 -PreReleaseLabel: test -PreReleaseNumber: 19 -WeightedPreReleaseNumber: 19 -BuildMetaData: -BuildMetaDataPadded: -FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -MajorMinorPatch: 4.10.3 -SemVer: 4.10.3-test.19 -LegacySemVer: 4.10.3-test19 -LegacySemVerPadded: 4.10.3-test0019 -AssemblySemVer: 4.10.3.0 -AssemblySemFileVer: 4.10.3.0 -FullSemVer: 4.10.3-test.19 -InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -BranchName: feature/test -Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f -ShortSha: dd2a29af -NuGetVersionV2: 4.10.3-test0019 -NuGetVersion: 4.10.3-test0019 -NuGetPreReleaseTagV2: test0019 -NuGetPreReleaseTag: test0019 -VersionSourceSha: 4.10.2 -CommitsSinceVersionSource: 19 -CommitsSinceVersionSourcePadded: 0019 -CommitDate: 2015-11-10 -"; - - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); - vv = versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null); - vv.AssemblySemVer.ShouldBe("4.10.3.0"); - - vv = versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null, noCache: true); - vv.AssemblySemVer.ShouldBe("0.1.0.0"); - }); - } - - - [Test] - public void WorkingDirectoryWithoutGit() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var exception = Assert.Throws(() => versionAndBranchFinder.ExecuteGitVersion(null, null, null, null, false, Environment.SystemDirectory, null)); - exception.Message.ShouldContain("Can't find the .git directory in"); - }); - } - - [Test] - [Category("NoMono")] - [Description("LibGit2Sharp fails when running under Mono")] - public void GetProjectRootDirectory_WorkingDirectoryWithWorktree() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString()); - try - { - // create a branch and a new worktree for it - var repo = new Repository(fixture.RepositoryPath); - repo.Worktrees.Add("worktree", worktreePath, false); - - var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, worktreePath); - gitPreparer.GetProjectRootDirectory().TrimEnd('/', '\\').ShouldBe(worktreePath); - } - finally - { - DirectoryHelper.DeleteDirectory(worktreePath); - } - }); - } - - [Test] - public void GetProjectRootDirectory_NoWorktree() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, fixture.RepositoryPath); - var expectedPath = fixture.RepositoryPath.TrimEnd('/', '\\'); - gitPreparer.GetProjectRootDirectory().TrimEnd('/', '\\').ShouldBe(expectedPath); - }); - } - - [Test] - public void DynamicRepositoriesShouldNotErrorWithFailedToFindGitDirectory() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - versionAndBranchFinder.ExecuteGitVersion("https://github.com/GitTools/GitVersion.git", null, new Authentication(), "refs/head/master", false, fixture.RepositoryPath, null); - }); - } - - [Test] - public void GetDotGitDirectory_NoWorktree() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, fixture.RepositoryPath); - var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); - gitPreparer.GetDotGitDirectory().ShouldBe(expectedPath); - }); - } - - [Test] - [Category("NoMono")] - [Description("LibGit2Sharp fails when running under Mono")] - public void GetDotGitDirectory_Worktree() - { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); - - RepositoryScope(versionAndBranchFinder, (fixture, vv) => - { - var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString()); - try - { - - // create a branch and a new worktree for it - var repo = new Repository(fixture.RepositoryPath); - repo.Worktrees.Add("worktree", worktreePath, false); - - var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, worktreePath); - var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); - gitPreparer.GetDotGitDirectory().ShouldBe(expectedPath); - } - finally - { - DirectoryHelper.DeleteDirectory(worktreePath); - } - }); - } - - private void RepositoryScope(ExecuteCore executeCore, Action fixtureAction = null) - { - // Make sure GitVersion doesn't trigger build server mode when we are running the tests - environment.SetEnvironmentVariable(AppVeyor.EnvironmentVariableName, null); - environment.SetEnvironmentVariable(TravisCI.EnvironmentVariableName, null); - environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, null); - - using var fixture = new EmptyRepositoryFixture(); - fixture.Repository.MakeACommit(); - var vv = executeCore.ExecuteGitVersion(null, null, null, null, false, fixture.RepositoryPath, null); - - vv.AssemblySemVer.ShouldBe("0.1.0.0"); - vv.FileName.ShouldNotBeNullOrEmpty(); - - fixtureAction?.Invoke(fixture, vv); - } - } -} diff --git a/src/GitVersionCore.Tests/Extensions/ExtensionMethodsTests.cs b/src/GitVersionCore.Tests/Extensions/ExtensionMethodsTests.cs index a00b9ab372..bce69d7ac9 100644 --- a/src/GitVersionCore.Tests/Extensions/ExtensionMethodsTests.cs +++ b/src/GitVersionCore.Tests/Extensions/ExtensionMethodsTests.cs @@ -1,5 +1,5 @@ -using GitVersion.Helpers; using NUnit.Framework; +using GitVersion.Extensions; namespace GitVersionCore.Tests.Extensions { diff --git a/src/GitVersionCore.Tests/GitRepoMetadataProviderTests.cs b/src/GitVersionCore.Tests/GitRepoMetadataProviderTests.cs index 65b7c3fff7..067cb75804 100644 --- a/src/GitVersionCore.Tests/GitRepoMetadataProviderTests.cs +++ b/src/GitVersionCore.Tests/GitRepoMetadataProviderTests.cs @@ -5,8 +5,8 @@ using GitVersionCore.Tests.IntegrationTests; using NUnit.Framework; using Shouldly; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersionCore.Tests { diff --git a/src/GitVersionCore.Tests/GitToolsTestingExtensions.cs b/src/GitVersionCore.Tests/GitToolsTestingExtensions.cs index 47c3b48292..99f023f84e 100644 --- a/src/GitVersionCore.Tests/GitToolsTestingExtensions.cs +++ b/src/GitVersionCore.Tests/GitToolsTestingExtensions.cs @@ -5,8 +5,11 @@ using GitVersion.OutputVariables; using LibGit2Sharp; using Shouldly; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.VersionCalculation; +using GitVersionCore.Tests.VersionCalculation; +using Microsoft.Extensions.Options; +using GitVersion.Extensions; namespace GitVersionCore.Tests { @@ -14,7 +17,7 @@ public static class GitToolsTestingExtensions { public static Config ApplyDefaults(this Config config) { - ConfigurationProvider.ApplyDefaultsTo(config); + config.Reset(); return config; } @@ -23,11 +26,15 @@ public static VersionVariables GetVersion(this RepositoryFixtureBase fixture, Co if (configuration == null) { configuration = new Config(); - ConfigurationProvider.ApplyDefaultsTo(configuration); + configuration.Reset(); } var log = new NullLog(); - var variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new TestBaseVersionStrategiesCalculator(log); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); var gitVersionContext = new GitVersionContext(repository ?? fixture.Repository, log, targetBranch, configuration, isForTrackedBranchOnly, commitId); var executeGitVersion = ExecuteGitVersion(gitVersionContext); var variables = variableProvider.GetVariablesFor(executeGitVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged); @@ -50,7 +57,7 @@ public static void AssertFullSemver(this RepositoryFixtureBase fixture, string f public static void AssertFullSemver(this RepositoryFixtureBase fixture, Config configuration, string fullSemver, IRepository repository = null, string commitId = null, bool isForTrackedBranchOnly = true, string targetBranch = null) { - ConfigurationProvider.ApplyDefaultsTo(configuration); + configuration.Reset(); Console.WriteLine("---------"); try @@ -71,16 +78,28 @@ public static void AssertFullSemver(this RepositoryFixtureBase fixture, Config c private static SemanticVersion ExecuteGitVersion(GitVersionContext context) { - var vf = new GitVersionFinder(); - return vf.FindVersion(new NullLog(), context); + var log = new NullLog(); + var metadataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new TestBaseVersionStrategiesCalculator(log); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metadataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metadataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var vf = new GitVersionFinder(log, nextVersionCalculator); + return vf.FindVersion(context); } /// /// Simulates running on build server /// - public static void InitialiseRepo(this RemoteRepositoryFixture fixture) + public static void InitializeRepo(this RemoteRepositoryFixture fixture) { - new GitPreparer(new NullLog(), null, null, new Authentication(), false, fixture.LocalRepositoryFixture.RepositoryPath).Initialise(true, null); + var log = new NullLog(); + + var arguments = new Arguments + { + Authentication = new Authentication(), + TargetPath = fixture.LocalRepositoryFixture.RepositoryPath + }; + new GitPreparer(log, Options.Create(arguments)).Prepare(true, null); } } } diff --git a/src/GitVersionCore.Tests/GitVersionContextBuilder.cs b/src/GitVersionCore.Tests/GitVersionContextBuilder.cs index a3ee9b2472..7471c80a9c 100644 --- a/src/GitVersionCore.Tests/GitVersionContextBuilder.cs +++ b/src/GitVersionCore.Tests/GitVersionContextBuilder.cs @@ -63,7 +63,7 @@ public GitVersionContextBuilder AddBranch(string branchName) public GitVersionContext Build() { var configuration = config ?? new Config(); - ConfigurationProvider.ApplyDefaultsTo(configuration); + configuration.Reset(); var repo = repository ?? CreateRepository(); return new GitVersionContext(repo, new NullLog(), repo.Head, configuration); } diff --git a/src/GitVersionCore.Tests/GitVersionContextTests.cs b/src/GitVersionCore.Tests/GitVersionContextTests.cs index 221c22d5d7..edfe417344 100644 --- a/src/GitVersionCore.Tests/GitVersionContextTests.cs +++ b/src/GitVersionCore.Tests/GitVersionContextTests.cs @@ -21,7 +21,7 @@ public void CanInheritVersioningMode(VersioningMode mode) { VersioningMode = mode }; - ConfigurationProvider.ApplyDefaultsTo(config); + config.Reset(); var mockBranch = new MockBranch("master") { new MockCommit { CommitterEx = Generate.SignatureNow() } }; var mockRepository = new MockRepository @@ -50,7 +50,7 @@ public void CanInheritIncrement(IncrementStrategy increment, IncrementStrategy? { Increment = increment }; - ConfigurationProvider.ApplyDefaultsTo(config); + config.Reset(); using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); @@ -78,7 +78,7 @@ public void UsesBranchSpecificConfigOverTopLevelDefaults() } } }; - ConfigurationProvider.ApplyDefaultsTo(config); + config.Reset(); var develop = new MockBranch("develop") { new MockCommit { CommitterEx = Generate.SignatureNow() } }; var mockRepository = new MockRepository { diff --git a/src/GitVersionCore.Tests/GitVersionCore.Tests.csproj b/src/GitVersionCore.Tests/GitVersionCore.Tests.csproj index aa1f2a0fa6..75f3f8cf0a 100644 --- a/src/GitVersionCore.Tests/GitVersionCore.Tests.csproj +++ b/src/GitVersionCore.Tests/GitVersionCore.Tests.csproj @@ -14,6 +14,7 @@ + diff --git a/src/GitVersionCore.Tests/GitVersionExecutorTests.cs b/src/GitVersionCore.Tests/GitVersionExecutorTests.cs new file mode 100644 index 0000000000..8ecd515f20 --- /dev/null +++ b/src/GitVersionCore.Tests/GitVersionExecutorTests.cs @@ -0,0 +1,562 @@ +using System; +using System.IO; +using System.Text; +using GitTools.Testing; +using GitVersion; +using NUnit.Framework; +using Shouldly; +using GitVersion.BuildServers; +using GitVersion.Configuration; +using GitVersion.OutputVariables; +using GitVersion.Cache; +using GitVersion.Configuration.Init.Wizard; +using LibGit2Sharp; +using GitVersionCore.Tests.Helpers; +using GitVersion.Logging; +using GitVersion.VersionCalculation; +using GitVersionCore.Tests.VersionCalculation; +using Microsoft.Extensions.Options; +using Environment = System.Environment; + +namespace GitVersionCore.Tests +{ + [TestFixture] + [Parallelizable(ParallelScope.None)] + public class GitVersionExecutorTests : TestBase + { + private IFileSystem fileSystem; + private IEnvironment environment; + private ILog log; + private IConfigFileLocator configFileLocator; + private IBuildServerResolver buildServerResolver; + private IGitVersionCache gitVersionCache; + private IMetaDataCalculator metaDataCalculator; + private IGitVersionFinder gitVersionFinder; + + [SetUp] + public void SetUp() + { + fileSystem = new FileSystem(); + environment = new TestEnvironment(); + log = new NullLog(); + configFileLocator = new DefaultConfigFileLocator(fileSystem, log); + buildServerResolver = new BuildServerResolver(null, log); + gitVersionCache = new GitVersionCache(fileSystem, log); + metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new TestBaseVersionStrategiesCalculator(log); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + + gitVersionFinder = new GitVersionFinder(log, nextVersionCalculator); + } + + [Test] + public void CacheKeySameAfterReNormalizing() + { + RepositoryScope((fixture, vv) => + { + var targetUrl = "https://github.com/GitTools/GitVersion.git"; + var targetBranch = "refs/head/master"; + + var arguments = new Arguments + { + TargetUrl = targetUrl, + TargetPath = fixture.RepositoryPath + }; + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + configFileLocator = new DefaultConfigFileLocator(fileSystem, log); + + gitPreparer.Prepare(true, targetBranch); + var cacheKey1 = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, configFileLocator, null); + gitPreparer.Prepare(true, targetBranch); + var cacheKey2 = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, configFileLocator, null); + + cacheKey2.Value.ShouldBe(cacheKey1.Value); + }); + } + + [Test] + [Category("NoMono")] + [Description("LibGit2Sharp fails here when running under Mono")] + public void CacheKeyForWorktree() + { + RepositoryScope((fixture, vv) => + { + var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString()); + try + { + // create a branch and a new worktree for it + var repo = new Repository(fixture.RepositoryPath); + repo.Worktrees.Add("worktree", worktreePath, false); + + var targetUrl = "https://github.com/GitTools/GitVersion.git"; + + var arguments = new Arguments + { + TargetUrl = targetUrl, + TargetPath = worktreePath + }; + + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + configFileLocator = new DefaultConfigFileLocator(fileSystem, log); + var cacheKey = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, configFileLocator, null); + cacheKey.Value.ShouldNotBeEmpty(); + } + finally + { + DirectoryHelper.DeleteDirectory(worktreePath); + } + }); + } + + [Test] + public void CacheFileExistsOnDisk() + { + const string versionCacheFileContent = @" + Major: 4 + Minor: 10 + Patch: 3 + PreReleaseTag: test.19 + PreReleaseTagWithDash: -test.19 + PreReleaseLabel: test + PreReleaseNumber: 19 + WeightedPreReleaseNumber: 19 + BuildMetaData: + BuildMetaDataPadded: + FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + MajorMinorPatch: 4.10.3 + SemVer: 4.10.3-test.19 + LegacySemVer: 4.10.3-test19 + LegacySemVerPadded: 4.10.3-test0019 + AssemblySemVer: 4.10.3.0 + AssemblySemFileVer: 4.10.3.0 + FullSemVer: 4.10.3-test.19 + InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + BranchName: feature/test + Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + ShortSha: dd2a29af + NuGetVersionV2: 4.10.3-test0019 + NuGetVersion: 4.10.3-test0019 + NuGetPreReleaseTagV2: test0019 + NuGetPreReleaseTag: test0019 + VersionSourceSha: 4.10.2 + CommitsSinceVersionSource: 19 + CommitsSinceVersionSourcePadded: 0019 + CommitDate: 2015-11-10 + "; + + var stringBuilder = new StringBuilder(); + void Action(string s) => stringBuilder.AppendLine(s); + + var logAppender = new TestLogAppender(Action); + log = new Log(logAppender); + + gitVersionCache = new GitVersionCache(fileSystem, log); + + RepositoryScope(log, (fixture, vv) => + { + fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); + + var arguments = new Arguments { TargetPath = fixture.RepositoryPath }; + var gitVersionCalculator = GetGitVersionCalculator(arguments); + + vv = gitVersionCalculator.CalculateVersionVariables(); + vv.AssemblySemVer.ShouldBe("4.10.3.0"); + }); + + var logsMessages = stringBuilder.ToString(); + + logsMessages.ShouldContain("Deserializing version variables from cache file", () => logsMessages); + } + + [Test] + public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDynamicallyCalculatedWithoutSavingInCache() + { + const string versionCacheFileContent = @" + Major: 4 + Minor: 10 + Patch: 3 + PreReleaseTag: test.19 + PreReleaseTagWithDash: -test.19 + PreReleaseLabel: test + PreReleaseNumber: 19 + BuildMetaData: + BuildMetaDataPadded: + FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + MajorMinorPatch: 4.10.3 + SemVer: 4.10.3-test.19 + LegacySemVer: 4.10.3-test19 + LegacySemVerPadded: 4.10.3-test0019 + AssemblySemVer: 4.10.3.0 + AssemblySemFileVer: 4.10.3.0 + FullSemVer: 4.10.3-test.19 + InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + BranchName: feature/test + Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + ShortSha: dd2a29af + NuGetVersionV2: 4.10.3-test0019 + NuGetVersion: 4.10.3-test0019 + NuGetPreReleaseTagV2: test0019 + NuGetPreReleaseTag: test0019 + CommitsSinceVersionSource: 19 + CommitsSinceVersionSourcePadded: 0019 + CommitDate: 2015-11-10 + "; + + RepositoryScope((fixture, vv) => + { + fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); + + var arguments = new Arguments + { + TargetPath = fixture.RepositoryPath + }; + + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + + gitVersionCache = new GitVersionCache(fileSystem, log); + var cacheDirectory = gitVersionCache.GetCacheDirectory(gitPreparer); + + var cacheDirectoryTimestamp = fileSystem.GetLastDirectoryWrite(cacheDirectory); + + arguments = new Arguments { TargetPath = fixture.RepositoryPath, OverrideConfig = new Config { TagPrefix = "prefix" } }; + + var gitVersionCalculator = GetGitVersionCalculator(arguments); + vv = gitVersionCalculator.CalculateVersionVariables(); + + vv.AssemblySemVer.ShouldBe("0.1.0.0"); + + var cachedDirectoryTimestampAfter = fileSystem.GetLastDirectoryWrite(cacheDirectory); + cachedDirectoryTimestampAfter.ShouldBe(cacheDirectoryTimestamp, () => "Cache was updated when override config was set"); + }); + } + + [Test] + public void CacheFileIsMissing() + { + var stringBuilder = new StringBuilder(); + void Action(string s) => stringBuilder.AppendLine(s); + + var logAppender = new TestLogAppender(Action); + log = new Log(logAppender); + gitVersionCache = new GitVersionCache(fileSystem, log); + + RepositoryScope(); + var logsMessages = stringBuilder.ToString(); + logsMessages.ShouldContain("yml not found", () => logsMessages); + } + + + [Test] + public void ConfigChangeInvalidatesCache() + { + const string versionCacheFileContent = @" + Major: 4 + Minor: 10 + Patch: 3 + PreReleaseTag: test.19 + PreReleaseTagWithDash: -test.19 + PreReleaseLabel: test + PreReleaseNumber: 19 + WeightedPreReleaseNumber: 19 + BuildMetaData: + BuildMetaDataPadded: + FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + MajorMinorPatch: 4.10.3 + SemVer: 4.10.3-test.19 + LegacySemVer: 4.10.3-test19 + LegacySemVerPadded: 4.10.3-test0019 + AssemblySemVer: 4.10.3.0 + AssemblySemFileVer: 4.10.3.0 + FullSemVer: 4.10.3-test.19 + InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + BranchName: feature/test + Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + ShortSha: dd2a29af + NuGetVersionV2: 4.10.3-test0019 + NuGetVersion: 4.10.3-test0019 + NuGetPreReleaseTagV2: test0019 + NuGetPreReleaseTag: test0019 + VersionSourceSha: 4.10.2 + CommitsSinceVersionSource: 19 + CommitsSinceVersionSourcePadded: 0019 + CommitDate: 2015-11-10 + "; + + RepositoryScope((fixture, vv) => + { + fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); + var arguments = new Arguments { TargetPath = fixture.RepositoryPath }; + + var gitVersionCalculator = GetGitVersionCalculator(arguments); + + vv = gitVersionCalculator.CalculateVersionVariables(); + vv.AssemblySemVer.ShouldBe("4.10.3.0"); + + var configPath = Path.Combine(fixture.RepositoryPath, "GitVersionConfig.yaml"); + fileSystem.WriteAllText(configPath, "next-version: 5.0"); + + vv = gitVersionCalculator.CalculateVersionVariables(); + vv.AssemblySemVer.ShouldBe("5.0.0.0"); + }); + } + + [Test] + public void NoCacheBypassesCache() + { + const string versionCacheFileContent = @" + Major: 4 + Minor: 10 + Patch: 3 + PreReleaseTag: test.19 + PreReleaseTagWithDash: -test.19 + PreReleaseLabel: test + PreReleaseNumber: 19 + WeightedPreReleaseNumber: 19 + BuildMetaData: + BuildMetaDataPadded: + FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + MajorMinorPatch: 4.10.3 + SemVer: 4.10.3-test.19 + LegacySemVer: 4.10.3-test19 + LegacySemVerPadded: 4.10.3-test0019 + AssemblySemVer: 4.10.3.0 + AssemblySemFileVer: 4.10.3.0 + FullSemVer: 4.10.3-test.19 + InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + BranchName: feature/test + Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f + ShortSha: dd2a29af + NuGetVersionV2: 4.10.3-test0019 + NuGetVersion: 4.10.3-test0019 + NuGetPreReleaseTagV2: test0019 + NuGetPreReleaseTag: test0019 + VersionSourceSha: 4.10.2 + CommitsSinceVersionSource: 19 + CommitsSinceVersionSourcePadded: 0019 + CommitDate: 2015-11-10 + "; + + RepositoryScope((fixture, vv) => + { + var arguments = new Arguments { TargetPath = fixture.RepositoryPath }; + + var gitVersionCalculator = GetGitVersionCalculator(arguments); + + fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); + vv = gitVersionCalculator.CalculateVersionVariables(); + vv.AssemblySemVer.ShouldBe("4.10.3.0"); + + arguments.NoCache = true; + vv = gitVersionCalculator.CalculateVersionVariables(); + vv.AssemblySemVer.ShouldBe("0.1.0.0"); + }); + } + + + [Test] + public void WorkingDirectoryWithoutGit() + { + RepositoryScope((fixture, vv) => + { + var arguments = new Arguments { TargetPath = Environment.SystemDirectory }; + + var gitVersionCalculator = GetGitVersionCalculator(arguments); + + var exception = Assert.Throws(() => gitVersionCalculator.CalculateVersionVariables()); + exception.Message.ShouldContain("Can't find the .git directory in"); + }); + } + + [Test] + [Category("NoMono")] + [Description("LibGit2Sharp fails when running under Mono")] + public void GetProjectRootDirectoryWorkingDirectoryWithWorktree() + { + RepositoryScope((fixture, vv) => + { + var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString()); + try + { + // create a branch and a new worktree for it + var repo = new Repository(fixture.RepositoryPath); + repo.Worktrees.Add("worktree", worktreePath, false); + + var targetUrl = "https://github.com/GitTools/GitVersion.git"; + + var arguments = new Arguments + { + TargetUrl = targetUrl, + TargetPath = worktreePath + }; + + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + + gitPreparer.GetProjectRootDirectory().TrimEnd('/', '\\').ShouldBe(worktreePath); + } + finally + { + DirectoryHelper.DeleteDirectory(worktreePath); + } + }); + } + + [Test] + public void GetProjectRootDirectoryNoWorktree() + { + RepositoryScope((fixture, vv) => + { + var targetUrl = "https://github.com/GitTools/GitVersion.git"; + + var arguments = new Arguments + { + TargetUrl = targetUrl, + TargetPath = fixture.RepositoryPath + }; + + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + var expectedPath = fixture.RepositoryPath.TrimEnd('/', '\\'); + gitPreparer.GetProjectRootDirectory().TrimEnd('/', '\\').ShouldBe(expectedPath); + }); + } + + [Test] + public void DynamicRepositoriesShouldNotErrorWithFailedToFindGitDirectory() + { + RepositoryScope((fixture, vv) => + { + var arguments = new Arguments + { + TargetPath = fixture.RepositoryPath, + TargetUrl = "https://github.com/GitTools/GitVersion.git", + TargetBranch = "refs/head/master" + }; + + var gitVersionCalculator = GetGitVersionCalculator(arguments); + + gitVersionCalculator.CalculateVersionVariables(); + }); + } + + [Test] + public void GetDotGitDirectoryNoWorktree() + { + RepositoryScope((fixture, vv) => + { + var targetUrl = "https://github.com/GitTools/GitVersion.git"; + + var arguments = new Arguments + { + TargetUrl = targetUrl, + TargetPath = fixture.RepositoryPath + }; + + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); + gitPreparer.GetDotGitDirectory().ShouldBe(expectedPath); + }); + } + + [Test] + [Category("NoMono")] + [Description("LibGit2Sharp fails when running under Mono")] + public void GetDotGitDirectoryWorktree() + { + RepositoryScope((fixture, vv) => + { + var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString()); + try + { + // create a branch and a new worktree for it + var repo = new Repository(fixture.RepositoryPath); + repo.Worktrees.Add("worktree", worktreePath, false); + + var targetUrl = "https://github.com/GitTools/GitVersion.git"; + + var arguments = new Arguments + { + TargetUrl = targetUrl, + TargetPath = worktreePath + }; + + var gitPreparer = new GitPreparer(log, Options.Create(arguments)); + var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); + gitPreparer.GetDotGitDirectory().ShouldBe(expectedPath); + } + finally + { + DirectoryHelper.DeleteDirectory(worktreePath); + } + }); + } + + private void RepositoryScope(Action fixtureAction = null) + { + // Make sure GitVersion doesn't trigger build server mode when we are running the tests + environment.SetEnvironmentVariable(AppVeyor.EnvironmentVariableName, null); + environment.SetEnvironmentVariable(TravisCi.EnvironmentVariableName, null); + environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, null); + + using var fixture = new EmptyRepositoryFixture(); + + var arguments = new Arguments { TargetPath = fixture.RepositoryPath }; + + var gitVersionCalculator = GetGitVersionCalculator(arguments); + + fixture.Repository.MakeACommit(); + var vv = gitVersionCalculator.CalculateVersionVariables(); + + vv.AssemblySemVer.ShouldBe("0.1.0.0"); + vv.FileName.ShouldNotBeNullOrEmpty(); + + fixtureAction?.Invoke(fixture, vv); + } + + private void RepositoryScope(ILog log, Action fixtureAction = null) + { + // Make sure GitVersion doesn't trigger build server mode when we are running the tests + environment.SetEnvironmentVariable(AppVeyor.EnvironmentVariableName, null); + environment.SetEnvironmentVariable(TravisCi.EnvironmentVariableName, null); + environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, null); + + using var fixture = new EmptyRepositoryFixture(); + + var arguments = new Arguments { TargetPath = fixture.RepositoryPath }; + var options = Options.Create(arguments); + + var gitPreparer = new GitPreparer(log, options); + var stepFactory = new ConfigInitStepFactory(); + var configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + var configurationProvider = new ConfigProvider(fileSystem, log, configFileLocator, gitPreparer, configInitWizard); + var baseVersionCalculator = new BaseVersionCalculator(this.log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(this.log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(this.log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); + var gitVersionCalculator = new GitVersionCalculator(fileSystem, log, configFileLocator, configurationProvider, buildServerResolver, gitVersionCache, gitVersionFinder, gitPreparer, variableProvider, options); + + fixture.Repository.MakeACommit(); + var vv = gitVersionCalculator.CalculateVersionVariables(); + + vv.AssemblySemVer.ShouldBe("0.1.0.0"); + vv.FileName.ShouldNotBeNullOrEmpty(); + + fixtureAction?.Invoke(fixture, vv); + } + + private GitVersionCalculator GetGitVersionCalculator(Arguments arguments) + { + var options = Options.Create(arguments); + + var gitPreparer = new GitPreparer(log, options); + var stepFactory = new ConfigInitStepFactory(); + var configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + var configurationProvider = new ConfigProvider(fileSystem, log, configFileLocator, gitPreparer, configInitWizard); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); + var gitVersionCalculator = new GitVersionCalculator(fileSystem, log, configFileLocator, configurationProvider, buildServerResolver, gitVersionCache, gitVersionFinder, gitPreparer, variableProvider, options); + return gitVersionCalculator; + } + } +} diff --git a/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs b/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs index 16122b630f..331a8d304f 100644 --- a/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs +++ b/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs @@ -1,11 +1,12 @@ using System; using System.IO; -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.OutputVariables; using GitVersion.Extensions.GitVersionInformationResources; using GitVersion.Logging; +using GitVersion; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests { @@ -41,7 +42,12 @@ public void ShouldCreateFile(string fileExtension) "feature1", "commitSha", "commitShortSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; - var variableProvider = new VariableProvider(new NullLog()); + var log = new NullLog(); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); var variables = variableProvider.GetVariablesFor(semanticVersion, new TestEffectiveConfiguration(), false); var generator = new GitVersionInformationGenerator(fileName, directory, variables, fileSystem); diff --git a/src/GitVersionCore.Tests/Helpers/DirectoryHelper.cs b/src/GitVersionCore.Tests/Helpers/DirectoryHelper.cs index f2ac3fab0a..2a71eb2426 100644 --- a/src/GitVersionCore.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersionCore.Tests/Helpers/DirectoryHelper.cs @@ -7,7 +7,7 @@ namespace GitVersionCore.Tests.Helpers { public static class DirectoryHelper { - private static Dictionary toRename = new Dictionary + private static readonly Dictionary ToRename = new Dictionary { {"gitted", ".git"}, {"gitmodules", ".gitmodules"}, @@ -29,7 +29,7 @@ public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo targ private static string Rename(string name) { - return toRename.ContainsKey(name) ? toRename[name] : name; + return ToRename.ContainsKey(name) ? ToRename[name] : name; } public static void DeleteSubDirectories(string parentPath) diff --git a/src/GitVersionCore.Tests/Init/InitScenarios.cs b/src/GitVersionCore.Tests/Init/InitScenarios.cs index 572b499d61..bf90a6d56b 100644 --- a/src/GitVersionCore.Tests/Init/InitScenarios.cs +++ b/src/GitVersionCore.Tests/Init/InitScenarios.cs @@ -1,7 +1,13 @@ using System.IO; using System.Runtime.InteropServices; +using GitVersion; using GitVersion.Configuration; +using GitVersion.Configuration.Init; +using GitVersion.Configuration.Init.Wizard; +using GitVersion.Extensions; using GitVersion.Logging; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using NUnit.Framework; using Shouldly; @@ -21,12 +27,28 @@ public void Setup() [Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void CanSetNextVersion() { - var log = new NullLog(); - var fileSystem = new TestFileSystem(); - var testConsole = new TestConsole("3", "2.0.0", "0"); + ILog log = new NullLog(); + IFileSystem fileSystem = new TestFileSystem(); + IConsole testConsole = new TestConsole("3", "2.0.0", "0"); + + var serviceCollections = new ServiceCollection(); + serviceCollections.AddModule(new GitVersionInitModule()); + + serviceCollections.AddSingleton(log); + serviceCollections.AddSingleton(fileSystem); + serviceCollections.AddSingleton(testConsole); + + var serviceProvider = serviceCollections.BuildServiceProvider(); + + var stepFactory = new ConfigInitStepFactory(serviceProvider); + var configInitWizard = new ConfigInitWizard(testConsole, stepFactory); var configFileLocator = new DefaultConfigFileLocator(fileSystem, log); var workingDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c:\\proj" : "/proj"; - ConfigurationProvider.Init(workingDirectory, fileSystem, testConsole, log, configFileLocator); + + var gitPreparer = new GitPreparer(log, Options.Create(new Arguments { TargetPath = workingDirectory })); + var configurationProvider = new ConfigProvider(fileSystem, log, configFileLocator, gitPreparer, configInitWizard); + + configurationProvider.Init(workingDirectory); fileSystem.ReadAllText(Path.Combine(workingDirectory, "GitVersion.yml")).ShouldMatchApproved(); } diff --git a/src/GitVersionCore.Tests/Init/TestConsole.cs b/src/GitVersionCore.Tests/Init/TestConsole.cs index c0ace2a9be..15b4df240e 100644 --- a/src/GitVersionCore.Tests/Init/TestConsole.cs +++ b/src/GitVersionCore.Tests/Init/TestConsole.cs @@ -8,7 +8,7 @@ namespace GitVersionCore.Tests.Init public class TestConsole : IConsole { private readonly Queue responses; - private ILog log; + private readonly ILog log; public TestConsole(params string[] responses) { diff --git a/src/GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs index 53289b693d..8388a0e3b9 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/DevelopScenarios.cs @@ -11,7 +11,7 @@ namespace GitVersionCore.Tests.IntegrationTests public class DevelopScenarios : TestBase { [Test] - public void WhenDevelopHasMultipleCommits_SpecifyExistingCommitId() + public void WhenDevelopHasMultipleCommitsSpecifyExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); @@ -27,7 +27,7 @@ public void WhenDevelopHasMultipleCommits_SpecifyExistingCommitId() } [Test] - public void WhenDevelopHasMultipleCommits_SpecifyNonExistingCommitId() + public void WhenDevelopHasMultipleCommitsSpecifyNonExistingCommitId() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); @@ -85,7 +85,7 @@ public void WhenDeveloperBranchExistsDontTreatAsDevelop() } [Test] - public void WhenDevelopBranchedFromMaster_MinorIsIncreased() + public void WhenDevelopBranchedFromMasterMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); @@ -95,7 +95,7 @@ public void WhenDevelopBranchedFromMaster_MinorIsIncreased() } [Test] - public void MergingReleaseBranchBackIntoDevelopWithMergingToMaster_DoesBumpDevelopVersion() + public void MergingReleaseBranchBackIntoDevelopWithMergingToMasterDoesBumpDevelopVersion() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); @@ -133,7 +133,7 @@ public void CanHandleContinuousDelivery() } [Test] - public void WhenDevelopBranchedFromMasterDetachedHead_MinorIsIncreased() + public void WhenDevelopBranchedFromMasterDetachedHeadMinorIsIncreased() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.0"); diff --git a/src/GitVersionCore.Tests/IntegrationTests/DocumentationSamples.cs b/src/GitVersionCore.Tests/IntegrationTests/DocumentationSamples.cs index 2739f4686c..9f7bf67c7c 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/DocumentationSamples.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/DocumentationSamples.cs @@ -2,7 +2,7 @@ using GitTools.Testing; using NUnit.Framework; using Shouldly; -using GitVersion.Helpers; +using GitVersion.Extensions; namespace GitVersionCore.Tests.IntegrationTests { diff --git a/src/GitVersionCore.Tests/IntegrationTests/FileSystemTests.cs b/src/GitVersionCore.Tests/IntegrationTests/FileSystemTests.cs index 58e013ffe8..b0e74b298e 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/FileSystemTests.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/FileSystemTests.cs @@ -2,7 +2,7 @@ using System.Text; using NUnit.Framework; using Shouldly; -using GitVersion.Common; +using GitVersion; namespace GitVersionCore.Tests.IntegrationTests { @@ -28,7 +28,7 @@ public void Cleanup() [TestCase("utf-16")] [TestCase("utf-16BE")] [TestCase("utf-8")] - public void WhenFileExistsWithEncodingPreamble_EncodingIsPreservedAfterWriteAll(string encodingName) + public void WhenFileExistsWithEncodingPreambleEncodingIsPreservedAfterWriteAll(string encodingName) { var encoding = Encoding.GetEncoding(encodingName); @@ -46,7 +46,7 @@ public void WhenFileExistsWithEncodingPreamble_EncodingIsPreservedAfterWriteAll( } [Test] - public void WhenFileDoesNotExist_CreateWithUTF8WithPreamble() + public void WhenFileDoesNotExistCreateWithUtf8WithPreamble() { var encoding = Encoding.UTF8; diff --git a/src/GitVersionCore.Tests/IntegrationTests/HotfixBranchScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/HotfixBranchScenarios.cs index e0e5a550d2..7579fc30ff 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/HotfixBranchScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/HotfixBranchScenarios.cs @@ -125,7 +125,7 @@ public void PatchOlderReleaseExample() /// Create a feature branch from a hotfix branch, and merge back, then delete it /// [Test] - public void FeatureOnHotfix_FeatureBranchDeleted() + public void FeatureOnHotfixFeatureBranchDeleted() { var config = new Config { @@ -178,7 +178,7 @@ public void FeatureOnHotfix_FeatureBranchDeleted() /// Create a feature branch from a hotfix branch, and merge back, but don't delete it /// [Test] - public void FeatureOnHotfix_FeatureBranchNotDeleted() + public void FeatureOnHotfixFeatureBranchNotDeleted() { var config = new Config { diff --git a/src/GitVersionCore.Tests/IntegrationTests/MainlineDevelopmentMode.cs b/src/GitVersionCore.Tests/IntegrationTests/MainlineDevelopmentMode.cs index 5e215a3d70..f3660ae602 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/MainlineDevelopmentMode.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/MainlineDevelopmentMode.cs @@ -3,17 +3,18 @@ using System.Reflection; using System.Text; using GitTools.Testing; +using GitVersion; using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.VersioningModes; using LibGit2Sharp; using NUnit.Framework; +using GitVersion.Extensions; namespace GitVersionCore.Tests.IntegrationTests { public class MainlineDevelopmentMode : TestBase { - private Config config = new Config + private readonly Config config = new Config { VersioningMode = VersioningMode.Mainline }; @@ -321,7 +322,7 @@ public void VerifyMergingMasterToFeatureDoesNotStopMasterCommitsIncrementingVers } [Test] - public void VerifyIssue1154_CanForwardMergeMasterToFeatureBranch() + public void VerifyIssue1154CanForwardMergeMasterToFeatureBranch() { using var fixture = new EmptyRepositoryFixture(); fixture.MakeACommit(); diff --git a/src/GitVersionCore.Tests/IntegrationTests/MasterScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/MasterScenarios.cs index d17fba7fd0..5bf5847343 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/MasterScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/MasterScenarios.cs @@ -52,7 +52,7 @@ public void CanHandleContinuousDeployment() } [Test] - public void GivenARepositoryWithCommitsButNoTags_VersionShouldBe_0_1() + public void GivenARepositoryWithCommitsButNoTagsVersionShouldBe01() { using var fixture = new EmptyRepositoryFixture(); // Given @@ -65,7 +65,7 @@ public void GivenARepositoryWithCommitsButNoTags_VersionShouldBe_0_1() } [Test] - public void GivenARepositoryWithCommitsButBadTags_VersionShouldBe_0_1() + public void GivenARepositoryWithCommitsButBadTagsVersionShouldBe01() { using var fixture = new EmptyRepositoryFixture(); // Given @@ -79,7 +79,7 @@ public void GivenARepositoryWithCommitsButBadTags_VersionShouldBe_0_1() } [Test] - public void GivenARepositoryWithCommitsButNoTagsWithDetachedHead_VersionShouldBe_0_1() + public void GivenARepositoryWithCommitsButNoTagsWithDetachedHeadVersionShouldBe01() { using var fixture = new EmptyRepositoryFixture(); // Given @@ -96,66 +96,66 @@ public void GivenARepositoryWithCommitsButNoTagsWithDetachedHead_VersionShouldBe } [Test] - public void GivenARepositoryWithTagAndNextVersionInConfig_VersionShouldMatchVersionTxtFile() + public void GivenARepositoryWithTagAndNextVersionInConfigVersionShouldMatchVersionTxtFile() { - const string ExpectedNextVersion = "1.1.0"; - var config = new Config { NextVersion = ExpectedNextVersion }; + const string expectedNextVersion = "1.1.0"; + var config = new Config { NextVersion = expectedNextVersion }; using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver(config, "1.1.0+5"); } [Test] - public void GivenARepositoryWithTagAndANextVersionTxtFileAndNoCommits_VersionShouldBeTag() + public void GivenARepositoryWithTagAndANextVersionTxtFileAndNoCommitsVersionShouldBeTag() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.AssertFullSemver(new Config { NextVersion = "1.1.0" }, "1.0.3"); } [Test] - public void GivenARepositoryWithTagAndNoNextVersionTxtFile_VersionShouldBeTagWithBumpedPatch() + public void GivenARepositoryWithTagAndNoNextVersionTxtFileVersionShouldBeTagWithBumpedPatch() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver("1.0.4+5"); } [Test] - public void GivenARepositoryWithTagAndNoNextVersionTxtFileAndNoCommits_VersionShouldBeTag() + public void GivenARepositoryWithTagAndNoNextVersionTxtFileAndNoCommitsVersionShouldBeTag() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.AssertFullSemver("1.0.3"); } [Test] - public void GivenARepositoryWithTagAndOldNextVersionConfig_VersionShouldBeTagWithBumpedPatch() + public void GivenARepositoryWithTagAndOldNextVersionConfigVersionShouldBeTagWithBumpedPatch() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.1.0"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.1.0"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver(new Config { NextVersion = "1.0.0" }, "1.1.1+5"); } [Test] - public void GivenARepositoryWithTagAndOldNextVersionConfigAndNoCommits_VersionShouldBeTag() + public void GivenARepositoryWithTagAndOldNextVersionConfigAndNoCommitsVersionShouldBeTag() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.1.0"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.1.0"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.AssertFullSemver(new Config { NextVersion = "1.0.0" }, "1.1.0"); } @@ -164,8 +164,8 @@ public void GivenARepositoryWithTagAndOldNextVersionConfigAndNoCommits_VersionSh public void CanSpecifyTagPrefixes() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "version-1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "version-1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver(new Config { TagPrefix = "version-" }, "1.0.4+5"); @@ -176,14 +176,14 @@ public void CanSpecifyTagPrefixesAsRegex() { var config = new Config { TagPrefix = "version-|[vV]" }; using var fixture = new EmptyRepositoryFixture(); - var TaggedVersion = "v1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + var taggedVersion = "v1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver(config, "1.0.4+5"); - TaggedVersion = "version-1.0.5"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + taggedVersion = "version-1.0.5"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver(config, "1.0.6+5"); @@ -194,14 +194,14 @@ public void AreTagsNotAdheringToTagPrefixIgnored() { var config = new Config { TagPrefix = "" }; using var fixture = new EmptyRepositoryFixture(); - var TaggedVersion = "version-1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + var taggedVersion = "version-1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.AssertFullSemver(config, "0.1.0+5"); //Fallback version + 5 commits since tag - TaggedVersion = "bad/1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + taggedVersion = "bad/1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.AssertFullSemver(config, "0.1.0+6"); //Fallback version + 6 commits since tag } diff --git a/src/GitVersionCore.Tests/IntegrationTests/OtherBranchScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/OtherBranchScenarios.cs index e8d3ed6ac3..952b275056 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/OtherBranchScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/OtherBranchScenarios.cs @@ -12,8 +12,8 @@ public class OtherBranchScenarios : TestBase public void CanTakeVersionFromReleaseBranch() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release/beta-2.0.0"); Commands.Checkout(fixture.Repository, "release/beta-2.0.0"); @@ -25,8 +25,8 @@ public void CanTakeVersionFromReleaseBranch() public void BranchesWithIllegalCharsShouldNotBeUsedInVersionNames() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("issue/m/github-569"); Commands.Checkout(fixture.Repository, "issue/m/github-569"); diff --git a/src/GitVersionCore.Tests/IntegrationTests/OtherScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/OtherScenarios.cs index 28259135b4..a023542888 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/OtherScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/OtherScenarios.cs @@ -3,6 +3,7 @@ using LibGit2Sharp; using NUnit.Framework; using System.Collections.Generic; +using GitVersion; using GitVersion.Configuration; using GitVersion.VersioningModes; @@ -26,7 +27,7 @@ public void DoNotBlowUpWhenMasterAndDevelopPointAtSameCommit() Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); Commands.Checkout(fixture.LocalRepositoryFixture.Repository, fixture.Repository.Head.Tip); fixture.LocalRepositoryFixture.Repository.Branches.Remove("master"); - fixture.InitialiseRepo(); + fixture.InitializeRepo(); fixture.AssertFullSemver("1.0.1+1"); } @@ -93,7 +94,7 @@ public void DoNotBlowUpWhenDevelopAndFeatureBranchPointAtSameCommit() Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); Commands.Checkout(fixture.LocalRepositoryFixture.Repository, fixture.Repository.Head.Tip); fixture.LocalRepositoryFixture.Repository.Branches.Remove("master"); - fixture.InitialiseRepo(); + fixture.InitializeRepo(); fixture.AssertFullSemver("1.1.0-alpha.1"); } } diff --git a/src/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs index 4629247234..dd7e8ace84 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/PullRequestScenarios.cs @@ -1,7 +1,7 @@ using GitTools.Testing; using LibGit2Sharp; using NUnit.Framework; -using GitVersion.Helpers; +using GitVersion.Extensions; namespace GitVersionCore.Tests.IntegrationTests { diff --git a/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs index 57ce61b7b8..7360832a63 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs @@ -135,7 +135,7 @@ public void CanHandleReleaseBranchWithStability() } [Test] - public void WhenReleaseBranch_OffDevelop_IsMergedIntoMasterAndDevelop_VersionIsTakenWithIt() + public void WhenReleaseBranchOffDevelopIsMergedIntoMasterAndDevelopVersionIsTakenWithIt() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); @@ -154,7 +154,7 @@ public void WhenReleaseBranch_OffDevelop_IsMergedIntoMasterAndDevelop_VersionIsT } [Test] - public void WhenReleaseBranch_OffMaster_IsMergedIntoMaster_VersionIsTakenWithIt() + public void WhenReleaseBranchOffMasterIsMergedIntoMasterVersionIsTakenWithIt() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeATaggedCommit("1.0.3"); @@ -235,8 +235,8 @@ public void WhenReleaseBranchIsMergedIntoMasterHighestVersionIsTakenWithIt() public void WhenMergingReleaseBackToDevShouldNotResetBetaVersion() { using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.CreateBranch("develop"); fixture.Checkout("develop"); @@ -275,8 +275,8 @@ public void HotfixOffReleaseBranchShouldNotResetCount() VersioningMode = VersioningMode.ContinuousDeployment }; using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.CreateBranch("develop"); fixture.Checkout("develop"); @@ -313,8 +313,8 @@ public void MergeOnReleaseBranchShouldNotResetCount() VersioningMode = VersioningMode.ContinuousDeployment, }; using var fixture = new EmptyRepositoryFixture(); - const string TaggedVersion = "1.0.3"; - fixture.Repository.MakeATaggedCommit(TaggedVersion); + const string taggedVersion = "1.0.3"; + fixture.Repository.MakeATaggedCommit(taggedVersion); fixture.Repository.CreateBranch("develop"); fixture.Checkout("develop"); fixture.Repository.MakeACommit(); @@ -335,7 +335,7 @@ public void MergeOnReleaseBranchShouldNotResetCount() } [Test] - public void CommitOnDevelop_AfterReleaseBranchMergeToDevelop_ShouldNotResetCount() + public void CommitOnDevelopAfterReleaseBranchMergeToDevelopShouldNotResetCount() { var config = new Config { @@ -391,7 +391,7 @@ public void CommitOnDevelop_AfterReleaseBranchMergeToDevelop_ShouldNotResetCount } [Test] - public void CommitBeetweenMergeReleaseToDevelop_ShouldNotResetCount() + public void CommitBeetweenMergeReleaseToDevelopShouldNotResetCount() { var config = new Config { @@ -466,7 +466,7 @@ public void ReleaseBranchedAtCommitWithSemverMessageShouldUseBranchNameVersion() } [Test] - public void FeatureFromReleaseBranch_ShouldNotResetCount() + public void FeatureFromReleaseBranchShouldNotResetCount() { var config = new Config { @@ -532,7 +532,7 @@ public void AssemblySemFileVerShouldBeWeightedByPreReleaseWeight() fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); - ConfigurationProvider.ApplyDefaultsTo(config); + config.Reset(); var variables = fixture.GetVersion(config); Assert.AreEqual(variables.AssemblySemFileVer, "2.0.0.1001"); } @@ -549,7 +549,7 @@ public void AssemblySemFileVerShouldBeWeightedByDefaultPreReleaseWeight() fixture.Repository.MakeCommits(5); fixture.Repository.CreateBranch("release-2.0.0"); fixture.Checkout("release-2.0.0"); - ConfigurationProvider.ApplyDefaultsTo(config); + config.Reset(); var variables = fixture.GetVersion(config); Assert.AreEqual(variables.AssemblySemFileVer, "2.0.0.30001"); } @@ -558,7 +558,7 @@ public void AssemblySemFileVerShouldBeWeightedByDefaultPreReleaseWeight() /// Create a feature branch from a release branch, and merge back, then delete it /// [Test] - public void FeatureOnRelease_FeatureBranchDeleted() + public void FeatureOnReleaseFeatureBranchDeleted() { var config = new Config { @@ -593,7 +593,7 @@ public void FeatureOnRelease_FeatureBranchDeleted() /// Create a feature branch from a release branch, and merge back, but don't delete it /// [Test] - public void FeatureOnRelease_FeatureBranchNotDeleted() + public void FeatureOnReleaseFeatureBranchNotDeleted() { var config = new Config { diff --git a/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs index ba054f824c..d7111d2707 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs @@ -14,7 +14,7 @@ namespace GitVersionCore.Tests.IntegrationTests public class RemoteRepositoryScenarios : TestBase { [Test] - public void GivenARemoteGitRepositoryWithCommits_ThenClonedLocalShouldMatchRemoteVersion() + public void GivenARemoteGitRepositoryWithCommitsThenClonedLocalShouldMatchRemoteVersion() { using var fixture = new RemoteRepositoryFixture(); fixture.AssertFullSemver("0.1.0+4"); @@ -22,7 +22,7 @@ public void GivenARemoteGitRepositoryWithCommits_ThenClonedLocalShouldMatchRemot } [Test] - public void GivenARemoteGitRepositoryWithCommitsAndBranches_ThenClonedLocalShouldMatchRemoteVersion() + public void GivenARemoteGitRepositoryWithCommitsAndBranchesThenClonedLocalShouldMatchRemoteVersion() { using var fixture = new RemoteRepositoryFixture( path => @@ -48,7 +48,7 @@ public void GivenARemoteGitRepositoryWithCommitsAndBranches_ThenClonedLocalShoul } [Test] - public void GivenARemoteGitRepositoryAheadOfLocalRepository_ThenChangesShouldPull() + public void GivenARemoteGitRepositoryAheadOfLocalRepositoryThenChangesShouldPull() { using var fixture = new RemoteRepositoryFixture(); fixture.Repository.MakeACommit(); @@ -60,7 +60,7 @@ public void GivenARemoteGitRepositoryAheadOfLocalRepository_ThenChangesShouldPul } [Test] - public void GivenARemoteGitRepositoryWhenCheckingOutDetachedhead_UsingExistingImplementationThrowsException() + public void GivenARemoteGitRepositoryWhenCheckingOutDetachedheadUsingExistingImplementationThrowsException() { using var fixture = new RemoteRepositoryFixture(); Commands.Checkout( @@ -72,7 +72,7 @@ public void GivenARemoteGitRepositoryWhenCheckingOutDetachedhead_UsingExistingIm } [Test] - public void GivenARemoteGitRepositoryWhenCheckingOutDetachedhead_UsingTrackingBranchOnlyBehaviourShouldReturnVersion_0_1_4plus5() + public void GivenARemoteGitRepositoryWhenCheckingOutDetachedheadUsingTrackingBranchOnlyBehaviourShouldReturnVersion014Plus5() { using var fixture = new RemoteRepositoryFixture(); Commands.Checkout(fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Head.Tip); diff --git a/src/GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs index 232d2b2964..3f086b37ca 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/SwitchingToGitFlowScenarios.cs @@ -8,7 +8,7 @@ namespace GitVersionCore.Tests.IntegrationTests public class SwitchingToGitFlowScenarios : TestBase { [Test] - public void WhenDevelopBranchedFromMasterWithLegacyVersionTags_DevelopCanUseReachableTag() + public void WhenDevelopBranchedFromMasterWithLegacyVersionTagsDevelopCanUseReachableTag() { using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeCommits(5); diff --git a/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs b/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs index ff8d8d1d72..55224a3e14 100644 --- a/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs +++ b/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs @@ -1,10 +1,11 @@ using System; -using GitVersion; using GitVersion.Logging; using NUnit.Framework; using Shouldly; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; +using GitVersion; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests { @@ -33,7 +34,12 @@ public void Json() var config = new TestEffectiveConfiguration(); - var variableProvider = new VariableProvider(new NullLog()); + var log = new NullLog(); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); var json = JsonOutputFormatter.ToJson(variables); json.ShouldMatchApproved(c => c.SubFolder("Approved")); diff --git a/src/GitVersionCore.Tests/MergeMessageTests.cs b/src/GitVersionCore.Tests/MergeMessageTests.cs index ad278a75d1..bce6a2d788 100644 --- a/src/GitVersionCore.Tests/MergeMessageTests.cs +++ b/src/GitVersionCore.Tests/MergeMessageTests.cs @@ -10,13 +10,13 @@ namespace GitVersionCore.Tests [TestFixture] public class MergeMessageTests : TestBase { - private readonly Config _config = new Config { TagPrefix = "[vV]" }; + private readonly Config config = new Config { TagPrefix = "[vV]" }; [Test] public void NullMessageStringThrows() { // Act / Assert - Should.Throw(() => new MergeMessage(null, _config)); + Should.Throw(() => new MergeMessage(null, config)); } [TestCase("")] @@ -24,7 +24,7 @@ public void NullMessageStringThrows() public void EmptyMessageString(string message) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.TargetBranch.ShouldBeNull(); @@ -73,7 +73,7 @@ public void ParsesMergeMessage( SemanticVersion expectedVersion) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBe("Default"); @@ -104,7 +104,7 @@ public void ParsesGitHubPullMergeMessage( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBe("GitHubPull"); @@ -138,7 +138,7 @@ public void ParsesBitBucketPullMergeMessage( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBe("BitBucketPull"); @@ -169,7 +169,7 @@ public void ParsesSmartGitMergeMessage( SemanticVersion expectedVersion) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBe("SmartGit"); @@ -199,7 +199,7 @@ public void ParsesRemoteTrackingMergeMessage( SemanticVersion expectedVersion) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBe("RemoteTracking"); @@ -226,7 +226,7 @@ public void ParsesInvalidMergeMessage( int? expectedPullRequestNumber) { // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBeNull(); @@ -243,13 +243,13 @@ public void MatchesSingleCustomMessage() // Arrange var message = "My custom message"; var definition = "Mycustom"; - _config.MergeMessageFormats = new Dictionary + config.MergeMessageFormats = new Dictionary { [definition] = message }; // Act - var sut = new MergeMessage(message, _config); + var sut = new MergeMessage(message, config); // Assert sut.FormatName.ShouldBe(definition); @@ -266,7 +266,7 @@ public void MatchesMultipleCustomMessages() // Arrange var format = "My custom message"; var definition = "Mycustom"; - _config.MergeMessageFormats = new Dictionary + config.MergeMessageFormats = new Dictionary { ["Default2"] = "some example", ["Default3"] = "another example", @@ -274,7 +274,7 @@ public void MatchesMultipleCustomMessages() }; // Act - var sut = new MergeMessage(format, _config); + var sut = new MergeMessage(format, config); // Assert sut.FormatName.ShouldBe(definition); @@ -291,7 +291,7 @@ public void MatchesCaptureGroupsFromCustomMessages() // Arrange var format = @"^Merged PR #(?\d+) into (?[^\s]*) from (?:(?[^\s]*))"; var definition = "Mycustom"; - _config.MergeMessageFormats = new Dictionary + config.MergeMessageFormats = new Dictionary { [definition] = format }; @@ -301,7 +301,7 @@ public void MatchesCaptureGroupsFromCustomMessages() // Act - var sut = new MergeMessage($"Merged PR #{pr} into {target} from {source}", _config); + var sut = new MergeMessage($"Merged PR #{pr} into {target} from {source}", config); // Assert sut.FormatName.ShouldBe(definition); @@ -318,7 +318,7 @@ public void ReturnsAfterFirstMatchingPattern() // Arrange var format = @"^Merge (branch|tag) '(?[^']*)'(?: into (?[^\s]*))*"; var definition = "Mycustom"; - _config.MergeMessageFormats = new Dictionary + config.MergeMessageFormats = new Dictionary { [definition] = format, ["Default2"] = format, @@ -326,7 +326,7 @@ public void ReturnsAfterFirstMatchingPattern() }; // Act - var sut = new MergeMessage("Merge branch 'this'", _config); + var sut = new MergeMessage("Merge branch 'this'", config); // Assert sut.FormatName.ShouldBe(definition); diff --git a/src/GitVersionCore.Tests/Mocks/MockBranch.cs b/src/GitVersionCore.Tests/Mocks/MockBranch.cs index b0f0ff5933..574ac01b14 100644 --- a/src/GitVersionCore.Tests/Mocks/MockBranch.cs +++ b/src/GitVersionCore.Tests/Mocks/MockBranch.cs @@ -23,8 +23,8 @@ public MockBranch() } - private MockCommitLog commits = new MockCommitLog(); - private string friendlyName; + private readonly MockCommitLog commits = new MockCommitLog(); + private readonly string friendlyName; public override string FriendlyName => friendlyName; public override ICommitLog Commits => commits; public override Commit Tip => commits.First(); diff --git a/src/GitVersionCore.Tests/Mocks/MockCommit.cs b/src/GitVersionCore.Tests/Mocks/MockCommit.cs index 51a46ff9e8..e6dba7f17c 100644 --- a/src/GitVersionCore.Tests/Mocks/MockCommit.cs +++ b/src/GitVersionCore.Tests/Mocks/MockCommit.cs @@ -27,7 +27,7 @@ public MockCommit(ObjectId id = null) public Signature CommitterEx; public override Signature Committer => CommitterEx; - private ObjectId idEx; + private readonly ObjectId idEx; public override ObjectId Id => idEx; public override string Sha => idEx.Sha; diff --git a/src/GitVersionCore.Tests/Mocks/MockThreadSleep.cs b/src/GitVersionCore.Tests/Mocks/MockThreadSleep.cs index 9c889346d6..f313c94aeb 100644 --- a/src/GitVersionCore.Tests/Mocks/MockThreadSleep.cs +++ b/src/GitVersionCore.Tests/Mocks/MockThreadSleep.cs @@ -1,23 +1,23 @@ using System; using System.Threading.Tasks; -using GitVersion.Common; +using GitVersion; namespace GitVersionCore.Tests.Mocks { public class MockThreadSleep : IThreadSleep { - private Func Validator; + private readonly Func validator; public MockThreadSleep(Func validator = null) { - Validator = validator; + this.validator = validator; } public async Task SleepAsync(int milliseconds) { - if (Validator != null) + if (validator != null) { - await Validator(milliseconds); + await validator(milliseconds); } } } diff --git a/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs b/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs index 86733245e1..2e8450bbeb 100644 --- a/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs +++ b/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs @@ -3,8 +3,10 @@ using Shouldly; using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.Common; +using GitVersion; +using GitVersion.Configuration.Init.Wizard; using GitVersion.Logging; +using Microsoft.Extensions.Options; namespace GitVersionCore.Tests { @@ -19,15 +21,20 @@ public class NamedConfigFileLocatorTests : TestBase private IFileSystem fileSystem; private NamedConfigFileLocator configFileLocator; private ILog log; + private IConfigInitStepFactory stepFactory; + private IOptions options; [SetUp] public void Setup() { fileSystem = new TestFileSystem(); log = new NullLog(); - configFileLocator = new NamedConfigFileLocator("my-config.yaml", fileSystem, log); + + options = Options.Create(new Arguments { ConfigFile = "my-config.yaml" }); + configFileLocator = new NamedConfigFileLocator(fileSystem, log, options); repoPath = DefaultRepoPath; workingPath = DefaultWorkingPath; + stepFactory = new ConfigInitStepFactory(); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); } @@ -55,9 +62,13 @@ public void NoWarnOnCustomYmlFile() var logAppender = new TestLogAppender(Action); log = new Log(logAppender); - configFileLocator = new NamedConfigFileLocator("my-config.yaml", fileSystem, log); + configFileLocator = new NamedConfigFileLocator(fileSystem, log, options); + + var gitPreparer = new GitPreparer(log, Options.Create(new Arguments { TargetPath = repoPath })); + var configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + var configurationProvider = new ConfigProvider(fileSystem, log, configFileLocator, gitPreparer, configInitWizard); - ConfigurationProvider.Provide(repoPath, configFileLocator); + configurationProvider.Provide(repoPath); stringLogger.Length.ShouldBe(0); } @@ -72,9 +83,12 @@ public void NoWarnOnCustomYmlFileOutsideRepoPath() var logAppender = new TestLogAppender(Action); log = new Log(logAppender); - configFileLocator = new NamedConfigFileLocator("my-config.yaml", fileSystem, log); + configFileLocator = new NamedConfigFileLocator(fileSystem, log, options); + var gitPreparer = new GitPreparer(log, Options.Create(new Arguments { TargetPath = repoPath })); + var configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + var configurationProvider = new ConfigProvider(fileSystem, log, configFileLocator, gitPreparer, configInitWizard); - ConfigurationProvider.Provide(repoPath, configFileLocator); + configurationProvider.Provide(repoPath); stringLogger.Length.ShouldBe(0); } diff --git a/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs b/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs index 69523141dc..26e6b9e23b 100644 --- a/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs +++ b/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs @@ -35,12 +35,12 @@ void Operation() } var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), new NullLog(), Operation); - Task action = retryOperation.ExecuteAsync(); + var action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); } [Test] - public async Task OperationIsRetriedOnIOException() + public async Task OperationIsRetriedOnIoException() { var operationCount = 0; @@ -72,7 +72,7 @@ void Operation() } var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), new NullLog(), Operation, numberOfRetries); - Task action = retryOperation.ExecuteAsync(); + var action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); operationCount.ShouldBe(numberOfRetries + 1); @@ -98,7 +98,7 @@ Task Validator(int u) } var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(Validator), new NullLog(), Operation, numberOfRetries); - Task action = retryOperation.ExecuteAsync(); + var action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); // action.ShouldThrow(); @@ -110,7 +110,7 @@ Task Validator(int u) public async Task TotalSleepTimeForSixRetriesIsAboutThirtySecondsAsync() { const int numberOfRetries = 6; - int totalSleep = 0; + var totalSleep = 0; void Operation() { @@ -124,7 +124,7 @@ Task Validator(int u) var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(Validator), new NullLog(), Operation, numberOfRetries); - Task action = retryOperation.ExecuteAsync(); + var action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); // Action action = () => retryOperation.ExecuteAsync(); // action.ShouldThrow(); diff --git a/src/GitVersionCore.Tests/SemanticVersionTests.cs b/src/GitVersionCore.Tests/SemanticVersionTests.cs index 941dd58d80..b5e40e7707 100644 --- a/src/GitVersionCore.Tests/SemanticVersionTests.cs +++ b/src/GitVersionCore.Tests/SemanticVersionTests.cs @@ -1,7 +1,7 @@ -using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.Configuration; +using GitVersion; namespace GitVersionCore.Tests { @@ -29,15 +29,15 @@ public class SemanticVersionTests : TestBase [TestCase("1.2.3+4.Branch.Foo", 1, 2, 3, null, null, 4, "Foo", null, null, null, null)] [TestCase("1.2.3+randomMetaData", 1, 2, 3, null, null, null, null, null, "randomMetaData", null, null)] [TestCase("1.2.3-beta.1+4.Sha.12234.Othershiz", 1, 2, 3, "beta", 1, 4, null, "12234", "Othershiz", null, null)] - [TestCase("1.2.3", 1, 2, 3, null, null, null, null, null, null, null, ConfigurationProvider.DefaultTagPrefix)] - [TestCase("v1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", ConfigurationProvider.DefaultTagPrefix)] - [TestCase("V1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", ConfigurationProvider.DefaultTagPrefix)] + [TestCase("1.2.3", 1, 2, 3, null, null, null, null, null, null, null, Config.DefaultTagPrefix)] + [TestCase("v1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", Config.DefaultTagPrefix)] + [TestCase("V1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", Config.DefaultTagPrefix)] [TestCase("version-1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", "version-")] public void ValidateVersionParsing( string versionString, int major, int minor, int patch, string tag, int? tagNumber, int? numberOfBuilds, string branchName, string sha, string otherMetaData, string fullFormattedVersionString, string tagPrefixRegex) { - fullFormattedVersionString = fullFormattedVersionString ?? versionString; + fullFormattedVersionString ??= versionString; SemanticVersion.TryParse(versionString, tagPrefixRegex, out var version).ShouldBe(true, versionString); Assert.AreEqual(major, version.Major); @@ -141,7 +141,7 @@ public void ToStringLTests() Assert.AreEqual("1.2.3-beta4", fullSemVer.ToString("l")); } [Test] - public void ToStringLPTests() + public void ToStringLpTests() { Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("lp")); Assert.AreEqual("1.2.3-beta0004", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("lp")); diff --git a/src/GitVersionCore.Tests/StringFormatWithExtensionTests.cs b/src/GitVersionCore.Tests/StringFormatWithExtensionTests.cs index a542ea3a46..3075e7d14b 100644 --- a/src/GitVersionCore.Tests/StringFormatWithExtensionTests.cs +++ b/src/GitVersionCore.Tests/StringFormatWithExtensionTests.cs @@ -9,7 +9,7 @@ namespace GitVersionCore.Tests public class StringFormatWithExtensionTests { [Test] - public void FormatWith_NoTokens() + public void FormatWithNoTokens() { var propertyObject = new { }; var target = "Some String without tokens"; @@ -19,7 +19,7 @@ public void FormatWith_NoTokens() } [Test] - public void FormatWith_SingleSimpleToken() + public void FormatWithSingleSimpleToken() { var propertyObject = new { SomeProperty = "SomeValue" }; var target = "{SomeProperty}"; @@ -29,7 +29,7 @@ public void FormatWith_SingleSimpleToken() } [Test] - public void FormatWith_MultipleTokensAndVerbatimText() + public void FormatWithMultipleTokensAndVerbatimText() { var propertyObject = new { SomeProperty = "SomeValue", AnotherProperty = "Other Value" }; var target = "{SomeProperty} some text {AnotherProperty}"; @@ -39,7 +39,7 @@ public void FormatWith_MultipleTokensAndVerbatimText() } [Test] - public void FormatWith_EnvVarToken() + public void FormatWithEnvVarToken() { Environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; @@ -50,7 +50,7 @@ public void FormatWith_EnvVarToken() } [Test] - public void FormatWith_EnvVarTokenWithFallback() + public void FormatWithEnvVarTokenWithFallback() { Environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR", "Env Var Value"); var propertyObject = new { }; @@ -61,7 +61,7 @@ public void FormatWith_EnvVarTokenWithFallback() } [Test] - public void FormatWith_UnsetEnvVarTokenWithFallback() + public void FormatWithUnsetEnvVarTokenWithFallback() { Environment.SetEnvironmentVariable("GIT_VERSION_UNSET_TEST_VAR", null); var propertyObject = new { }; @@ -72,7 +72,7 @@ public void FormatWith_UnsetEnvVarTokenWithFallback() } [Test] - public void FormatWith_MultipleEnvVars() + public void FormatWithMultipleEnvVars() { Environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_1", "Val-1"); Environment.SetEnvironmentVariable("GIT_VERSION_TEST_VAR_2", "Val-2"); @@ -84,7 +84,7 @@ public void FormatWith_MultipleEnvVars() } [Test] - public void FormatWith_MultipleEnvChars() + public void FormatWithMultipleEnvChars() { var propertyObject = new { }; //Test the greediness of the regex in matching env: char @@ -95,7 +95,7 @@ public void FormatWith_MultipleEnvChars() } [Test] - public void FormatWith_MultipleFallbackChars() + public void FormatWithMultipleFallbackChars() { var propertyObject = new { }; //Test the greediness of the regex in matching env: and ?? chars @@ -105,7 +105,7 @@ public void FormatWith_MultipleFallbackChars() } [Test] - public void FormatWith_SingleFallbackChar() + public void FormatWithSingleFallbackChar() { Environment.SetEnvironmentVariable("DUMMY_ENV_VAR", "Dummy-Val"); var propertyObject = new { }; @@ -116,7 +116,7 @@ public void FormatWith_SingleFallbackChar() } [Test] - public void FormatWIth_NullPropagationWithMultipleSpaces() + public void FormatWIthNullPropagationWithMultipleSpaces() { var propertyObject = new { SomeProperty = "Some Value" }; var target = "{SomeProperty} and {env:DUMMY_ENV_VAR ?? fallback}"; diff --git a/src/GitVersionCore.Tests/TestEnvironment.cs b/src/GitVersionCore.Tests/TestEnvironment.cs index 5a93cc47bc..bb50eee453 100644 --- a/src/GitVersionCore.Tests/TestEnvironment.cs +++ b/src/GitVersionCore.Tests/TestEnvironment.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; -using GitVersion.Common; +using GitVersion; namespace GitVersionCore.Tests { public class TestEnvironment : IEnvironment { - private IDictionary map; + private readonly IDictionary map; public TestEnvironment() { diff --git a/src/GitVersionCore.Tests/TestFileSystem.cs b/src/GitVersionCore.Tests/TestFileSystem.cs index e75315fbdc..2dff623698 100644 --- a/src/GitVersionCore.Tests/TestFileSystem.cs +++ b/src/GitVersionCore.Tests/TestFileSystem.cs @@ -3,13 +3,13 @@ using System.IO; using System.Text; using GitVersion.Helpers; -using GitVersion.Common; +using GitVersion; namespace GitVersionCore.Tests { public class TestFileSystem : IFileSystem { - private Dictionary fileSystem = new Dictionary(); + private readonly Dictionary fileSystem = new Dictionary(); public void Copy(string @from, string to, bool overwrite) { diff --git a/src/GitVersionCore.Tests/TestStream.cs b/src/GitVersionCore.Tests/TestStream.cs index 003062dc43..6e11299480 100644 --- a/src/GitVersionCore.Tests/TestStream.cs +++ b/src/GitVersionCore.Tests/TestStream.cs @@ -6,7 +6,7 @@ public class TestStream : Stream { private readonly string path; private readonly TestFileSystem testFileSystem; - private MemoryStream underlying = new MemoryStream(); + private readonly MemoryStream underlying = new MemoryStream(); public TestStream(string path, TestFileSystem testFileSystem) { diff --git a/src/GitVersionCore.Tests/VariableProviderTests.cs b/src/GitVersionCore.Tests/VariableProviderTests.cs index 7451c15c42..5d38b41f1a 100644 --- a/src/GitVersionCore.Tests/VariableProviderTests.cs +++ b/src/GitVersionCore.Tests/VariableProviderTests.cs @@ -1,10 +1,11 @@ using System; -using GitVersion; using GitVersion.Logging; using NUnit.Framework; using Shouldly; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; +using GitVersion; +using GitVersion.VersionCalculation; using GitVersion.VersioningModes; namespace GitVersionCore.Tests @@ -19,7 +20,11 @@ public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); var log = new NullLog(); - variableProvider = new VariableProvider(log); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + variableProvider = new VariableProvider(nextVersionCalculator); } [Test] diff --git a/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index b6c33c082a..5b8af42c91 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -10,15 +10,15 @@ using LibGit2Sharp; using NUnit.Framework; using Shouldly; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersionCore.Tests.VersionCalculation { [TestFixture] public class BaseVersionCalculatorTests : TestBase { - private ILog log; + private readonly ILog log; public BaseVersionCalculatorTests() { @@ -29,7 +29,9 @@ public void ChoosesHighestVersionReturnedFromStrategies() { var context = new GitVersionContextBuilder().Build(); var dateTimeOffset = DateTimeOffset.Now; - var sut = new BaseVersionCalculator(log, new V1Strategy(DateTimeOffset.Now), new V2Strategy(dateTimeOffset)); + + var versionStrategies = new IVersionStrategy[] { new V1Strategy(DateTimeOffset.Now), new V2Strategy(dateTimeOffset) }; + var sut = new BaseVersionCalculator(log, versionStrategies); var baseVersion = sut.GetBaseVersion(context); @@ -43,7 +45,9 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhen() { var context = new GitVersionContextBuilder().Build(); var when = DateTimeOffset.Now; - var sut = new BaseVersionCalculator(log, new V1Strategy(when), new V2Strategy(null)); + + var versionStrategies = new IVersionStrategy[] { new V1Strategy(when), new V2Strategy(null) }; + var sut = new BaseVersionCalculator(log, versionStrategies); var baseVersion = sut.GetBaseVersion(context); @@ -57,7 +61,9 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() { var context = new GitVersionContextBuilder().Build(); var when = DateTimeOffset.Now; - var sut = new BaseVersionCalculator(log, new V1Strategy(null), new V2Strategy(when)); + + var versionStrategies = new IVersionStrategy[] { new V1Strategy(null), new V2Strategy(when) }; + var sut = new BaseVersionCalculator(log, versionStrategies); var baseVersion = sut.GetBaseVersion(context); @@ -66,7 +72,7 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() baseVersion.BaseVersionSource.When().ShouldBe(when); } - private class V1Strategy : BaseVersionStrategy + private class V1Strategy : IVersionStrategy { private readonly Commit when; @@ -75,22 +81,22 @@ public V1Strategy(DateTimeOffset? when) this.when = when == null ? null : new MockCommit { CommitterEx = Generate.Signature(when.Value) }; } - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { yield return new BaseVersion(context, "Source 1", false, new SemanticVersion(1), when, null); } } - private class V2Strategy : BaseVersionStrategy + private class V2Strategy : IVersionStrategy { - private Commit when; + private readonly Commit when; public V2Strategy(DateTimeOffset? when) { this.when = when == null ? null : new MockCommit { CommitterEx = Generate.Signature(when.Value) }; } - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { yield return new BaseVersion(context, "Source 2", true, new SemanticVersion(2), when, null); } @@ -102,7 +108,9 @@ public void ShouldNotFilterVersion() var fakeIgnoreConfig = new TestIgnoreConfig(new ExcludeSourcesContainingExclude()); var context = new GitVersionContextBuilder().WithConfig(new Config() { Ignore = fakeIgnoreConfig }).Build(); var version = new BaseVersion(context, "dummy", false, new SemanticVersion(2), new MockCommit(), null); - var sut = new BaseVersionCalculator(log, new TestVersionStrategy(version)); + + var versionStrategies = new IVersionStrategy[] { new TestVersionStrategy(version) }; + var sut = new BaseVersionCalculator(log, versionStrategies); var baseVersion = sut.GetBaseVersion(context); @@ -118,7 +126,9 @@ public void ShouldFilterVersion() var context = new GitVersionContextBuilder().WithConfig(new Config() { Ignore = fakeIgnoreConfig }).Build(); var higherVersion = new BaseVersion(context, "exclude", false, new SemanticVersion(2), new MockCommit(), null); var lowerVersion = new BaseVersion(context, "dummy", false, new SemanticVersion(1), new MockCommit(), null); - var sut = new BaseVersionCalculator(log, new TestVersionStrategy(higherVersion, lowerVersion)); + + var versionStrategies = new IVersionStrategy[] { new TestVersionStrategy(higherVersion, lowerVersion) }; + var sut = new BaseVersionCalculator(log, versionStrategies); var baseVersion = sut.GetBaseVersion(context); @@ -158,7 +168,7 @@ public bool Exclude(BaseVersion version, out string reason) } } - private class TestVersionStrategy : BaseVersionStrategy + private class TestVersionStrategy : IVersionStrategy { private readonly IEnumerable versions; @@ -167,7 +177,7 @@ public TestVersionStrategy(params BaseVersion[] versions) this.versions = versions; } - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { return versions; } diff --git a/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs b/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs index 6afd5e943d..e16a1e715e 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using GitTools.Testing; -using GitVersion; using GitVersion.Configuration; using GitVersion.VersionCalculation; using GitVersion.VersioningModes; @@ -9,25 +8,30 @@ using LibGit2Sharp; using NUnit.Framework; using Shouldly; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion; +using GitVersion.Extensions; namespace GitVersionCore.Tests.VersionCalculation { public class NextVersionCalculatorTests : TestBase { - private ILog log; + private readonly ILog log; + private IMainlineVersionCalculator mainlineVersionCalculator; public NextVersionCalculatorTests() { + var metaDataCalculator = new MetaDataCalculator(); + log = new NullLog(); + mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); } [Test] public void ShouldIncrementVersionBasedOnConfig() { var baseCalculator = new TestBaseVersionCalculator(true, new SemanticVersion(1), new MockCommit()); var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 1, "master", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now); - var sut = new NextVersionCalculator(log, baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var sut = new NextVersionCalculator(log, new TestMetaDataCalculator(semanticVersionBuildMetaData), baseCalculator, mainlineVersionCalculator); var config = new Config(); var context = new GitVersionContextBuilder().WithConfig(config).Build(); @@ -41,7 +45,7 @@ public void DoesNotIncrementWhenBaseVersionSaysNotTo() { var baseCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit()); var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 1, "master", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now); - var sut = new NextVersionCalculator(log, baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var sut = new NextVersionCalculator(log, new TestMetaDataCalculator(semanticVersionBuildMetaData), baseCalculator, mainlineVersionCalculator); var config = new Config(); var context = new GitVersionContextBuilder().WithConfig(config).Build(); @@ -55,7 +59,7 @@ public void AppliesBranchPreReleaseTag() { var baseCalculator = new TestBaseVersionCalculator(false, new SemanticVersion(1), new MockCommit()); var semanticVersionBuildMetaData = new SemanticVersionBuildMetaData("ef7d0d7e1e700f1c7c9fa01ea6791bb778a5c37c", 2, "develop", "b1a34edbd80e141f7cc046c074f109be7d022074", "b1a34e", DateTimeOffset.Now); - var sut = new NextVersionCalculator(log, baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var sut = new NextVersionCalculator(log, new TestMetaDataCalculator(semanticVersionBuildMetaData), baseCalculator, mainlineVersionCalculator); var context = new GitVersionContextBuilder() .WithDevelopBranch() .Build(); diff --git a/src/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs b/src/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs index 30fd42418e..76810beb1b 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/Strategies/ConfigNextVersionBaseVersionStrategyTests.cs @@ -17,7 +17,7 @@ public void ShouldNotBeIncremented() { NextVersion = "1.0.0" }); - var sut = new ConfigNextVersionBaseVersionStrategy(); + var sut = new ConfigNextVersionVersionStrategy(); var baseVersion = sut.GetVersions(contextBuilder.Build()).Single(); @@ -29,7 +29,7 @@ public void ShouldNotBeIncremented() public void ReturnsNullWhenNoNextVersionIsInConfig() { var contextBuilder = new GitVersionContextBuilder(); - var sut = new ConfigNextVersionBaseVersionStrategy(); + var sut = new ConfigNextVersionVersionStrategy(); var baseVersion = sut.GetVersions(contextBuilder.Build()).SingleOrDefault(); @@ -44,7 +44,7 @@ public void NextVersionCanBeInteger() { NextVersion = "2" }); - var sut = new ConfigNextVersionBaseVersionStrategy(); + var sut = new ConfigNextVersionVersionStrategy(); var baseVersion = sut.GetVersions(contextBuilder.Build()).Single(); @@ -59,7 +59,7 @@ public void NextVersionCanHaveEnormousMinorVersion() { NextVersion = "2.118998723" }); - var sut = new ConfigNextVersionBaseVersionStrategy(); + var sut = new ConfigNextVersionVersionStrategy(); var baseVersion = sut.GetVersions(contextBuilder.Build()).Single(); @@ -74,7 +74,7 @@ public void NextVersionCanHavePatch() { NextVersion = "2.12.654651698" }); - var sut = new ConfigNextVersionBaseVersionStrategy(); + var sut = new ConfigNextVersionVersionStrategy(); var baseVersion = sut.GetVersions(contextBuilder.Build()).Single(); diff --git a/src/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs b/src/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs index f72f363c1e..4ed4968e92 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/Strategies/MergeMessageBaseVersionStrategyTests.cs @@ -25,7 +25,7 @@ public void ShouldNotAllowIncrementOfVersion() ParentsEx = GetParents(true) } } }).Build(); - var sut = new MergeMessageBaseVersionStrategy(); + var sut = new MergeMessageVersionStrategy(); var baseVersion = sut.GetVersions(context).Single(); @@ -162,7 +162,7 @@ private static void AssertMergeMessage(string message, string expectedVersion, L } }) .Build(); - var sut = new MergeMessageBaseVersionStrategy(); + var sut = new MergeMessageVersionStrategy(); var baseVersion = sut.GetVersions(context).SingleOrDefault(); diff --git a/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs b/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs index 5f68d7ff36..089a2f518d 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs @@ -21,7 +21,7 @@ public void CanTakeVersionFromNameOfReleaseBranch(string branchName, string expe using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); var branch = fixture.Repository.CreateBranch(branchName); - var sut = new VersionInBranchNameBaseVersionStrategy(); + var sut = new VersionInBranchNameVersionStrategy(); var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, new Config().ApplyDefaults()); var baseVersion = sut.GetVersions(gitVersionContext).Single(); @@ -38,7 +38,7 @@ public void ShouldNotTakeVersionFromNameOfNonReleaseBranch(string branchName) using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); var branch = fixture.Repository.CreateBranch(branchName); - var sut = new VersionInBranchNameBaseVersionStrategy(); + var sut = new VersionInBranchNameVersionStrategy(); var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, new Config().ApplyDefaults()); var baseVersions = sut.GetVersions(gitVersionContext); @@ -53,7 +53,7 @@ public void CanTakeVersionFromNameOfConfiguredReleaseBranch(string branchName, s using var fixture = new EmptyRepositoryFixture(); fixture.Repository.MakeACommit(); var branch = fixture.Repository.CreateBranch(branchName); - var sut = new VersionInBranchNameBaseVersionStrategy(); + var sut = new VersionInBranchNameVersionStrategy(); var branchConfigs = new Dictionary { { "support", new BranchConfig { IsReleaseBranch = true } } }; var config = new Config { Branches = branchConfigs }.ApplyDefaults(); @@ -75,7 +75,7 @@ public void CanTakeVersionFromNameOfRemoteReleaseBranch(string branchName, strin Commands.Fetch((Repository)fixture.LocalRepositoryFixture.Repository, fixture.LocalRepositoryFixture.Repository.Network.Remotes.First().Name, new string[0], new FetchOptions(), null); fixture.LocalRepositoryFixture.Checkout($"origin/{branchName}"); - var sut = new VersionInBranchNameBaseVersionStrategy(); + var sut = new VersionInBranchNameVersionStrategy(); var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, new Config().ApplyDefaults()); var baseVersion = sut.GetVersions(gitVersionContext).Single(); diff --git a/src/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs b/src/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs index 81e583ae27..ce289eca2b 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/TestBaseVersionCalculator.cs @@ -1,4 +1,5 @@ using GitVersion; +using GitVersion.Logging; using GitVersion.VersionCalculation; using GitVersion.VersionCalculation.BaseVersionCalculators; using LibGit2Sharp; @@ -8,8 +9,8 @@ namespace GitVersionCore.Tests.VersionCalculation public class TestBaseVersionCalculator : IBaseVersionCalculator { private readonly SemanticVersion semanticVersion; - private bool shouldIncrement; - private Commit source; + private readonly bool shouldIncrement; + private readonly Commit source; public TestBaseVersionCalculator(bool shouldIncrement, SemanticVersion semanticVersion, Commit source) { @@ -23,4 +24,20 @@ public BaseVersion GetBaseVersion(GitVersionContext context) return new BaseVersion(context, "Test source", shouldIncrement, semanticVersion, source, null); } } -} \ No newline at end of file + + public class TestBaseVersionStrategiesCalculator : BaseVersionCalculator + { + private static readonly IVersionStrategy[] VersionStrategies = new IVersionStrategy[] + { + new FallbackVersionStrategy(), + new ConfigNextVersionVersionStrategy(), + new TaggedCommitVersionStrategy(), + new MergeMessageVersionStrategy(), + new VersionInBranchNameVersionStrategy(), + new TrackReleaseBranchesVersionStrategy() + }; + public TestBaseVersionStrategiesCalculator(ILog log) : base(log, VersionStrategies) + { + } + } +} diff --git a/src/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs b/src/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs index ec5baba817..c08f62aacd 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/TestMetaDataCalculator.cs @@ -6,7 +6,7 @@ namespace GitVersionCore.Tests.VersionCalculation { public class TestMetaDataCalculator : IMetaDataCalculator { - private SemanticVersionBuildMetaData metaData; + private readonly SemanticVersionBuildMetaData metaData; public TestMetaDataCalculator(SemanticVersionBuildMetaData metaData) { diff --git a/src/GitVersionCore.Tests/VersionFilters/MinDateVersionFilterTests.cs b/src/GitVersionCore.Tests/VersionFilters/MinDateVersionFilterTests.cs index e995c79fe2..61ccdb9df3 100644 --- a/src/GitVersionCore.Tests/VersionFilters/MinDateVersionFilterTests.cs +++ b/src/GitVersionCore.Tests/VersionFilters/MinDateVersionFilterTests.cs @@ -1,9 +1,9 @@ -using GitVersion; using GitVersion.VersionCalculation.BaseVersionCalculators; using GitVersion.VersionFilters; using NUnit.Framework; using Shouldly; using System; +using GitVersion; using GitVersionCore.Tests.Mocks; namespace GitVersionCore.Tests.VersionFilters diff --git a/src/GitVersionCore.Tests/VersionSourceTests.cs b/src/GitVersionCore.Tests/VersionSourceTests.cs index 498ef7e261..9e169c823e 100644 --- a/src/GitVersionCore.Tests/VersionSourceTests.cs +++ b/src/GitVersionCore.Tests/VersionSourceTests.cs @@ -3,6 +3,7 @@ using GitVersion.Configuration; using GitVersion.Logging; using GitVersion.VersionCalculation; +using GitVersionCore.Tests.VersionCalculation; using LibGit2Sharp; using NUnit.Framework; using Shouldly; @@ -13,10 +14,17 @@ namespace GitVersionCore.Tests public class VersionSourceTests : TestBase { private ILog log; + private IMetaDataCalculator metaDataCalculator; + private IBaseVersionCalculator baseVersionCalculator; + private IMainlineVersionCalculator mainlineVersionCalculator; - public VersionSourceTests() + [SetUp] + public void SetUp() { log = new NullLog(); + metaDataCalculator = new MetaDataCalculator(); + baseVersionCalculator = new TestBaseVersionStrategiesCalculator(log); + mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); } [Test] @@ -32,8 +40,8 @@ public void VersionSourceSha() Commands.Checkout(fixture.Repository, featureBranch); _ = fixture.Repository.MakeACommit(); - var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Head, config); - var nextVersionCalculator = new NextVersionCalculator(log); + var context = new GitVersionContext(fixture.Repository, log, fixture.Repository.Head, config); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); var version = nextVersionCalculator.FindVersion(context); version.BuildMetaData.VersionSourceSha.ShouldBe(initialCommit.Sha); @@ -49,7 +57,7 @@ public void VersionSourceShaOneCommit() var initialCommit = fixture.Repository.MakeACommit(); var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Head, config); - var nextVersionCalculator = new NextVersionCalculator(log); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); var version = nextVersionCalculator.FindVersion(context); version.BuildMetaData.VersionSourceSha.ShouldBe(initialCommit.Sha); @@ -71,7 +79,7 @@ public void VersionSourceShaUsingTag() _ = fixture.Repository.MakeACommit(); var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Head, config); - var nextVersionCalculator = new NextVersionCalculator(log); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); var version = nextVersionCalculator.FindVersion(context); version.BuildMetaData.VersionSourceSha.ShouldBe(secondCommit.Sha); diff --git a/src/GitVersionCore.Tests/WixFileTests.cs b/src/GitVersionCore.Tests/WixFileTests.cs index a878ab0c9f..c55cb7c958 100644 --- a/src/GitVersionCore.Tests/WixFileTests.cs +++ b/src/GitVersionCore.Tests/WixFileTests.cs @@ -1,12 +1,13 @@ using System; using System.IO; using System.Text; -using GitVersion; using GitVersion.OutputVariables; using NUnit.Framework; using Shouldly; using GitVersion.Extensions; using GitVersion.Logging; +using GitVersion; +using GitVersion.VersionCalculation; namespace GitVersionCore.Tests { @@ -42,15 +43,19 @@ public void UpdateWixVersionFile() var config = new TestEffectiveConfiguration(buildMetaDataPadding: 2, legacySemVerPadding: 5); - var variableProvider = new VariableProvider(new NullLog()); - var vars = variableProvider.GetVariablesFor(semVer, config, false); - var stringBuilder = new StringBuilder(); void Action(string s) => stringBuilder.AppendLine(s); var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); + var metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); + var vars = variableProvider.GetVariablesFor(semVer, config, false); + using var wixVersionFileUpdater = new WixVersionFileUpdater(workingDir, vars, fileSystem, log); wixVersionFileUpdater.Update(); fileSystem.ReadAllText(wixVersionFileUpdater.WixVersionFile). diff --git a/src/GitVersionCore/Arguments.cs b/src/GitVersionCore/Arguments.cs index b69dd0f273..d133662160 100644 --- a/src/GitVersionCore/Arguments.cs +++ b/src/GitVersionCore/Arguments.cs @@ -7,15 +7,6 @@ namespace GitVersion { public class Arguments { - public Arguments() - { - Authentication = new Authentication(); - OverrideConfig = new Config(); - Output = OutputType.Json; - UpdateAssemblyInfoFileName = new HashSet(); - Verbosity = Verbosity.Normal; - } - public Authentication Authentication; public Config OverrideConfig; @@ -36,17 +27,11 @@ public Arguments() public string LogFilePath; public string ShowVariable; - public OutputType Output; - public string Proj; public string ProjArgs; public string Exec; public string ExecArgs; - public bool UpdateAssemblyInfo; - public ISet UpdateAssemblyInfoFileName; - public bool EnsureAssemblyInfo; - public bool UpdateWixVersionFile; public bool ShowConfig; @@ -54,8 +39,12 @@ public Arguments() public bool NoCache; public bool NoNormalize; - public Verbosity Verbosity; + public OutputType Output = OutputType.Json; + public Verbosity Verbosity = Verbosity.Normal; + public bool UpdateAssemblyInfo; + public ISet UpdateAssemblyInfoFileName = new HashSet(); + public bool EnsureAssemblyInfo; public void AddAssemblyInfoFileName(string fileName) { UpdateAssemblyInfoFileName.Add(fileName); diff --git a/src/GitVersionCore/Authentication.cs b/src/GitVersionCore/Authentication.cs index 56fc67e148..843af3b8da 100644 --- a/src/GitVersionCore/Authentication.cs +++ b/src/GitVersionCore/Authentication.cs @@ -1,13 +1,11 @@ -using System; - namespace GitVersion { public class Authentication { public Authentication() { - Username = Environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); - Password = Environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); + Username = System.Environment.GetEnvironmentVariable("GITVERSION_REMOTE_USERNAME"); + Password = System.Environment.GetEnvironmentVariable("GITVERSION_REMOTE_PASSWORD"); } public string Username; public string Password; diff --git a/src/GitVersionCore/BuildServers/AppVeyor.cs b/src/GitVersionCore/BuildServers/AppVeyor.cs index 68876cd452..245e2ffa54 100644 --- a/src/GitVersionCore/BuildServers/AppVeyor.cs +++ b/src/GitVersionCore/BuildServers/AppVeyor.cs @@ -1,7 +1,6 @@ using System.Net; using System.Text; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers diff --git a/src/GitVersionCore/BuildServers/AzurePipelines.cs b/src/GitVersionCore/BuildServers/AzurePipelines.cs index 9ddd816feb..c2ed0c9fc0 100644 --- a/src/GitVersionCore/BuildServers/AzurePipelines.cs +++ b/src/GitVersionCore/BuildServers/AzurePipelines.cs @@ -2,9 +2,8 @@ using System.Linq; using System.Text.RegularExpressions; using GitVersion.OutputVariables; -using GitVersion.Helpers; -using GitVersion.Common; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersion.BuildServers { diff --git a/src/GitVersionCore/BuildServers/BuildServerList.cs b/src/GitVersionCore/BuildServers/BuildServerList.cs deleted file mode 100644 index 552e3e5f26..0000000000 --- a/src/GitVersionCore/BuildServers/BuildServerList.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Collections.Generic; -using GitVersion.Common; -using GitVersion.Logging; - -namespace GitVersion.BuildServers -{ - public static class BuildServerList - { - private static List supportedBuildServers; - - public static IEnumerable GetApplicableBuildServers(ILog log) - { - var buildServices = new List(); - - foreach (var buildServer in supportedBuildServers) - { - try - { - if (buildServer.CanApplyToCurrentContext()) - { - log.Info($"Applicable build agent found: '{buildServer.GetType().Name}'."); - buildServices.Add(buildServer); - } - } - catch (Exception ex) - { - log.Warning($"Failed to check build server '{buildServer.GetType().Name}': {ex.Message}"); - } - } - - return buildServices; - } - - public static void Init(IEnvironment environment, ILog log) - { - supportedBuildServers = new List - { - new ContinuaCi(environment, log), - new TeamCity(environment, log), - new AppVeyor(environment, log), - new MyGet(environment, log), - new Jenkins(environment, log), - new GitLabCi(environment, log), - new AzurePipelines(environment, log), - new TravisCI(environment, log), - new EnvRun(environment, log), - new Drone(environment, log), - new CodeBuild(environment, log) - }; - } - } -} diff --git a/src/GitVersionCore/BuildServers/CodeBuild.cs b/src/GitVersionCore/BuildServers/CodeBuild.cs index 88fd422e19..4f3471210d 100644 --- a/src/GitVersionCore/BuildServers/CodeBuild.cs +++ b/src/GitVersionCore/BuildServers/CodeBuild.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using GitVersion.Common; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; using GitVersion.Logging; diff --git a/src/GitVersionCore/BuildServers/ContinuaCi.cs b/src/GitVersionCore/BuildServers/ContinuaCi.cs index 2fe99be160..b2bf5033a2 100644 --- a/src/GitVersionCore/BuildServers/ContinuaCi.cs +++ b/src/GitVersionCore/BuildServers/ContinuaCi.cs @@ -1,5 +1,4 @@ using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers diff --git a/src/GitVersionCore/BuildServers/Drone.cs b/src/GitVersionCore/BuildServers/Drone.cs index 82f9f1c733..f833547dd0 100644 --- a/src/GitVersionCore/BuildServers/Drone.cs +++ b/src/GitVersionCore/BuildServers/Drone.cs @@ -1,6 +1,5 @@ using System; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers diff --git a/src/GitVersionCore/BuildServers/EnvRun.cs b/src/GitVersionCore/BuildServers/EnvRun.cs index 740d62bb81..4f4f21b218 100644 --- a/src/GitVersionCore/BuildServers/EnvRun.cs +++ b/src/GitVersionCore/BuildServers/EnvRun.cs @@ -1,6 +1,5 @@ using System.IO; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers @@ -15,7 +14,7 @@ public EnvRun(IEnvironment environment, ILog log) : base(environment, log) protected override string EnvironmentVariable { get; } = EnvironmentVariableName; public override bool CanApplyToCurrentContext() { - string envRunDatabasePath = Environment.GetEnvironmentVariable(EnvironmentVariableName); + var envRunDatabasePath = Environment.GetEnvironmentVariable(EnvironmentVariableName); if (!string.IsNullOrEmpty(envRunDatabasePath)) { if (!File.Exists(envRunDatabasePath)) diff --git a/src/GitVersionCore/BuildServers/GitLabCi.cs b/src/GitVersionCore/BuildServers/GitLabCi.cs index 5f1d347e2d..5c8c3c8b9a 100755 --- a/src/GitVersionCore/BuildServers/GitLabCi.cs +++ b/src/GitVersionCore/BuildServers/GitLabCi.cs @@ -2,7 +2,6 @@ using System.IO; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers @@ -10,11 +9,11 @@ namespace GitVersion.BuildServers public class GitLabCi : BuildServerBase { public const string EnvironmentVariableName = "GITLAB_CI"; - private string _file; + private readonly string file; public GitLabCi(IEnvironment environment, ILog log, string propertiesFileName = "gitversion.properties") : base(environment, log) { - _file = propertiesFileName; + file = propertiesFileName; } protected override string EnvironmentVariable { get; } = EnvironmentVariableName; @@ -43,13 +42,13 @@ public override string GetCurrentBranch(bool usingDynamicRepos) public override void WriteIntegration(Action writer, VersionVariables variables) { base.WriteIntegration(writer, variables); - writer($"Outputting variables to '{_file}' ... "); + writer($"Outputting variables to '{file}' ... "); WriteVariablesFile(variables); } private void WriteVariablesFile(VersionVariables variables) { - File.WriteAllLines(_file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables)); + File.WriteAllLines(file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables)); } } } diff --git a/src/GitVersionCore/BuildServers/Jenkins.cs b/src/GitVersionCore/BuildServers/Jenkins.cs index 47474d660e..fe819d21d6 100644 --- a/src/GitVersionCore/BuildServers/Jenkins.cs +++ b/src/GitVersionCore/BuildServers/Jenkins.cs @@ -2,7 +2,6 @@ using System.IO; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers @@ -10,12 +9,12 @@ namespace GitVersion.BuildServers public class Jenkins : BuildServerBase { public const string EnvironmentVariableName = "JENKINS_URL"; - private string _file; + private readonly string file; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; public Jenkins(IEnvironment environment, ILog log, string propertiesFileName = "gitversion.properties") : base(environment, log) { - _file = propertiesFileName; + file = propertiesFileName; } public override string GenerateSetVersionMessage(VersionVariables variables) @@ -58,13 +57,13 @@ public override bool ShouldCleanUpRemotes() public override void WriteIntegration(Action writer, VersionVariables variables) { base.WriteIntegration(writer, variables); - writer($"Outputting variables to '{_file}' ... "); + writer($"Outputting variables to '{file}' ... "); WriteVariablesFile(variables); } private void WriteVariablesFile(VersionVariables variables) { - File.WriteAllLines(_file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables)); + File.WriteAllLines(file, BuildOutputFormatter.GenerateBuildLogOutput(this, variables)); } } } diff --git a/src/GitVersionCore/BuildServers/MyGet.cs b/src/GitVersionCore/BuildServers/MyGet.cs index 4400fb2191..e0cae6f9d1 100644 --- a/src/GitVersionCore/BuildServers/MyGet.cs +++ b/src/GitVersionCore/BuildServers/MyGet.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using GitVersion.Helpers; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers diff --git a/src/GitVersionCore/BuildServers/TeamCity.cs b/src/GitVersionCore/BuildServers/TeamCity.cs index a67fae1987..99fd50bfa9 100644 --- a/src/GitVersionCore/BuildServers/TeamCity.cs +++ b/src/GitVersionCore/BuildServers/TeamCity.cs @@ -1,6 +1,5 @@ using GitVersion.Helpers; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers diff --git a/src/GitVersionCore/BuildServers/TravisCI.cs b/src/GitVersionCore/BuildServers/TravisCI.cs index c2b6a7f4db..cb86ad427c 100644 --- a/src/GitVersionCore/BuildServers/TravisCI.cs +++ b/src/GitVersionCore/BuildServers/TravisCI.cs @@ -1,12 +1,11 @@ using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.BuildServers { - public class TravisCI : BuildServerBase + public class TravisCi : BuildServerBase { - public TravisCI(IEnvironment environment, ILog log) : base(environment, log) + public TravisCi(IEnvironment environment, ILog log) : base(environment, log) { } diff --git a/src/GitVersionCore/Cache/GitVersionCache.cs b/src/GitVersionCore/Cache/GitVersionCache.cs index cd95a3e6ce..4bb175e039 100644 --- a/src/GitVersionCore/Cache/GitVersionCache.cs +++ b/src/GitVersionCore/Cache/GitVersionCache.cs @@ -5,23 +5,22 @@ using GitVersion.Helpers; using GitVersion.OutputVariables; using YamlDotNet.Serialization; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Cache { - public class GitVersionCache + public class GitVersionCache : IGitVersionCache { private readonly IFileSystem fileSystem; private readonly ILog log; public GitVersionCache(IFileSystem fileSystem, ILog log) { - this.fileSystem = fileSystem; - this.log = log; + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); } - public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache) + public void WriteVariablesToDiskCache(IGitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache) { var cacheDir = PrepareCacheDirectory(gitPreparer); var cacheFileName = GetCacheFileName(cacheKey, cacheDir); @@ -36,16 +35,12 @@ public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKe void WriteCacheOperation() { - using (var stream = fileSystem.OpenWrite(cacheFileName)) + using var stream = fileSystem.OpenWrite(cacheFileName); + using var sw = new StreamWriter(stream); + using (log.IndentLog("Storing version variables to cache file " + cacheFileName)) { - using (var sw = new StreamWriter(stream)) - { - using (log.IndentLog("Storing version variables to cache file " + cacheFileName)) - { - var serializer = new Serializer(); - serializer.Serialize(sw, dictionary); - } - } + var serializer = new Serializer(); + serializer.Serialize(sw, dictionary); } } @@ -53,24 +48,14 @@ void WriteCacheOperation() retryOperation.ExecuteAsync().Wait(); } - public static string GetCacheDirectory(GitPreparer gitPreparer) + public string GetCacheDirectory(IGitPreparer gitPreparer) { var gitDir = gitPreparer.GetDotGitDirectory(); var cacheDir = Path.Combine(gitDir, "gitversion_cache"); return cacheDir; } - private string PrepareCacheDirectory(GitPreparer gitPreparer) - { - var cacheDir = GetCacheDirectory(gitPreparer); - - // If the cacheDir already exists, CreateDirectory just won't do anything (it won't fail). @asbjornu - fileSystem.CreateDirectory(cacheDir); - - return cacheDir; - } - - public VersionVariables LoadVersionVariablesFromDiskCache(GitPreparer gitPreparer, GitVersionCacheKey key) + public VersionVariables LoadVersionVariablesFromDiskCache(IGitPreparer gitPreparer, GitVersionCacheKey key) { using (log.IndentLog("Loading version variables from disk cache")) { @@ -109,6 +94,16 @@ public VersionVariables LoadVersionVariablesFromDiskCache(GitPreparer gitPrepare } } + private string PrepareCacheDirectory(IGitPreparer gitPreparer) + { + var cacheDir = GetCacheDirectory(gitPreparer); + + // If the cacheDir already exists, CreateDirectory just won't do anything (it won't fail). @asbjornu + fileSystem.CreateDirectory(cacheDir); + + return cacheDir; + } + private static string GetCacheFileName(GitVersionCacheKey key, string cacheDir) { return Path.Combine(cacheDir, string.Concat(key.Value, ".yml")); diff --git a/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs b/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs index 4347189c0a..7f5b7d0781 100644 --- a/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs +++ b/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs @@ -5,14 +5,13 @@ using System.Security.Cryptography; using System.Text; using GitVersion.Configuration; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Cache { internal class GitVersionCacheKeyFactory { - public static GitVersionCacheKey Create(IFileSystem fileSystem, ILog log, GitPreparer gitPreparer, Config overrideConfig, IConfigFileLocator configFileLocator) + public static GitVersionCacheKey Create(IFileSystem fileSystem, ILog log, IGitPreparer gitPreparer, IConfigFileLocator configFileLocator, Config overrideConfig) { var gitSystemHash = GetGitSystemHash(gitPreparer, log); var configFileHash = GetConfigFileHash(fileSystem, gitPreparer, configFileLocator); @@ -23,7 +22,7 @@ public static GitVersionCacheKey Create(IFileSystem fileSystem, ILog log, GitPre return new GitVersionCacheKey(compositeHash); } - private static string GetGitSystemHash(GitPreparer gitPreparer, ILog log) + private static string GetGitSystemHash(IGitPreparer gitPreparer, ILog log) { var dotGitDirectory = gitPreparer.GetDotGitDirectory(); @@ -51,7 +50,7 @@ private static List CalculateDirectoryContents(ILog log, string root) while (dirs.Any()) { - string currentDir = dirs.Pop(); + var currentDir = dirs.Pop(); var di = new DirectoryInfo(currentDir); result.Add(di.Name); @@ -123,7 +122,7 @@ private static List CalculateDirectoryContents(ILog log, string root) return result; } - private static string GetRepositorySnapshotHash(GitPreparer gitPreparer) + private static string GetRepositorySnapshotHash(IGitPreparer gitPreparer) { var repositorySnapshot = gitPreparer.WithRepository(repo => { var head = repo.Head; @@ -157,7 +156,7 @@ private static string GetOverrideConfigHash(Config overrideConfig) return GetHash(configContent); } - private static string GetConfigFileHash(IFileSystem fileSystem, GitPreparer gitPreparer, IConfigFileLocator configFileLocator) + private static string GetConfigFileHash(IFileSystem fileSystem, IGitPreparer gitPreparer, IConfigFileLocator configFileLocator) { // will return the same hash even when config file will be moved // from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same. @@ -184,13 +183,11 @@ private static string GetHash(string textToHash) return string.Empty; } - using (var sha1 = SHA1.Create()) - { - var bytes = Encoding.UTF8.GetBytes(textToHash); - var hashedBytes = sha1.ComputeHash(bytes); - var hashedString = BitConverter.ToString(hashedBytes); - return hashedString.Replace("-", ""); - } + using var sha1 = SHA1.Create(); + var bytes = Encoding.UTF8.GetBytes(textToHash); + var hashedBytes = sha1.ComputeHash(bytes); + var hashedString = BitConverter.ToString(hashedBytes); + return hashedString.Replace("-", ""); } } } diff --git a/src/GitVersionCore/Cache/IGitVersionCache.cs b/src/GitVersionCore/Cache/IGitVersionCache.cs new file mode 100644 index 0000000000..58b4092207 --- /dev/null +++ b/src/GitVersionCore/Cache/IGitVersionCache.cs @@ -0,0 +1,11 @@ +using GitVersion.OutputVariables; + +namespace GitVersion.Cache +{ + public interface IGitVersionCache + { + void WriteVariablesToDiskCache(IGitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache); + string GetCacheDirectory(IGitPreparer gitPreparer); + VersionVariables LoadVersionVariablesFromDiskCache(IGitPreparer gitPreparer, GitVersionCacheKey key); + } +} \ No newline at end of file diff --git a/src/GitVersionCore/Common/BuildServerBase.cs b/src/GitVersionCore/Common/BuildServerBase.cs index e0d42bcc1c..bc0de6bba8 100644 --- a/src/GitVersionCore/Common/BuildServerBase.cs +++ b/src/GitVersionCore/Common/BuildServerBase.cs @@ -3,7 +3,7 @@ using GitVersion.OutputFormatters; using GitVersion.OutputVariables; -namespace GitVersion.Common +namespace GitVersion { public abstract class BuildServerBase : IBuildServer { diff --git a/src/GitVersionCore/Common/BuildServerResolver.cs b/src/GitVersionCore/Common/BuildServerResolver.cs new file mode 100644 index 0000000000..84c94b6d1c --- /dev/null +++ b/src/GitVersionCore/Common/BuildServerResolver.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using GitVersion.Logging; + +namespace GitVersion +{ + public class BuildServerResolver : IBuildServerResolver + { + private readonly IEnumerable buildServers; + private readonly ILog log; + public BuildServerResolver(IEnumerable buildServers, ILog log) + { + this.log = log; + this.buildServers = buildServers ?? Array.Empty(); + } + + public IBuildServer Resolve() + { + IBuildServer instance = null; + foreach (var buildServer in buildServers) + { + try + { + if (buildServer.CanApplyToCurrentContext()) + { + log.Info($"Applicable build agent found: '{buildServer.GetType().Name}'."); + instance = buildServer; + } + } + catch (Exception ex) + { + log.Warning($"Failed to check build server '{buildServer.GetType().Name}': {ex.Message}"); + } + } + + return instance; + } + } +} diff --git a/src/GitVersionCore/Common/Environment.cs b/src/GitVersionCore/Common/Environment.cs index 22ec8a8f66..0eb30eccc0 100644 --- a/src/GitVersionCore/Common/Environment.cs +++ b/src/GitVersionCore/Common/Environment.cs @@ -1,4 +1,4 @@ -namespace GitVersion.Common +namespace GitVersion { public class Environment : IEnvironment { diff --git a/src/GitVersionCore/Common/FileSystem.cs b/src/GitVersionCore/Common/FileSystem.cs index 80398e6bce..c07838bc0b 100644 --- a/src/GitVersionCore/Common/FileSystem.cs +++ b/src/GitVersionCore/Common/FileSystem.cs @@ -4,7 +4,7 @@ using System.Text; using GitVersion.Helpers; -namespace GitVersion.Common +namespace GitVersion { public class FileSystem : IFileSystem { @@ -86,7 +86,7 @@ public bool PathsEqual(string path, string otherPath) return string.Equals( Path.GetFullPath(path).TrimEnd('\\').TrimEnd('/'), Path.GetFullPath(otherPath).TrimEnd('\\').TrimEnd('/'), - StringComparerUtils.OSDependentComparison); + StringComparerUtils.OsDependentComparison); } } } diff --git a/src/GitVersionCore/Common/IBuildServer.cs b/src/GitVersionCore/Common/IBuildServer.cs index 5779def450..b1726a061c 100644 --- a/src/GitVersionCore/Common/IBuildServer.cs +++ b/src/GitVersionCore/Common/IBuildServer.cs @@ -1,7 +1,7 @@ using System; using GitVersion.OutputVariables; -namespace GitVersion.Common +namespace GitVersion { public interface IBuildServer { diff --git a/src/GitVersionCore/Common/IBuildServerResolver.cs b/src/GitVersionCore/Common/IBuildServerResolver.cs new file mode 100644 index 0000000000..19e0cafd92 --- /dev/null +++ b/src/GitVersionCore/Common/IBuildServerResolver.cs @@ -0,0 +1,7 @@ +namespace GitVersion +{ + public interface IBuildServerResolver + { + IBuildServer Resolve(); + } +} diff --git a/src/GitVersionCore/Common/IEnvironment.cs b/src/GitVersionCore/Common/IEnvironment.cs index 53d1951c76..efa0114a8b 100644 --- a/src/GitVersionCore/Common/IEnvironment.cs +++ b/src/GitVersionCore/Common/IEnvironment.cs @@ -1,4 +1,4 @@ -namespace GitVersion.Common +namespace GitVersion { public interface IEnvironment { diff --git a/src/GitVersionCore/Common/IFileSystem.cs b/src/GitVersionCore/Common/IFileSystem.cs index 39411828e6..55dd3e0b5c 100644 --- a/src/GitVersionCore/Common/IFileSystem.cs +++ b/src/GitVersionCore/Common/IFileSystem.cs @@ -2,7 +2,7 @@ using System.IO; using System.Text; -namespace GitVersion.Common +namespace GitVersion { public interface IFileSystem { diff --git a/src/GitVersionCore/Common/IGitVersionModule.cs b/src/GitVersionCore/Common/IGitVersionModule.cs new file mode 100644 index 0000000000..dfe04fc69b --- /dev/null +++ b/src/GitVersionCore/Common/IGitVersionModule.cs @@ -0,0 +1,9 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace GitVersion +{ + public interface IGitVersionModule + { + void RegisterTypes(IServiceCollection services); + } +} diff --git a/src/GitVersionCore/Common/IThreadSleep.cs b/src/GitVersionCore/Common/IThreadSleep.cs index 9b97afd5c7..4c01898f32 100644 --- a/src/GitVersionCore/Common/IThreadSleep.cs +++ b/src/GitVersionCore/Common/IThreadSleep.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -namespace GitVersion.Common +namespace GitVersion { public interface IThreadSleep { diff --git a/src/GitVersionCore/Common/ThreadSleep.cs b/src/GitVersionCore/Common/ThreadSleep.cs index 7d2954a374..b2f7e68bce 100644 --- a/src/GitVersionCore/Common/ThreadSleep.cs +++ b/src/GitVersionCore/Common/ThreadSleep.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -namespace GitVersion.Common +namespace GitVersion { internal class ThreadSleep : IThreadSleep { diff --git a/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs b/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs index 60b95319e5..c4b02de1b6 100644 --- a/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs +++ b/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs @@ -2,21 +2,21 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using GitVersion.Helpers; using GitVersion.Logging; using LibGit2Sharp; +using GitVersion.Extensions; namespace GitVersion.Configuration { public class BranchConfigurationCalculator : IBranchConfigurationCalculator { public static string FallbackConfigName = "Fallback"; - private GitVersionContext context; - private ILog log; + private readonly GitVersionContext context; + private readonly ILog log; public BranchConfigurationCalculator(ILog log, GitVersionContext context) { - this.log = log; + this.log = log ?? throw new ArgumentNullException(nameof(log)); this.context = context; } @@ -32,7 +32,7 @@ public BranchConfig GetBranchConfiguration(Branch targetBranch, IList ex log.Info($"No branch configuration found for branch {targetBranch.FriendlyName}, falling back to default configuration"); matchingBranches = new BranchConfig { Name = FallbackConfigName }; - ConfigurationProvider.ApplyBranchDefaults(context.FullConfiguration, matchingBranches, "", new List()); + context.FullConfiguration.ApplyBranchDefaults(matchingBranches, "", new List()); } if (matchingBranches.Increment == IncrementStrategy.Inherit) @@ -132,8 +132,8 @@ private BranchConfig InheritBranchConfiguration(Branch targetBranch, BranchConfi else errorMessage = "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName)); - var developBranchRegex = config.Branches[ConfigurationProvider.DevelopBranchKey].Regex; - var masterBranchRegex = config.Branches[ConfigurationProvider.MasterBranchKey].Regex; + var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex; + var masterBranchRegex = config.Branches[Config.MasterBranchKey].Regex; var chosenBranch = repository.Branches.FirstOrDefault(b => Regex.IsMatch(b.FriendlyName, developBranchRegex, RegexOptions.IgnoreCase) || Regex.IsMatch(b.FriendlyName, masterBranchRegex, RegexOptions.IgnoreCase)); @@ -145,12 +145,12 @@ private BranchConfig InheritBranchConfiguration(Branch targetBranch, BranchConfi } var branchName = chosenBranch.FriendlyName; - log.Warning(errorMessage + Environment.NewLine + Environment.NewLine + "Falling back to " + branchName + " branch config"); + log.Warning(errorMessage + System.Environment.NewLine + System.Environment.NewLine + "Falling back to " + branchName + " branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.IsSameBranch(chosenBranch)) { - BranchConfig developOrMasterConfig = + var developOrMasterConfig = ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem( chosenBranch, branchConfiguration, config); if (developOrMasterConfig != null) @@ -220,32 +220,32 @@ private Branch[] CalculateWhenMultipleParents(IRepository repository, Commit cur return excludedBranches; } - private static BranchConfig ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(Branch ChosenBranch, BranchConfig BranchConfiguration, Config config) + private static BranchConfig ChooseMasterOrDevelopIncrementStrategyIfTheChosenBranchIsOneOfThem(Branch chosenBranch, BranchConfig branchConfiguration, Config config) { BranchConfig masterOrDevelopConfig = null; - var developBranchRegex = config.Branches[ConfigurationProvider.DevelopBranchKey].Regex; - var masterBranchRegex = config.Branches[ConfigurationProvider.MasterBranchKey].Regex; - if (Regex.IsMatch(ChosenBranch.FriendlyName, developBranchRegex, RegexOptions.IgnoreCase)) + var developBranchRegex = config.Branches[Config.DevelopBranchKey].Regex; + var masterBranchRegex = config.Branches[Config.MasterBranchKey].Regex; + if (Regex.IsMatch(chosenBranch.FriendlyName, developBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check - if (config.Branches[ConfigurationProvider.DevelopBranchKey].Increment != + if (config.Branches[Config.DevelopBranchKey].Increment != IncrementStrategy.Inherit) { - masterOrDevelopConfig = new BranchConfig(BranchConfiguration) + masterOrDevelopConfig = new BranchConfig(branchConfiguration) { - Increment = config.Branches[ConfigurationProvider.DevelopBranchKey].Increment + Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } - else if (Regex.IsMatch(ChosenBranch.FriendlyName, masterBranchRegex, RegexOptions.IgnoreCase)) + else if (Regex.IsMatch(chosenBranch.FriendlyName, masterBranchRegex, RegexOptions.IgnoreCase)) { // Normally we would not expect this to happen but for safety we add a check - if (config.Branches[ConfigurationProvider.MasterBranchKey].Increment != + if (config.Branches[Config.MasterBranchKey].Increment != IncrementStrategy.Inherit) { - masterOrDevelopConfig = new BranchConfig(BranchConfiguration) + masterOrDevelopConfig = new BranchConfig(branchConfiguration) { - Increment = config.Branches[ConfigurationProvider.DevelopBranchKey].Increment + Increment = config.Branches[Config.DevelopBranchKey].Increment }; } } diff --git a/src/GitVersionCore/Configuration/Config.cs b/src/GitVersionCore/Configuration/Config.cs index 145515ed9f..41c235501e 100644 --- a/src/GitVersionCore/Configuration/Config.cs +++ b/src/GitVersionCore/Configuration/Config.cs @@ -2,16 +2,17 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text.RegularExpressions; using GitVersion.VersioningModes; using YamlDotNet.Serialization; using GitVersion.Extensions; +using System.IO; +using System.Text; namespace GitVersion.Configuration { public class Config { - private Dictionary branches = new Dictionary(); + private readonly Dictionary branches = new Dictionary(); private string nextVersion; public Config() @@ -48,7 +49,7 @@ public string NextVersion { get => nextVersion; set => - nextVersion = int.TryParse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var major) + nextVersion = Int32.TryParse(value, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var major) ? $"{major}.0" : value; } @@ -93,35 +94,6 @@ public Dictionary Branches } } - public BranchConfig GetConfigForBranch(string branchName) - { - if (branchName == null) throw new ArgumentNullException(nameof(branchName)); - var matches = Branches - .Where(b => Regex.IsMatch(branchName, b.Value.Regex, RegexOptions.IgnoreCase)) - .ToArray(); - - try - { - return matches - .Select(kvp => kvp.Value) - .SingleOrDefault(); - } - catch (InvalidOperationException) - { - var matchingConfigs = string.Join("\n - ", matches.Select(m => m.Key)); - var picked = matches - .Select(kvp => kvp.Value) - .First(); - - // TODO check how to log this - Console.WriteLine( - $"Multiple branch configurations match the current branch branchName of '{branchName}'. " + - $"Using the first matching configuration, '{picked}'. Matching configurations include: '{matchingConfigs}'"); - - return picked; - } - } - private static T MergeObjects(T target, T source) { typeof(T).GetProperties() @@ -133,8 +105,6 @@ private static T MergeObjects(T target, T source) return target; } - public bool IsReleaseBranch(string branchName) => GetConfigForBranch(branchName)?.IsReleaseBranch ?? false; - [YamlMember(Alias = "ignore")] public IgnoreConfig Ignore { get; set; } @@ -146,5 +116,32 @@ private static T MergeObjects(T target, T source) [YamlMember(Alias = "merge-message-formats")] public Dictionary MergeMessageFormats { get; set; } = new Dictionary(); + + public override string ToString() + { + var stringBuilder = new StringBuilder(); + using (var stream = new StringWriter(stringBuilder)) + { + ConfigSerialiser.Write(this, stream); + stream.Flush(); + } + return stringBuilder.ToString(); + } + + public const string DefaultTagPrefix = "[vV]"; + public const string ReleaseBranchRegex = "^releases?[/-]"; + public const string FeatureBranchRegex = "^features?[/-]"; + public const string PullRequestRegex = @"^(pull|pull\-requests|pr)[/-]"; + public const string HotfixBranchRegex = "^hotfix(es)?[/-]"; + public const string SupportBranchRegex = "^support[/-]"; + public const string DevelopBranchRegex = "^dev(elop)?(ment)?$"; + public const string MasterBranchRegex = "^master$"; + public const string MasterBranchKey = "master"; + public const string ReleaseBranchKey = "release"; + public const string FeatureBranchKey = "feature"; + public const string PullRequestBranchKey = "pull-request"; + public const string HotfixBranchKey = "hotfix"; + public const string SupportBranchKey = "support"; + public const string DevelopBranchKey = "develop"; } } diff --git a/src/GitVersionCore/Configuration/ConfigExtensions.cs b/src/GitVersionCore/Configuration/ConfigExtensions.cs new file mode 100644 index 0000000000..2bffb54f41 --- /dev/null +++ b/src/GitVersionCore/Configuration/ConfigExtensions.cs @@ -0,0 +1,214 @@ +using System.Collections.Generic; +using System.Linq; +using GitVersion.Extensions; +using GitVersion.VersioningModes; +using System; +using System.Text.RegularExpressions; + +namespace GitVersion.Configuration +{ + public static class ConfigExtensions + { + public static void Reset(this Config config) + { + config.AssemblyVersioningScheme ??= AssemblyVersioningScheme.MajorMinorPatch; + config.AssemblyFileVersioningScheme ??= AssemblyFileVersioningScheme.MajorMinorPatch; + config.AssemblyInformationalFormat = config.AssemblyInformationalFormat; + config.AssemblyVersioningFormat = config.AssemblyVersioningFormat; + config.AssemblyFileVersioningFormat = config.AssemblyFileVersioningFormat; + config.TagPrefix ??= Config.DefaultTagPrefix; + config.VersioningMode ??= VersioningMode.ContinuousDelivery; + config.ContinuousDeploymentFallbackTag ??= "ci"; + config.MajorVersionBumpMessage ??= IncrementStrategyFinder.DefaultMajorPattern; + config.MinorVersionBumpMessage ??= IncrementStrategyFinder.DefaultMinorPattern; + config.PatchVersionBumpMessage ??= IncrementStrategyFinder.DefaultPatchPattern; + config.NoBumpMessage ??= IncrementStrategyFinder.DefaultNoBumpPattern; + config.CommitMessageIncrementing ??= CommitMessageIncrementMode.Enabled; + config.LegacySemVerPadding ??= 4; + config.BuildMetaDataPadding ??= 4; + config.CommitsSinceVersionSourcePadding ??= 4; + config.CommitDateFormat ??= "yyyy-MM-dd"; + + var configBranches = config.Branches.ToList(); + + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.DevelopBranchKey), Config.DevelopBranchRegex, + new List(), + defaultTag: "alpha", + defaultIncrementStrategy: IncrementStrategy.Minor, + defaultVersioningMode: config.VersioningMode == VersioningMode.Mainline ? VersioningMode.Mainline : VersioningMode.ContinuousDeployment, + defaultTrackMergeTarget: true, + tracksReleaseBranches: true); + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.MasterBranchKey), Config.MasterBranchRegex, + new List + { "develop", "release" }, + defaultTag: string.Empty, + defaultPreventIncrement: true, + defaultIncrementStrategy: IncrementStrategy.Patch, + isMainline: true); + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.ReleaseBranchKey), Config.ReleaseBranchRegex, + new List + { "develop", "master", "support", "release" }, + defaultTag: "beta", + defaultPreventIncrement: true, + defaultIncrementStrategy: IncrementStrategy.Patch, + isReleaseBranch: true); + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.FeatureBranchKey), Config.FeatureBranchRegex, + new List + { "develop", "master", "release", "feature", "support", "hotfix" }, + defaultIncrementStrategy: IncrementStrategy.Inherit); + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.PullRequestBranchKey), Config.PullRequestRegex, + new List + { "develop", "master", "release", "feature", "support", "hotfix" }, + defaultTag: "PullRequest", + defaultTagNumberPattern: @"[/-](?\d+)", + defaultIncrementStrategy: IncrementStrategy.Inherit); + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.HotfixBranchKey), Config.HotfixBranchRegex, + new List + { "develop", "master", "support" }, + defaultTag: "beta", + defaultIncrementStrategy: IncrementStrategy.Patch); + ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.SupportBranchKey), Config.SupportBranchRegex, + new List + { "master" }, + defaultTag: string.Empty, + defaultPreventIncrement: true, + defaultIncrementStrategy: IncrementStrategy.Patch, + isMainline: true); + + // Any user defined branches should have other values defaulted after known branches filled in. + // This allows users to override any of the value. + foreach (var branchConfig in configBranches) + { + var regex = branchConfig.Value.Regex; + if (regex == null) + { + throw new GitVersionConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'regex'\n\n" + + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); + } + + var sourceBranches = branchConfig.Value.SourceBranches; + if (sourceBranches == null) + { + throw new GitVersionConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'source-branches'\n\n" + + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); + } + + ApplyBranchDefaults(config, branchConfig.Value, regex, sourceBranches); + } + + // This is a second pass to add additional sources, it has to be another pass to prevent ordering issues + foreach (var branchConfig in configBranches) + { + if (branchConfig.Value.IsSourceBranchFor == null) continue; + foreach (var isSourceBranch in branchConfig.Value.IsSourceBranchFor) + { + config.Branches[isSourceBranch].SourceBranches.Add(branchConfig.Key); + } + } + } + + private static readonly Dictionary DefaultPreReleaseWeight = + new Dictionary + { + { Config.DevelopBranchRegex, 0 }, + { Config.HotfixBranchRegex, 30000 }, + { Config.ReleaseBranchRegex, 30000 }, + { Config.FeatureBranchRegex, 30000 }, + { Config.PullRequestRegex, 30000 }, + { Config.SupportBranchRegex, 55000 }, + { Config.MasterBranchRegex, 55000 } + }; + private const IncrementStrategy DefaultIncrementStrategy = IncrementStrategy.Inherit; + + public static void ApplyBranchDefaults(this Config config, + BranchConfig branchConfig, + string branchRegex, + List sourceBranches, + string defaultTag = "useBranchName", + IncrementStrategy? defaultIncrementStrategy = null, // Looked up from main config + bool defaultPreventIncrement = false, + VersioningMode? defaultVersioningMode = null, // Looked up from main config + bool defaultTrackMergeTarget = false, + string defaultTagNumberPattern = null, + bool tracksReleaseBranches = false, + bool isReleaseBranch = false, + bool isMainline = false) + { + branchConfig.Regex = string.IsNullOrEmpty(branchConfig.Regex) ? branchRegex : branchConfig.Regex; + branchConfig.SourceBranches = branchConfig.SourceBranches == null || !branchConfig.SourceBranches.Any() + ? sourceBranches : branchConfig.SourceBranches; + branchConfig.Tag ??= defaultTag; + branchConfig.TagNumberPattern ??= defaultTagNumberPattern; + branchConfig.Increment ??= defaultIncrementStrategy ?? config.Increment ?? DefaultIncrementStrategy; + branchConfig.PreventIncrementOfMergedBranchVersion ??= defaultPreventIncrement; + branchConfig.TrackMergeTarget ??= defaultTrackMergeTarget; + branchConfig.VersioningMode ??= defaultVersioningMode ?? config.VersioningMode; + branchConfig.TracksReleaseBranches ??= tracksReleaseBranches; + branchConfig.IsReleaseBranch ??= isReleaseBranch; + branchConfig.IsMainline ??= isMainline; + DefaultPreReleaseWeight.TryGetValue(branchRegex, out var defaultPreReleaseNumber); + branchConfig.PreReleaseWeight ??= defaultPreReleaseNumber; + } + + public static void Verify(this Config readConfig) + { + // Verify no branches are set to mainline mode + if (readConfig.Branches.Any(b => b.Value.VersioningMode == VersioningMode.Mainline)) + { + throw new GitVersionConfigurationException(@"Mainline mode only works at the repository level, a single branch cannot be put into mainline mode + +This is because mainline mode treats your entire git repository as an event source with each merge into the 'mainline' incrementing the version. + +If the docs do not help you decide on the mode open an issue to discuss what you are trying to do."); + } + } + + public static void ApplyOverridesTo(this Config config, Config overrideConfig) + { + config.TagPrefix = string.IsNullOrWhiteSpace(overrideConfig.TagPrefix) ? config.TagPrefix : overrideConfig.TagPrefix; + } + + public static BranchConfig GetConfigForBranch(this Config config, string branchName) + { + if (branchName == null) throw new ArgumentNullException(nameof(branchName)); + var matches = config.Branches + .Where(b => Regex.IsMatch(branchName, b.Value.Regex, RegexOptions.IgnoreCase)) + .ToArray(); + + try + { + return matches + .Select(kvp => kvp.Value) + .SingleOrDefault(); + } + catch (InvalidOperationException) + { + var matchingConfigs = String.Join("\n - ", matches.Select(m => m.Key)); + var picked = matches + .Select(kvp => kvp.Value) + .First(); + + // TODO check how to log this + Console.WriteLine( + $"Multiple branch configurations match the current branch branchName of '{branchName}'. " + + $"Using the first matching configuration, '{picked}'. Matching configurations include: '{matchingConfigs}'"); + + return picked; + } + } + + public static bool IsReleaseBranch(this Config config, string branchName) => config.GetConfigForBranch(branchName)?.IsReleaseBranch ?? false; + + private static BranchConfig GetOrCreateBranchDefaults(this Config config, string branchKey) + { + if (!config.Branches.ContainsKey(branchKey)) + { + var branchConfig = new BranchConfig { Name = branchKey }; + config.Branches.Add(branchKey, branchConfig); + return branchConfig; + } + + return config.Branches[branchKey]; + } + } +} diff --git a/src/GitVersionCore/Configuration/ConfigFileLocator.cs b/src/GitVersionCore/Configuration/ConfigFileLocator.cs index af00ea9764..7b87ca966c 100644 --- a/src/GitVersionCore/Configuration/ConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/ConfigFileLocator.cs @@ -1,5 +1,5 @@ +using System; using System.IO; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration @@ -11,8 +11,8 @@ public abstract class ConfigFileLocator : IConfigFileLocator protected ConfigFileLocator(IFileSystem fileSystem, ILog log) { - FileSystem = fileSystem; - Log = log; + FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + Log = log ?? throw new ArgumentNullException(nameof(log)); } public abstract bool HasConfigFileAt(string workingDirectory); @@ -21,7 +21,7 @@ protected ConfigFileLocator(IFileSystem fileSystem, ILog log) public abstract void Verify(string workingDirectory, string projectRootDirectory); - public string SelectConfigFilePath(GitPreparer gitPreparer) + public string SelectConfigFilePath(IGitPreparer gitPreparer) { var workingDirectory = gitPreparer.WorkingDirectory; var projectRootDirectory = gitPreparer.GetProjectRootDirectory(); @@ -48,7 +48,7 @@ public Config ReadConfig(string workingDirectory) return new Config(); } - public void Verify(GitPreparer gitPreparer) + public void Verify(IGitPreparer gitPreparer) { if (!string.IsNullOrWhiteSpace(gitPreparer.TargetUrl)) { diff --git a/src/GitVersionCore/Configuration/ConfigFileLocatorFactory.cs b/src/GitVersionCore/Configuration/ConfigFileLocatorFactory.cs new file mode 100644 index 0000000000..8e4de34465 --- /dev/null +++ b/src/GitVersionCore/Configuration/ConfigFileLocatorFactory.cs @@ -0,0 +1,27 @@ +using System; +using GitVersion.Logging; +using Microsoft.Extensions.Options; + +namespace GitVersion.Configuration +{ + public class ConfigFileLocatorFactory : IConfigFileLocatorFactory + { + private readonly IFileSystem fileSystem; + private readonly ILog log; + private readonly IOptions options; + + public ConfigFileLocatorFactory(IFileSystem fileSystem, ILog log, IOptions options) + { + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.options = options ?? throw new ArgumentNullException(nameof(fileSystem)); + } + + public IConfigFileLocator Create() + { + return string.IsNullOrWhiteSpace(options.Value.ConfigFile) + ? new DefaultConfigFileLocator(fileSystem, log) as IConfigFileLocator + : new NamedConfigFileLocator(fileSystem, log, options); + } + } +} \ No newline at end of file diff --git a/src/GitVersionCore/Configuration/ConfigProvider.cs b/src/GitVersionCore/Configuration/ConfigProvider.cs new file mode 100644 index 0000000000..7a2be130e6 --- /dev/null +++ b/src/GitVersionCore/Configuration/ConfigProvider.cs @@ -0,0 +1,59 @@ +using System; +using System.IO; +using GitVersion.Configuration.Init.Wizard; +using GitVersion.Logging; + +namespace GitVersion.Configuration +{ + public class ConfigProvider : IConfigProvider + { + private readonly IFileSystem fileSystem; + private readonly ILog log; + private readonly IConfigFileLocator configFileLocator; + private readonly IGitPreparer gitPreparer; + private readonly IConfigInitWizard configInitWizard; + + public ConfigProvider(IFileSystem fileSystem, ILog log, IConfigFileLocator configFileLocator, IGitPreparer gitPreparer, IConfigInitWizard configInitWizard) + { + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.configFileLocator = configFileLocator ?? throw new ArgumentNullException(nameof(configFileLocator)); + this.gitPreparer = gitPreparer ?? throw new ArgumentNullException(nameof(gitPreparer)); + this.configInitWizard = configInitWizard ?? throw new ArgumentNullException(nameof(this.configInitWizard)); + } + + public Config Provide(bool applyDefaults = true, Config overrideConfig = null) + { + var workingDirectory = gitPreparer.WorkingDirectory; + var projectRootDirectory = gitPreparer.GetProjectRootDirectory(); + + var rootDirectory = configFileLocator.HasConfigFileAt(workingDirectory) ? workingDirectory : projectRootDirectory; + return Provide(rootDirectory, applyDefaults, overrideConfig); + } + + public Config Provide(string workingDirectory, bool applyDefaults = true, Config overrideConfig = null) + { + var readConfig = configFileLocator.ReadConfig(workingDirectory); + readConfig.Verify(); + + if (applyDefaults) readConfig.Reset(); + if (null != overrideConfig) readConfig.ApplyOverridesTo(overrideConfig); + return readConfig; + } + + public void Init(string workingDirectory) + { + var configFilePath = configFileLocator.GetConfigFilePath(workingDirectory); + var currentConfiguration = Provide(workingDirectory, false); + + var config = configInitWizard.Run(currentConfiguration, workingDirectory); + if (config == null) return; + + using var stream = fileSystem.OpenWrite(configFilePath); + using var writer = new StreamWriter(stream); + log.Info("Saving config file"); + ConfigSerialiser.Write(config, writer); + stream.Flush(); + } + } +} diff --git a/src/GitVersionCore/Configuration/ConfigurationProvider.cs b/src/GitVersionCore/Configuration/ConfigurationProvider.cs deleted file mode 100644 index b4a16b7794..0000000000 --- a/src/GitVersionCore/Configuration/ConfigurationProvider.cs +++ /dev/null @@ -1,265 +0,0 @@ -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using GitVersion.Configuration.Init.Wizard; -using GitVersion.VersioningModes; -using GitVersion.Extensions; -using GitVersion.Common; -using GitVersion.Logging; - -namespace GitVersion.Configuration -{ - public class ConfigurationProvider - { - internal const string DefaultTagPrefix = "[vV]"; - - public const string ReleaseBranchRegex = "^releases?[/-]"; - public const string FeatureBranchRegex = "^features?[/-]"; - public const string PullRequestRegex = @"^(pull|pull\-requests|pr)[/-]"; - public const string HotfixBranchRegex = "^hotfix(es)?[/-]"; - public const string SupportBranchRegex = "^support[/-]"; - public const string DevelopBranchRegex = "^dev(elop)?(ment)?$"; - public const string MasterBranchRegex = "^master$"; - public const string MasterBranchKey = "master"; - public const string ReleaseBranchKey = "release"; - public const string FeatureBranchKey = "feature"; - public const string PullRequestBranchKey = "pull-request"; - public const string HotfixBranchKey = "hotfix"; - public const string SupportBranchKey = "support"; - public const string DevelopBranchKey = "develop"; - - private static Dictionary DefaultPreReleaseWeight = - new Dictionary - { - { DevelopBranchRegex, 0 }, - { HotfixBranchRegex, 30000 }, - { ReleaseBranchRegex, 30000 }, - { FeatureBranchRegex, 30000 }, - { PullRequestRegex, 30000 }, - { SupportBranchRegex, 55000 }, - { MasterBranchRegex, 55000 } - }; - - private const IncrementStrategy DefaultIncrementStrategy = IncrementStrategy.Inherit; - - public static Config Provide(GitPreparer gitPreparer, IConfigFileLocator configFileLocator, bool applyDefaults = true, Config overrideConfig = null) - { - var workingDirectory = gitPreparer.WorkingDirectory; - var projectRootDirectory = gitPreparer.GetProjectRootDirectory(); - - if (configFileLocator.HasConfigFileAt(workingDirectory)) - { - return Provide(workingDirectory, configFileLocator, applyDefaults, overrideConfig); - } - - return Provide(projectRootDirectory, configFileLocator, applyDefaults, overrideConfig); - } - - public static Config Provide(string workingDirectory, IConfigFileLocator configFileLocator, bool applyDefaults = true, Config overrideConfig = null) - { - var readConfig = configFileLocator.ReadConfig(workingDirectory); - VerifyConfiguration(readConfig); - - if (applyDefaults) - ApplyDefaultsTo(readConfig); - if (null != overrideConfig) - ApplyOverridesTo(readConfig, overrideConfig); - return readConfig; - } - - private static void VerifyConfiguration(Config readConfig) - { - // Verify no branches are set to mainline mode - if (readConfig.Branches.Any(b => b.Value.VersioningMode == VersioningMode.Mainline)) - { - throw new GitVersionConfigurationException(@"Mainline mode only works at the repository level, a single branch cannot be put into mainline mode - -This is because mainline mode treats your entire git repository as an event source with each merge into the 'mainline' incrementing the version. - -If the docs do not help you decide on the mode open an issue to discuss what you are trying to do."); - } - } - - public static void ApplyDefaultsTo(Config config) - { - config.AssemblyVersioningScheme = config.AssemblyVersioningScheme ?? AssemblyVersioningScheme.MajorMinorPatch; - config.AssemblyFileVersioningScheme = config.AssemblyFileVersioningScheme ?? AssemblyFileVersioningScheme.MajorMinorPatch; - config.AssemblyInformationalFormat = config.AssemblyInformationalFormat; - config.AssemblyVersioningFormat = config.AssemblyVersioningFormat; - config.AssemblyFileVersioningFormat = config.AssemblyFileVersioningFormat; - config.TagPrefix = config.TagPrefix ?? DefaultTagPrefix; - config.VersioningMode = config.VersioningMode ?? VersioningMode.ContinuousDelivery; - config.ContinuousDeploymentFallbackTag = config.ContinuousDeploymentFallbackTag ?? "ci"; - config.MajorVersionBumpMessage = config.MajorVersionBumpMessage ?? IncrementStrategyFinder.DefaultMajorPattern; - config.MinorVersionBumpMessage = config.MinorVersionBumpMessage ?? IncrementStrategyFinder.DefaultMinorPattern; - config.PatchVersionBumpMessage = config.PatchVersionBumpMessage ?? IncrementStrategyFinder.DefaultPatchPattern; - config.NoBumpMessage = config.NoBumpMessage ?? IncrementStrategyFinder.DefaultNoBumpPattern; - config.CommitMessageIncrementing = config.CommitMessageIncrementing ?? CommitMessageIncrementMode.Enabled; - config.LegacySemVerPadding = config.LegacySemVerPadding ?? 4; - config.BuildMetaDataPadding = config.BuildMetaDataPadding ?? 4; - config.CommitsSinceVersionSourcePadding = config.CommitsSinceVersionSourcePadding ?? 4; - config.CommitDateFormat = config.CommitDateFormat ?? "yyyy-MM-dd"; - - var configBranches = config.Branches.ToList(); - - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, DevelopBranchKey), - DevelopBranchRegex, - new List(), - defaultTag: "alpha", - defaultIncrementStrategy: IncrementStrategy.Minor, - defaultVersioningMode: config.VersioningMode == VersioningMode.Mainline ? VersioningMode.Mainline : VersioningMode.ContinuousDeployment, - defaultTrackMergeTarget: true, - tracksReleaseBranches: true); - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, MasterBranchKey), - MasterBranchRegex, - new List { "develop", "release" }, - defaultTag: string.Empty, - defaultPreventIncrement: true, - defaultIncrementStrategy: IncrementStrategy.Patch, - isMainline: true); - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, ReleaseBranchKey), - ReleaseBranchRegex, - new List { "develop", "master", "support", "release" }, - defaultTag: "beta", - defaultPreventIncrement: true, - defaultIncrementStrategy: IncrementStrategy.Patch, - isReleaseBranch: true); - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, FeatureBranchKey), - FeatureBranchRegex, - new List { "develop", "master", "release", "feature", "support", "hotfix" }, - defaultIncrementStrategy: IncrementStrategy.Inherit); - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, PullRequestBranchKey), - PullRequestRegex, - new List { "develop", "master", "release", "feature", "support", "hotfix" }, - defaultTag: "PullRequest", - defaultTagNumberPattern: @"[/-](?\d+)", - defaultIncrementStrategy: IncrementStrategy.Inherit); - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, HotfixBranchKey), - HotfixBranchRegex, - new List { "develop", "master", "support" }, - defaultTag: "beta", - defaultIncrementStrategy: IncrementStrategy.Patch); - ApplyBranchDefaults(config, - GetOrCreateBranchDefaults(config, SupportBranchKey), - SupportBranchRegex, - new List { "master" }, - defaultTag: string.Empty, - defaultPreventIncrement: true, - defaultIncrementStrategy: IncrementStrategy.Patch, - isMainline: true); - - // Any user defined branches should have other values defaulted after known branches filled in. - // This allows users to override any of the value. - foreach (var branchConfig in configBranches) - { - var regex = branchConfig.Value.Regex; - if (regex == null) - { - throw new GitVersionConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'regex'\n\n" + - "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); - } - - var sourceBranches = branchConfig.Value.SourceBranches; - if (sourceBranches == null) - { - throw new GitVersionConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'source-branches'\n\n" + - "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); - } - - ApplyBranchDefaults(config, branchConfig.Value, regex, sourceBranches); - } - - // This is a second pass to add additional sources, it has to be another pass to prevent ordering issues - foreach (var branchConfig in configBranches) - { - if (branchConfig.Value.IsSourceBranchFor == null) continue; - foreach (var isSourceBranch in branchConfig.Value.IsSourceBranchFor) - { - config.Branches[isSourceBranch].SourceBranches.Add(branchConfig.Key); - } - } - } - - private static void ApplyOverridesTo(Config config, Config overrideConfig) - { - config.TagPrefix = string.IsNullOrWhiteSpace(overrideConfig.TagPrefix) ? config.TagPrefix : overrideConfig.TagPrefix; - } - - private static BranchConfig GetOrCreateBranchDefaults(Config config, string branchKey) - { - if (!config.Branches.ContainsKey(branchKey)) - { - var branchConfig = new BranchConfig { Name = branchKey }; - config.Branches.Add(branchKey, branchConfig); - return branchConfig; - } - - return config.Branches[branchKey]; - } - - public static void ApplyBranchDefaults(Config config, - BranchConfig branchConfig, - string branchRegex, - List sourceBranches, - string defaultTag = "useBranchName", - IncrementStrategy? defaultIncrementStrategy = null, // Looked up from main config - bool defaultPreventIncrement = false, - VersioningMode? defaultVersioningMode = null, // Looked up from main config - bool defaultTrackMergeTarget = false, - string defaultTagNumberPattern = null, - bool tracksReleaseBranches = false, - bool isReleaseBranch = false, - bool isMainline = false) - { - branchConfig.Regex = string.IsNullOrEmpty(branchConfig.Regex) ? branchRegex : branchConfig.Regex; - branchConfig.SourceBranches = branchConfig.SourceBranches == null || !branchConfig.SourceBranches.Any() - ? sourceBranches : branchConfig.SourceBranches; - branchConfig.Tag = branchConfig.Tag ?? defaultTag; - branchConfig.TagNumberPattern = branchConfig.TagNumberPattern ?? defaultTagNumberPattern; - branchConfig.Increment = branchConfig.Increment ?? defaultIncrementStrategy ?? config.Increment ?? DefaultIncrementStrategy; - branchConfig.PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion ?? defaultPreventIncrement; - branchConfig.TrackMergeTarget = branchConfig.TrackMergeTarget ?? defaultTrackMergeTarget; - branchConfig.VersioningMode = branchConfig.VersioningMode ?? defaultVersioningMode ?? config.VersioningMode; - branchConfig.TracksReleaseBranches = branchConfig.TracksReleaseBranches ?? tracksReleaseBranches; - branchConfig.IsReleaseBranch = branchConfig.IsReleaseBranch ?? isReleaseBranch; - branchConfig.IsMainline = branchConfig.IsMainline ?? isMainline; - DefaultPreReleaseWeight.TryGetValue(branchRegex, out var defaultPreReleaseNumber); - branchConfig.PreReleaseWeight = branchConfig.PreReleaseWeight ?? defaultPreReleaseNumber; - } - - public static string GetEffectiveConfigAsString(string workingDirectory, IConfigFileLocator configFileLocator) - { - var config = Provide(workingDirectory, configFileLocator); - var stringBuilder = new StringBuilder(); - using (var stream = new StringWriter(stringBuilder)) - { - ConfigSerialiser.Write(config, stream); - stream.Flush(); - } - return stringBuilder.ToString(); - } - - public static void Init(string workingDirectory, IFileSystem fileSystem, IConsole console, ILog log, IConfigFileLocator configFileLocator) - { - var configFilePath = configFileLocator.GetConfigFilePath(workingDirectory); - var currentConfiguration = Provide(workingDirectory, applyDefaults: false, configFileLocator: configFileLocator); - var config = new ConfigInitWizard(console, fileSystem, log).Run(currentConfiguration, workingDirectory); - if (config == null) return; - - using (var stream = fileSystem.OpenWrite(configFilePath)) - using (var writer = new StreamWriter(stream)) - { - log.Info("Saving config file"); - ConfigSerialiser.Write(config, writer); - stream.Flush(); - } - } - } -} diff --git a/src/GitVersionCore/Configuration/DefaultConfigFileLocator.cs b/src/GitVersionCore/Configuration/DefaultConfigFileLocator.cs index 694a4a81f3..221eae847e 100644 --- a/src/GitVersionCore/Configuration/DefaultConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/DefaultConfigFileLocator.cs @@ -1,6 +1,5 @@ using System.IO; using GitVersion.Exceptions; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration @@ -69,8 +68,8 @@ private void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, stri var workingConfigFile = GetConfigFilePath(workingDirectory); var projectRootConfigFile = GetConfigFilePath(projectRootDirectory); - bool hasConfigInWorkingDirectory = FileSystem.Exists(workingConfigFile); - bool hasConfigInProjectRootDirectory = FileSystem.Exists(projectRootConfigFile); + var hasConfigInWorkingDirectory = FileSystem.Exists(workingConfigFile); + var hasConfigInProjectRootDirectory = FileSystem.Exists(projectRootConfigFile); if (hasConfigInProjectRootDirectory && hasConfigInWorkingDirectory) { throw new WarningException($"Ambiguous config file selection from '{workingConfigFile}' and '{projectRootConfigFile}'"); diff --git a/src/GitVersionCore/Configuration/IConfigFileLocator.cs b/src/GitVersionCore/Configuration/IConfigFileLocator.cs index 333d1a617c..1eafec7143 100644 --- a/src/GitVersionCore/Configuration/IConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/IConfigFileLocator.cs @@ -5,8 +5,8 @@ public interface IConfigFileLocator bool HasConfigFileAt(string workingDirectory); string GetConfigFilePath(string workingDirectory); void Verify(string workingDirectory, string projectRootDirectory); - string SelectConfigFilePath(GitPreparer gitPreparer); + string SelectConfigFilePath(IGitPreparer gitPreparer); Config ReadConfig(string workingDirectory); - void Verify(GitPreparer gitPreparer); + void Verify(IGitPreparer gitPreparer); } } diff --git a/src/GitVersionCore/Configuration/IConfigFileLocatorFactory.cs b/src/GitVersionCore/Configuration/IConfigFileLocatorFactory.cs new file mode 100644 index 0000000000..09a3bd4ccc --- /dev/null +++ b/src/GitVersionCore/Configuration/IConfigFileLocatorFactory.cs @@ -0,0 +1,7 @@ +namespace GitVersion.Configuration +{ + public interface IConfigFileLocatorFactory + { + IConfigFileLocator Create(); + } +} \ No newline at end of file diff --git a/src/GitVersionCore/Configuration/IConfigProvider.cs b/src/GitVersionCore/Configuration/IConfigProvider.cs new file mode 100644 index 0000000000..382bc4ecbc --- /dev/null +++ b/src/GitVersionCore/Configuration/IConfigProvider.cs @@ -0,0 +1,9 @@ +namespace GitVersion.Configuration +{ + public interface IConfigProvider + { + Config Provide(bool applyDefaults = true, Config overrideConfig = null); + Config Provide(string workingDirectory, bool applyDefaults = true, Config overrideConfig = null); + void Init(string workingDirectory); + } +} diff --git a/src/GitVersionCore/Configuration/IgnoreConfig.cs b/src/GitVersionCore/Configuration/IgnoreConfig.cs index 11783ff745..c3103d98e8 100644 --- a/src/GitVersionCore/Configuration/IgnoreConfig.cs +++ b/src/GitVersionCore/Configuration/IgnoreConfig.cs @@ -10,18 +10,18 @@ public class IgnoreConfig { public IgnoreConfig() { - SHAs = Enumerable.Empty(); + ShAs = Enumerable.Empty(); } [YamlMember(Alias = "commits-before")] public DateTimeOffset? Before { get; set; } [YamlMember(Alias = "sha")] - public IEnumerable SHAs { get; set; } + public IEnumerable ShAs { get; set; } public virtual IEnumerable ToFilters() { - if (SHAs.Any()) yield return new ShaVersionFilter(SHAs); + if (ShAs.Any()) yield return new ShaVersionFilter(ShAs); if (Before.HasValue) yield return new MinDateVersionFilter(Before.Value); } } diff --git a/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs b/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs index c43bd0a80b..8c5f5a57c0 100644 --- a/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs +++ b/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs @@ -3,7 +3,6 @@ using System.IO; using System.Text; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.BuildServer @@ -16,45 +15,46 @@ internal enum ProjectVisibility internal class AppVeyorSetup : ConfigInitWizardStep { - private readonly ILog log; - private ProjectVisibility _projectVisibility; + private ProjectVisibility projectVisibility; - public AppVeyorSetup(IConsole console, IFileSystem fileSystem, ILog log, ProjectVisibility visibility) : base(console, fileSystem, log) + public AppVeyorSetup(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { - this.log = log; - _projectVisibility = visibility; + } + + public AppVeyorSetup WithData(ProjectVisibility visibility) + { + projectVisibility = visibility; + return this; } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) { + var editConfigStep = StepFactory.CreateStep(); switch (result) { case "0": - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "1": GenerateBasicConfig(workingDirectory); - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "2": GenerateNuGetConfig(workingDirectory); - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); } return StepResult.InvalidResponseSelected(); } - private static string GetGVCommand(ProjectVisibility visibility) + private static string GetGvCommand(ProjectVisibility visibility) { - switch (visibility) + return visibility switch { - case ProjectVisibility.Public: - return " - ps: gitversion /l console /output buildserver /updateAssemblyInfo"; - case ProjectVisibility.Private: - return " - ps: gitversion $env:APPVEYOR_BUILD_FOLDER /l console /output buildserver /updateAssemblyInfo /nofetch /b $env:APPVEYOR_REPO_BRANCH"; - default: - return ""; - } + ProjectVisibility.Public => " - ps: gitversion /l console /output buildserver /updateAssemblyInfo", + ProjectVisibility.Private => " - ps: gitversion $env:APPVEYOR_BUILD_FOLDER /l console /output buildserver /updateAssemblyInfo /nofetch /b $env:APPVEYOR_REPO_BRANCH", + _ => "" + }; } private void GenerateBasicConfig(string workingDirectory) @@ -64,7 +64,7 @@ private void GenerateBasicConfig(string workingDirectory) before_build: - nuget restore -{GetGVCommand(_projectVisibility)} +{GetGvCommand(projectVisibility)} build: project: "); @@ -80,7 +80,7 @@ private void GenerateNuGetConfig(string workingDirectory) before_build: - nuget restore -{GetGVCommand(_projectVisibility)} +{GetGvCommand(projectVisibility)} build: project: @@ -95,7 +95,7 @@ private void WriteConfig(string workingDirectory, IFileSystem fileSystem, string { var outputFilename = GetOutputFilename(workingDirectory, fileSystem); fileSystem.WriteAllText(outputFilename, configContents); - log.Info($"AppVeyor sample config file written to {outputFilename}"); + Log.Info($"AppVeyor sample config file written to {outputFilename}"); } protected override string GetPrompt(Config config, string workingDirectory) diff --git a/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs b/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs index 6603490437..c64feedb53 100644 --- a/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs +++ b/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs @@ -1,14 +1,12 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.BuildServer { internal class AppveyorPublicPrivate : ConfigInitWizardStep { - - public AppveyorPublicPrivate(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public AppveyorPublicPrivate(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -17,13 +15,13 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); case "1": - steps.Enqueue(new AppVeyorSetup(Console, FileSystem, Log, ProjectVisibility.Public)); + steps.Enqueue(StepFactory.CreateStep().WithData(ProjectVisibility.Public)); return StepResult.Ok(); case "2": - steps.Enqueue(new AppVeyorSetup(Console, FileSystem, Log, ProjectVisibility.Private)); + steps.Enqueue(StepFactory.CreateStep().WithData(ProjectVisibility.Private)); return StepResult.Ok(); } return StepResult.Ok(); diff --git a/src/GitVersionCore/Configuration/Init/BuildServer/SetupBuildScripts.cs b/src/GitVersionCore/Configuration/Init/BuildServer/SetupBuildScripts.cs index 5ae2ca9e19..3e6eacb55b 100644 --- a/src/GitVersionCore/Configuration/Init/BuildServer/SetupBuildScripts.cs +++ b/src/GitVersionCore/Configuration/Init/BuildServer/SetupBuildScripts.cs @@ -1,13 +1,12 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.BuildServer { internal class SetupBuildScripts : ConfigInitWizardStep { - public SetupBuildScripts(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public SetupBuildScripts(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -16,10 +15,10 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); case "1": - steps.Enqueue(new AppveyorPublicPrivate(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); } return StepResult.Ok(); diff --git a/src/GitVersionCore/Configuration/Init/EditConfigStep.cs b/src/GitVersionCore/Configuration/Init/EditConfigStep.cs index 7ad2f618e1..71969b8905 100644 --- a/src/GitVersionCore/Configuration/Init/EditConfigStep.cs +++ b/src/GitVersionCore/Configuration/Init/EditConfigStep.cs @@ -2,14 +2,13 @@ using GitVersion.Configuration.Init.BuildServer; using GitVersion.Configuration.Init.SetConfig; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init { public class EditConfigStep : ConfigInitWizardStep { - public EditConfigStep(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public EditConfigStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -23,24 +22,25 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); case "3": - steps.Enqueue(new SetNextVersion(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); case "4": - steps.Enqueue(new ConfigureBranches(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); case "5": - steps.Enqueue(new GlobalModeSetting(new EditConfigStep(Console, FileSystem, Log), false, Console, FileSystem, Log)); + var editConfigStep = StepFactory.CreateStep(); + steps.Enqueue(StepFactory.CreateStep().WithData(editConfigStep, false)); return StepResult.Ok(); case "6": - steps.Enqueue(new AssemblyVersioningSchemeSetting(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); case "7": - steps.Enqueue(new SetupBuildScripts(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); } return StepResult.InvalidResponseSelected(); diff --git a/src/GitVersionCore/Configuration/Init/GitVersionInitModule.cs b/src/GitVersionCore/Configuration/Init/GitVersionInitModule.cs new file mode 100644 index 0000000000..8e0206f416 --- /dev/null +++ b/src/GitVersionCore/Configuration/Init/GitVersionInitModule.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using GitVersion.Configuration.Init.Wizard; +using Microsoft.Extensions.DependencyInjection; + +namespace GitVersion.Configuration.Init +{ + public class GitVersionInitModule : IGitVersionModule + { + public void RegisterTypes(IServiceCollection services) + { + services.AddTransient(); + services.AddTransient(); + + var steps = FindAllDerivedTypes(Assembly.GetAssembly(GetType())); + + foreach (var step in steps) + { + services.AddTransient(step); + } + } + + private static IEnumerable FindAllDerivedTypes(Assembly assembly) + { + var derivedType = typeof(T); + return assembly.GetTypes().Where(t => t != derivedType && derivedType.IsAssignableFrom(t)); + } + } +} diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs b/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs index 0b07ff62e4..42dc08eb2d 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs @@ -1,43 +1,43 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.Extensions; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { public class AssemblyVersioningSchemeSetting : ConfigInitWizardStep { - public AssemblyVersioningSchemeSetting(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public AssemblyVersioningSchemeSetting(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) { + var editConfigStep = StepFactory.CreateStep(); switch (result) { case "0": - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "1": config.AssemblyVersioningScheme = AssemblyVersioningScheme.Major; - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "2": config.AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinor; - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "3": config.AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch; - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "4": config.AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatchTag; - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); case "5": config.AssemblyVersioningScheme = AssemblyVersioningScheme.None; - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); } diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs index dba713e924..3c182554d5 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig @@ -8,13 +7,17 @@ namespace GitVersion.Configuration.Init.SetConfig public class ConfigureBranch : ConfigInitWizardStep { private string name; - private readonly BranchConfig branchConfig; + private BranchConfig branchConfig; - public ConfigureBranch(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem, ILog log) - : base(console, fileSystem, log) + public ConfigureBranch(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) + { + } + + public ConfigureBranch WithData(string name, BranchConfig branchConfig) { this.branchConfig = branchConfig; this.name = name; + return this; } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) @@ -22,13 +25,13 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); case "1": - steps.Enqueue(new SetBranchTag(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep().WithData(name, branchConfig)); return StepResult.Ok(); case "2": - steps.Enqueue(new SetBranchIncrementMode(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep().WithData(name, branchConfig)); return StepResult.Ok(); } diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs index 6a3c48c405..65c59627f0 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs @@ -2,14 +2,13 @@ using System.Collections.Generic; using System.Linq; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { public class ConfigureBranches : ConfigInitWizardStep { - public ConfigureBranches(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public ConfigureBranches(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -19,7 +18,7 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); } @@ -32,7 +31,7 @@ protected override StepResult HandleResult(string result, Queue().WithData(foundBranch.Key, branchConfig)); return StepResult.Ok(); } catch (ArgumentOutOfRangeException) @@ -53,7 +52,7 @@ protected override string GetPrompt(Config config, string workingDirectory) private static IOrderedEnumerable> OrderedBranches(Config config) { var defaultConfig = new Config(); - ConfigurationProvider.ApplyDefaultsTo(defaultConfig); + defaultConfig.Reset(); var defaultConfigurationBranches = defaultConfig.Branches .Where(k => !config.Branches.ContainsKey(k.Key)) // Return an empty branch config diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs b/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs index 1689034a85..39f569370a 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs @@ -1,21 +1,24 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.VersioningModes; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { public class GlobalModeSetting : ConfigInitWizardStep { - private readonly ConfigInitWizardStep returnToStep; - private readonly bool isPartOfWizard; + private ConfigInitWizardStep returnToStep; + private bool isPartOfWizard; - public GlobalModeSetting(ConfigInitWizardStep returnToStep, bool isPartOfWizard, IConsole console, IFileSystem fileSystem, ILog log) - : base(console, fileSystem, log) + protected GlobalModeSetting(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) + { + } + + public GlobalModeSetting WithData(ConfigInitWizardStep returnToStep, bool isPartOfWizard) { this.returnToStep = returnToStep; this.isPartOfWizard = isPartOfWizard; + return this; } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs index 5d29250691..e2dff94c6e 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs @@ -1,37 +1,41 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.VersioningModes; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { public class SetBranchIncrementMode : ConfigInitWizardStep { - private readonly string name; - private readonly BranchConfig branchConfig; + private string name; + private BranchConfig branchConfig; - public SetBranchIncrementMode(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem, ILog log) - : base(console, fileSystem, log) + public SetBranchIncrementMode(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) + { + } + + public SetBranchIncrementMode WithData(string name, BranchConfig branchConfig) { - this.name = name; this.branchConfig = branchConfig; + this.name = name; + return this; } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) { + var configureBranchStep = StepFactory.CreateStep(); switch (result) { case "0": - steps.Enqueue(new ConfigureBranch(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); case "1": branchConfig.VersioningMode = VersioningMode.ContinuousDelivery; - steps.Enqueue(new ConfigureBranch(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); case "2": branchConfig.VersioningMode = VersioningMode.ContinuousDeployment; - steps.Enqueue(new ConfigureBranch(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); } diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs index da48c0b65e..30593bb163 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig @@ -8,13 +7,17 @@ namespace GitVersion.Configuration.Init.SetConfig public class SetBranchTag : ConfigInitWizardStep { private string name; - private readonly BranchConfig branchConfig; + private BranchConfig branchConfig; - public SetBranchTag(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem, ILog log) - : base(console, fileSystem, log) + public SetBranchTag(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) + { + } + + public SetBranchTag WithData(string name, BranchConfig branchConfig) { - this.name = name; this.branchConfig = branchConfig; + this.name = name; + return this; } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) @@ -24,18 +27,19 @@ protected override StepResult HandleResult(string result, Queue(); switch (result) { case "0": - steps.Enqueue(new ConfigureBranch(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); case "1": branchConfig.Tag = string.Empty; - steps.Enqueue(new ConfigureBranch(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); default: branchConfig.Tag = result; - steps.Enqueue(new ConfigureBranch(name, branchConfig, Console, FileSystem, Log)); + steps.Enqueue(configureBranchStep.WithData(name, branchConfig)); return StepResult.Ok(); } } diff --git a/src/GitVersionCore/Configuration/Init/SetNextVersion.cs b/src/GitVersionCore/Configuration/Init/SetNextVersion.cs index d368a1db52..7216e919f6 100644 --- a/src/GitVersionCore/Configuration/Init/SetNextVersion.cs +++ b/src/GitVersionCore/Configuration/Init/SetNextVersion.cs @@ -1,21 +1,21 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init { public class SetNextVersion : ConfigInitWizardStep { - public SetNextVersion(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public SetNextVersion(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) { + var editConfigStep = StepFactory.CreateStep(); if (string.IsNullOrEmpty(result)) { - steps.Enqueue(new EditConfigStep(Console, FileSystem, Log)); + steps.Enqueue(editConfigStep); return StepResult.Ok(); } @@ -23,7 +23,7 @@ protected override StepResult HandleResult(string result, Queue() => sp.GetService(); + } +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs index 5d3ed60310..b7f1bd3950 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs @@ -1,27 +1,24 @@ +using System; using System.Collections.Generic; -using GitVersion.Common; -using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { - public class ConfigInitWizard + public class ConfigInitWizard : IConfigInitWizard { private readonly IConsole console; - private readonly IFileSystem fileSystem; - private readonly ILog log; + private readonly IConfigInitStepFactory stepFactory; - public ConfigInitWizard(IConsole console, IFileSystem fileSystem, ILog log) + public ConfigInitWizard(IConsole console, IConfigInitStepFactory stepFactory) { - this.console = console; - this.fileSystem = fileSystem; - this.log = log; + this.console = console ?? throw new ArgumentNullException(nameof(console)); + this.stepFactory = stepFactory ?? throw new ArgumentNullException(nameof(stepFactory)); } public Config Run(Config config, string workingDirectory) { console.WriteLine("GitVersion init will guide you through setting GitVersion up to work for you"); var steps = new Queue(); - steps.Enqueue(new EditConfigStep(console, fileSystem, log)); + steps.Enqueue(stepFactory.CreateStep()); while (steps.Count > 0) { diff --git a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs index d68496982f..394b12927d 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs @@ -1,25 +1,24 @@ using System; using System.Collections.Generic; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public abstract class ConfigInitWizardStep { + protected readonly IConsole Console; + protected readonly IFileSystem FileSystem; + protected readonly ILog Log; + protected readonly IConfigInitStepFactory StepFactory; - protected ConfigInitWizardStep(IConsole console, IFileSystem fileSystem, ILog log) + protected ConfigInitWizardStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) { - Console = console; - FileSystem = fileSystem; - Log = log; + Console = console ?? throw new ArgumentNullException(nameof(console)); + FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + Log = log ?? throw new ArgumentNullException(nameof(log)); + StepFactory = stepFactory ?? throw new ArgumentNullException(nameof(stepFactory)); } - protected IConsole Console { get; private set; } - - protected IFileSystem FileSystem { get; private set; } - protected ILog Log { get; private set; } - public bool Apply(Queue steps, Config config, string workingDirectory) { Console.WriteLine(); diff --git a/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs index b8e2942361..ceb47047b4 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs @@ -1,11 +1,10 @@ -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class FinishedSetupStep : EditConfigStep { - public FinishedSetupStep(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public FinishedSetupStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } diff --git a/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs index d275c18b86..87b32d23e1 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs @@ -1,12 +1,11 @@ using GitVersion.Configuration.Init.SetConfig; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class GitFlowSetupStep : GlobalModeSetting { - public GitFlowSetupStep(IConsole console, IFileSystem fileSystem, ILog log) : base(new FinishedSetupStep(console, fileSystem, log), true, console, fileSystem, log) + public GitFlowSetupStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } diff --git a/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs index 0ffa4490ba..cb09a2464c 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs @@ -1,12 +1,11 @@ using GitVersion.Configuration.Init.SetConfig; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class GitHubFlowStep : GlobalModeSetting { - public GitHubFlowStep(IConsole console, IFileSystem fileSystem, ILog log) : base(new FinishedSetupStep(console, fileSystem, log), true, console, fileSystem, log) + public GitHubFlowStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } diff --git a/src/GitVersionCore/Configuration/Init/Wizard/IConfigInitStepFactory.cs b/src/GitVersionCore/Configuration/Init/Wizard/IConfigInitStepFactory.cs new file mode 100644 index 0000000000..3fdfb52c77 --- /dev/null +++ b/src/GitVersionCore/Configuration/Init/Wizard/IConfigInitStepFactory.cs @@ -0,0 +1,7 @@ +namespace GitVersion.Configuration.Init.Wizard +{ + public interface IConfigInitStepFactory + { + T CreateStep(); + } +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/IConfigInitWizard.cs b/src/GitVersionCore/Configuration/Init/Wizard/IConfigInitWizard.cs new file mode 100644 index 0000000000..feb9364993 --- /dev/null +++ b/src/GitVersionCore/Configuration/Init/Wizard/IConfigInitWizard.cs @@ -0,0 +1,7 @@ +namespace GitVersion.Configuration.Init.Wizard +{ + public interface IConfigInitWizard + { + Config Run(Config config, string workingDirectory); + } +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs index d21d3acd6f..12d4cfb1dd 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class PickBranchingStrategy1Step : ConfigInitWizardStep { - public PickBranchingStrategy1Step(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public PickBranchingStrategy1Step(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -18,10 +17,10 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); case "n": - steps.Enqueue(new PickBranchingStrategy2Step(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); } diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs index 7576c46adc..fb478ca93b 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class PickBranchingStrategy2Step : ConfigInitWizardStep { - public PickBranchingStrategy2Step(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public PickBranchingStrategy2Step(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -21,10 +20,10 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); case "n": - steps.Enqueue(new PickBranchingStrategy3Step(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); return StepResult.Ok(); } diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs index d695a552d4..1cacbe73a7 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class PickBranchingStrategy3Step : ConfigInitWizardStep { - public PickBranchingStrategy3Step(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public PickBranchingStrategy3Step(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } @@ -28,7 +27,7 @@ protected override StepResult HandleResult(string result, Queue()); return StepResult.Ok(); } diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs index f0c99a1588..413319a3ea 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs @@ -1,27 +1,27 @@ using System.Collections.Generic; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class PickBranchingStrategyStep : ConfigInitWizardStep { - public PickBranchingStrategyStep(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) + public PickBranchingStrategyStep(IConsole console, IFileSystem fileSystem, ILog log, IConfigInitStepFactory stepFactory) : base(console, fileSystem, log, stepFactory) { } protected override StepResult HandleResult(string result, Queue steps, Config config, string workingDirectory) { + var returnToStep = StepFactory.CreateStep(); switch (result) { case "1": - steps.Enqueue(new GitFlowSetupStep(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep().WithData(returnToStep, true)); break; case "2": - steps.Enqueue(new GitHubFlowStep(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep().WithData(returnToStep, true)); break; case "3": - steps.Enqueue(new PickBranchingStrategy1Step(Console, FileSystem, Log)); + steps.Enqueue(StepFactory.CreateStep()); break; default: return StepResult.InvalidResponseSelected(); diff --git a/src/GitVersionCore/Configuration/LegacyConfig.cs b/src/GitVersionCore/Configuration/LegacyConfig.cs index bad1932f51..dd48af37aa 100644 --- a/src/GitVersionCore/Configuration/LegacyConfig.cs +++ b/src/GitVersionCore/Configuration/LegacyConfig.cs @@ -9,11 +9,10 @@ namespace GitVersion.Configuration /// public class LegacyConfig { - private Dictionary branches = new Dictionary(); + private readonly Dictionary branches = new Dictionary(); -#pragma warning disable IDE1006 // Naming Styles - public string assemblyVersioningScheme { get; set; } -#pragma warning restore IDE1006 // Naming Styles + [YamlMember(Alias = "assemblyVersioningScheme")] + public string AssemblyVersioningScheme { get; set; } [YamlMember(Alias = "develop-branch-tag")] public string DevelopBranchTag { get; set; } diff --git a/src/GitVersionCore/Configuration/LegacyConfigNotifier.cs b/src/GitVersionCore/Configuration/LegacyConfigNotifier.cs index 1f33529449..4cd8f98275 100644 --- a/src/GitVersionCore/Configuration/LegacyConfigNotifier.cs +++ b/src/GitVersionCore/Configuration/LegacyConfigNotifier.cs @@ -10,18 +10,18 @@ public class LegacyConfigNotifier { private static readonly Dictionary OldConfigKnownRegexes = new Dictionary { - {ConfigurationProvider.MasterBranchRegex, ConfigurationProvider.MasterBranchKey}, - {ConfigurationProvider.DevelopBranchRegex, ConfigurationProvider.DevelopBranchKey}, - {ConfigurationProvider.FeatureBranchRegex, ConfigurationProvider.FeatureBranchKey}, - {ConfigurationProvider.HotfixBranchRegex, ConfigurationProvider.HotfixBranchKey}, - {ConfigurationProvider.ReleaseBranchRegex, ConfigurationProvider.ReleaseBranchKey}, - {ConfigurationProvider.SupportBranchRegex, ConfigurationProvider.SupportBranchKey}, - {ConfigurationProvider.PullRequestRegex, ConfigurationProvider.PullRequestBranchKey}, - {"dev(elop)?(ment)?$", ConfigurationProvider.DevelopBranchKey }, - {"release[/-]", ConfigurationProvider.ReleaseBranchKey }, - {"hotfix[/-]", ConfigurationProvider.HotfixBranchKey }, - {"feature(s)?[/-]", ConfigurationProvider.FeatureBranchKey }, - {"feature[/-]", ConfigurationProvider.FeatureBranchKey } + {Config.MasterBranchRegex, Config.MasterBranchKey}, + {Config.DevelopBranchRegex, Config.DevelopBranchKey}, + {Config.FeatureBranchRegex, Config.FeatureBranchKey}, + {Config.HotfixBranchRegex, Config.HotfixBranchKey}, + {Config.ReleaseBranchRegex, Config.ReleaseBranchKey}, + {Config.SupportBranchRegex, Config.SupportBranchKey}, + {Config.PullRequestRegex, Config.PullRequestBranchKey}, + {"dev(elop)?(ment)?$", Config.DevelopBranchKey }, + {"release[/-]", Config.ReleaseBranchKey }, + {"hotfix[/-]", Config.HotfixBranchKey }, + {"feature(s)?[/-]", Config.FeatureBranchKey }, + {"feature[/-]", Config.FeatureBranchKey } }; public static void Notify(StringReader reader) @@ -44,7 +44,7 @@ public static void Notify(StringReader reader) {branchErrors}"); } - if (legacyConfig.assemblyVersioningScheme != null) + if (legacyConfig.AssemblyVersioningScheme != null) issues.Add("assemblyVersioningScheme has been replaced by assembly-versioning-scheme"); if (legacyConfig.DevelopBranchTag != null) diff --git a/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs b/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs index 3b8ceaf329..abd5748ebf 100644 --- a/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs @@ -1,15 +1,17 @@ using System; using System.IO; -using GitVersion.Common; using GitVersion.Exceptions; using GitVersion.Logging; +using Microsoft.Extensions.Options; namespace GitVersion.Configuration { public class NamedConfigFileLocator : ConfigFileLocator { - public NamedConfigFileLocator(string filePath, IFileSystem fileSystem, ILog log) : base(fileSystem, log) + public NamedConfigFileLocator(IFileSystem fileSystem, ILog log, IOptions options) : base(fileSystem, log) { + var arguments = options.Value; + var filePath = arguments.ConfigFile; if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException(nameof(filePath), "Empty file path provided!"); FilePath = filePath; } diff --git a/src/GitVersionCore/ExecuteCore.cs b/src/GitVersionCore/ExecuteCore.cs deleted file mode 100644 index 5cd3751267..0000000000 --- a/src/GitVersionCore/ExecuteCore.cs +++ /dev/null @@ -1,131 +0,0 @@ -using System; -using System.Linq; -using GitVersion.BuildServers; -using GitVersion.Configuration; -using GitVersion.OutputVariables; -using GitVersion.Cache; -using GitVersion.Common; -using GitVersion.Logging; -using Environment = System.Environment; - -namespace GitVersion -{ - public class ExecuteCore - { - private readonly IFileSystem fileSystem; - private readonly IEnvironment environment; - private readonly ILog log; - private readonly IConfigFileLocator configFileLocator; - private readonly GitVersionCache gitVersionCache; - - public ExecuteCore(IFileSystem fileSystem, IEnvironment environment, ILog log, IConfigFileLocator configFileLocator = null) - { - this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); - this.environment = environment; - this.log = log; - this.configFileLocator = configFileLocator ?? new DefaultConfigFileLocator(fileSystem, log); - gitVersionCache = new GitVersionCache(fileSystem, log); - } - - public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId, Config overrideConfig = null, bool noCache = false, bool noNormalize = false) - { - BuildServerList.Init(environment, log); - - // Normalize if we are running on build server - var applicableBuildServers = BuildServerList.GetApplicableBuildServers(log); - var buildServer = applicableBuildServers.FirstOrDefault(); - var normalizeGitDirectory = !noNormalize && buildServer != null; - var fetch = noFetch || buildServer != null && buildServer.PreventFetch(); - var shouldCleanUpRemotes = buildServer != null && buildServer.ShouldCleanUpRemotes(); - var gitPreparer = new GitPreparer(log, targetUrl, dynamicRepositoryLocation, authentication, fetch, workingDirectory); - - gitPreparer.Initialise(normalizeGitDirectory, ResolveCurrentBranch(buildServer, targetBranch, !string.IsNullOrWhiteSpace(dynamicRepositoryLocation)), shouldCleanUpRemotes); - var dotGitDirectory = gitPreparer.GetDotGitDirectory(); - var projectRoot = gitPreparer.GetProjectRootDirectory(); - - // TODO Can't use this, it still needs work - //var gitRepository = GitRepositoryFactory.CreateRepository(new RepositoryInfo - //{ - // Url = targetUrl, - // Branch = targetBranch, - // Authentication = new AuthenticationInfo - // { - // Username = authentication.Username, - // Password = authentication.Password - // }, - // Directory = workingDirectory - //}); - log.Info($"Project root is: {projectRoot}"); - log.Info($"DotGit directory is: {dotGitDirectory}"); - if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot)) - { - // TODO Link to wiki article - throw new Exception($"Failed to prepare or find the .git directory in path '{workingDirectory}'."); - } - - var cacheKey = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, overrideConfig, configFileLocator); - var versionVariables = noCache ? default : gitVersionCache.LoadVersionVariablesFromDiskCache(gitPreparer, cacheKey); - if (versionVariables == null) - { - versionVariables = ExecuteInternal(targetBranch, commitId, gitPreparer, overrideConfig); - - if (!noCache) - { - try - { - gitVersionCache.WriteVariablesToDiskCache(gitPreparer, cacheKey, versionVariables); - } - catch (AggregateException e) - { - log.Warning($"One or more exceptions during cache write:{Environment.NewLine}{e}"); - } - } - } - - return versionVariables; - } - - public bool TryGetVersion(string directory, out VersionVariables versionVariables, bool noFetch, Authentication authentication) - { - try - { - versionVariables = ExecuteGitVersion(null, null, authentication, null, noFetch, directory, null); - return true; - } - catch (Exception ex) - { - log.Warning("Could not determine assembly version: " + ex); - versionVariables = null; - return false; - } - } - - private string ResolveCurrentBranch(IBuildServer buildServer, string targetBranch, bool isDynamicRepository) - { - if (buildServer == null) - { - return targetBranch; - } - - var currentBranch = buildServer.GetCurrentBranch(isDynamicRepository) ?? targetBranch; - log.Info("Branch from build environment: " + currentBranch); - - return currentBranch; - } - - private VersionVariables ExecuteInternal(string targetBranch, string commitId, GitPreparer gitPreparer, Config overrideConfig = null) - { - var versionFinder = new GitVersionFinder(); - var configuration = ConfigurationProvider.Provide(gitPreparer, overrideConfig: overrideConfig, configFileLocator: configFileLocator); - - return gitPreparer.WithRepository(repo => - { - var gitVersionContext = new GitVersionContext(repo, log, targetBranch, configuration, commitId: commitId); - var semanticVersion = versionFinder.FindVersion(log, gitVersionContext); - - var variableProvider = new VariableProvider(log); - return variableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged); - }); - } - } -} diff --git a/src/GitVersionCore/Extensions/AssemblyVersionsGenerator.cs b/src/GitVersionCore/Extensions/AssemblyVersionsGenerator.cs index f014aca73f..6733a75847 100644 --- a/src/GitVersionCore/Extensions/AssemblyVersionsGenerator.cs +++ b/src/GitVersionCore/Extensions/AssemblyVersionsGenerator.cs @@ -8,42 +8,30 @@ public static string GetAssemblyVersion( this SemanticVersion sv, AssemblyVersioningScheme scheme) { - switch (scheme) + return scheme switch { - case AssemblyVersioningScheme.Major: - return $"{sv.Major}.0.0.0"; - case AssemblyVersioningScheme.MajorMinor: - return $"{sv.Major}.{sv.Minor}.0.0"; - case AssemblyVersioningScheme.MajorMinorPatch: - return $"{sv.Major}.{sv.Minor}.{sv.Patch}.0"; - case AssemblyVersioningScheme.MajorMinorPatchTag: - return $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}"; - case AssemblyVersioningScheme.None: - return null; - default: - throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)); - } + AssemblyVersioningScheme.Major => $"{sv.Major}.0.0.0", + AssemblyVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", + AssemblyVersioningScheme.MajorMinorPatch => $"{sv.Major}.{sv.Minor}.{sv.Patch}.0", + AssemblyVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}", + AssemblyVersioningScheme.None => null, + _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) + }; } public static string GetAssemblyFileVersion( this SemanticVersion sv, AssemblyFileVersioningScheme scheme) { - switch (scheme) + return scheme switch { - case AssemblyFileVersioningScheme.Major: - return $"{sv.Major}.0.0.0"; - case AssemblyFileVersioningScheme.MajorMinor: - return $"{sv.Major}.{sv.Minor}.0.0"; - case AssemblyFileVersioningScheme.MajorMinorPatch: - return $"{sv.Major}.{sv.Minor}.{sv.Patch}.0"; - case AssemblyFileVersioningScheme.MajorMinorPatchTag: - return $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}"; - case AssemblyFileVersioningScheme.None: - return null; - default: - throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)); - } + AssemblyFileVersioningScheme.Major => $"{sv.Major}.0.0.0", + AssemblyFileVersioningScheme.MajorMinor => $"{sv.Major}.{sv.Minor}.0.0", + AssemblyFileVersioningScheme.MajorMinorPatch => $"{sv.Major}.{sv.Minor}.{sv.Patch}.0", + AssemblyFileVersioningScheme.MajorMinorPatchTag => $"{sv.Major}.{sv.Minor}.{sv.Patch}.{sv.PreReleaseTag.Number ?? 0}", + AssemblyFileVersioningScheme.None => null, + _ => throw new ArgumentException($"Unexpected value ({scheme}).", nameof(scheme)) + }; } } } diff --git a/src/GitVersionCore/Extensions/EnumerableExtensions.cs b/src/GitVersionCore/Extensions/EnumerableExtensions.cs new file mode 100644 index 0000000000..f4a0f3b6f6 --- /dev/null +++ b/src/GitVersionCore/Extensions/EnumerableExtensions.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; + +namespace GitVersion.Extensions +{ + public static class EnumerableExtensions + { + public static T OnlyOrDefault(this IEnumerable source) + { + switch (source) + { + case null: + throw new ArgumentNullException(nameof(source)); + case IList list when list.Count == 1: + return list[0]; + } + + using (var e = source.GetEnumerator()) + { + if (!e.MoveNext()) + return default; + var current = e.Current; + if (!e.MoveNext()) + return current; + } + + return default; + } + } +} diff --git a/src/GitVersionCore/Extensions/GitVersionInformationResources/GitVersionInformationGenerator.cs b/src/GitVersionCore/Extensions/GitVersionInformationResources/GitVersionInformationGenerator.cs index 9fbb287685..b01867eec0 100644 --- a/src/GitVersionCore/Extensions/GitVersionInformationResources/GitVersionInformationGenerator.cs +++ b/src/GitVersionCore/Extensions/GitVersionInformationResources/GitVersionInformationGenerator.cs @@ -1,19 +1,17 @@ using System.IO; using System.Linq; using GitVersion.OutputVariables; -using GitVersion.Common; -using Environment = System.Environment; namespace GitVersion.Extensions.GitVersionInformationResources { public class GitVersionInformationGenerator { - private string fileName; - private string directory; - private VersionVariables variables; - private IFileSystem fileSystem; + private readonly string fileName; + private readonly string directory; + private readonly VersionVariables variables; + private readonly IFileSystem fileSystem; - private TemplateManager templateManager; + private readonly TemplateManager templateManager; public GitVersionInformationGenerator(string fileName, string directory, VersionVariables variables, IFileSystem fileSystem) { @@ -40,7 +38,7 @@ public void Generate() var template = templateManager.GetTemplateFor(fileExtension); var addFormat = templateManager.GetAddFormatFor(fileExtension); - var members = string.Join(Environment.NewLine, variables.Select(v => string.Format(" " + addFormat, v.Key, v.Value))); + var members = string.Join(System.Environment.NewLine, variables.Select(v => string.Format(" " + addFormat, v.Key, v.Value))); var fileContents = string.Format(template, members); diff --git a/src/GitVersionCore/Helpers/LibGitExtensions.cs b/src/GitVersionCore/Extensions/LibGitExtensions.cs similarity index 89% rename from src/GitVersionCore/Helpers/LibGitExtensions.cs rename to src/GitVersionCore/Extensions/LibGitExtensions.cs index 68a4e28f5f..ff8ff670f9 100644 --- a/src/GitVersionCore/Helpers/LibGitExtensions.cs +++ b/src/GitVersionCore/Extensions/LibGitExtensions.cs @@ -4,9 +4,10 @@ using System.Linq; using System.Runtime.InteropServices; using System.Text; +using GitVersion.Helpers; using LibGit2Sharp; -namespace GitVersion.Helpers +namespace GitVersion.Extensions { public static class LibGitExtensions { @@ -138,5 +139,22 @@ public static void DumpGraph(string workingDirectory, Action writer = nu Console.Write(output.ToString()); } } + + public static bool IsBranch(this string branchName, string branchNameToCompareAgainst) + { + // "develop" == "develop" + if (string.Equals(branchName, branchNameToCompareAgainst, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + // "refs/head/develop" == "develop" + if (branchName.EndsWith($"/{branchNameToCompareAgainst}", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + return false; + } } } diff --git a/src/GitVersionCore/Helpers/ReadEmbeddedResourceExtensions.cs b/src/GitVersionCore/Extensions/ReadEmbeddedResourceExtensions.cs similarity index 72% rename from src/GitVersionCore/Helpers/ReadEmbeddedResourceExtensions.cs rename to src/GitVersionCore/Extensions/ReadEmbeddedResourceExtensions.cs index 2401388e9c..fdce1a92b3 100644 --- a/src/GitVersionCore/Helpers/ReadEmbeddedResourceExtensions.cs +++ b/src/GitVersionCore/Extensions/ReadEmbeddedResourceExtensions.cs @@ -1,6 +1,6 @@ using System.IO; -namespace GitVersion.Helpers +namespace GitVersion.Extensions { public static class ReadEmbeddedResourceExtensions { @@ -12,13 +12,9 @@ public static class ReadEmbeddedResourceExtensions /// public static string ReadAsStringFromEmbeddedResource(this string resourceName) { - using (var stream = resourceName.ReadFromEmbeddedResource()) - { - using (var rdr = new StreamReader(stream)) - { - return rdr.ReadToEnd(); - } - } + using var stream = resourceName.ReadFromEmbeddedResource(); + using var rdr = new StreamReader(stream); + return rdr.ReadToEnd(); } private static Stream ReadFromEmbeddedResource(this string resourceName) diff --git a/src/GitVersionCore/Extensions/ServiceCollectionExtensions.cs b/src/GitVersionCore/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000000..47373422f1 --- /dev/null +++ b/src/GitVersionCore/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,12 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace GitVersion.Extensions +{ + public static class ServiceCollectionExtensions + { + public static void AddModule(this IServiceCollection serviceCollection, IGitVersionModule gitVersionModule) + { + gitVersionModule.RegisterTypes(serviceCollection); + } + } +} diff --git a/src/GitVersionExe/ExtensionMethods.cs b/src/GitVersionCore/Extensions/StringExtensions.cs similarity index 76% rename from src/GitVersionExe/ExtensionMethods.cs rename to src/GitVersionCore/Extensions/StringExtensions.cs index 5c0d349628..aa20ba6f09 100644 --- a/src/GitVersionExe/ExtensionMethods.cs +++ b/src/GitVersionCore/Extensions/StringExtensions.cs @@ -1,25 +1,26 @@ using System; using System.IO; using System.Linq; +using System.Text; using System.Text.RegularExpressions; -namespace GitVersion +namespace GitVersion.Extensions { - public static class ExtensionMethods + public static class StringExtensions { - private static string[] trues; - private static string[] falses; + private static readonly string[] Trues; + private static readonly string[] Falses; - static ExtensionMethods() + static StringExtensions() { - trues = new[] + Trues = new[] { "1", "true" }; - falses = new[] + Falses = new[] { "0", "false" @@ -28,12 +29,12 @@ static ExtensionMethods() public static bool IsTrue(this string value) { - return trues.Contains(value, StringComparer.OrdinalIgnoreCase); + return Trues.Contains(value, StringComparer.OrdinalIgnoreCase); } public static bool IsFalse(this string value) { - return falses.Contains(value, StringComparer.OrdinalIgnoreCase); + return Falses.Contains(value, StringComparer.OrdinalIgnoreCase); } public static bool IsValidPath(this string path) @@ -47,7 +48,7 @@ public static bool IsValidPath(this string path) } catch { - path = Path.Combine(Environment.CurrentDirectory, path); + path = Path.Combine(System.Environment.CurrentDirectory, path); try { @@ -115,5 +116,16 @@ public static bool ArgumentRequiresValue(this string argument, int argumentIndex return argumentMightRequireValue; } + + public static void AppendLineFormat(this StringBuilder stringBuilder, string format, params object[] args) + { + stringBuilder.AppendFormat(format, args); + stringBuilder.AppendLine(); + } + + public static string RegexReplace(this string input, string pattern, string replace, RegexOptions options = RegexOptions.None) + { + return Regex.Replace(input, pattern, replace, options); + } } } diff --git a/src/GitVersionCore/Extensions/TemplateManager.cs b/src/GitVersionCore/Extensions/TemplateManager.cs index 483fa2aed7..f4fd47e079 100644 --- a/src/GitVersionCore/Extensions/TemplateManager.cs +++ b/src/GitVersionCore/Extensions/TemplateManager.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Reflection; -using GitVersion.Helpers; namespace GitVersion.Extensions { @@ -71,7 +69,7 @@ public bool IsSupported(string fileExtension) private static IEnumerable GetEmbeddedTemplates(TemplateType templateType, string templateCategory) { - Assembly assy = typeof(TemplateManager).Assembly; + var assy = typeof(TemplateManager).Assembly; foreach (var name in assy.GetManifestResourceNames()) { diff --git a/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs b/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs index 8224a4dfcc..e54922f3cc 100644 --- a/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs +++ b/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Text.RegularExpressions; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Extensions.VersionAssemblyInfoResources diff --git a/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs b/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs index d81ad98aef..56bf485c9c 100644 --- a/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs +++ b/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs @@ -3,47 +3,44 @@ using System.Text; using System.Xml; using GitVersion.OutputVariables; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Extensions { public class WixVersionFileUpdater : IDisposable { - private VersionVariables variables; - private IFileSystem fileSystem; + private readonly VersionVariables variables; + private readonly IFileSystem fileSystem; private readonly ILog log; public string WixVersionFile { get; } - public const string WIX_VERSION_FILE = "GitVersion_WixVersion.wxi"; + public const string WixVersionFileName = "GitVersion_WixVersion.wxi"; public WixVersionFileUpdater(string workingDirectory, VersionVariables variables, IFileSystem fileSystem, ILog log) { this.variables = variables; - this.fileSystem = fileSystem; - this.log = log; - this.WixVersionFile = Path.Combine(workingDirectory, WIX_VERSION_FILE); + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.WixVersionFile = Path.Combine(workingDirectory, WixVersionFileName); } public void Update() { log.Info("Updating GitVersion_WixVersion.wxi"); - XmlDocument doc = new XmlDocument(); + var doc = new XmlDocument(); doc.LoadXml(GetWixFormatFromVersionVariables()); - XmlDeclaration xmlDecl = doc.CreateXmlDeclaration("1.0", "utf-8", null); - XmlElement root = doc.DocumentElement; + var xmlDecl = doc.CreateXmlDeclaration("1.0", "utf-8", null); + var root = doc.DocumentElement; doc.InsertBefore(xmlDecl, root); - using (var fs = fileSystem.OpenWrite(WixVersionFile)) - { - doc.Save(fs); - } + using var fs = fileSystem.OpenWrite(WixVersionFile); + doc.Save(fs); } private string GetWixFormatFromVersionVariables() { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); builder.Append("\n"); var availableVariables = VersionVariables.AvailableVariables; foreach (var variable in availableVariables) diff --git a/src/GitVersionCore/GitPreparer.cs b/src/GitVersionCore/GitPreparer.cs index 626dc0f844..f3cba5d94c 100644 --- a/src/GitVersionCore/GitPreparer.cs +++ b/src/GitVersionCore/GitPreparer.cs @@ -4,77 +4,113 @@ using GitVersion.Helpers; using GitVersion.Logging; using LibGit2Sharp; +using Microsoft.Extensions.Options; namespace GitVersion { - public class GitPreparer + public class GitPreparer : IGitPreparer { private readonly ILog log; - private string dynamicRepositoryLocation; - private AuthenticationInfo authentication; - private bool noFetch; + private readonly string dynamicRepositoryLocation; + private readonly AuthenticationInfo authentication; + private readonly bool noFetch; - private const string defaultRemoteName = "origin"; + private const string DefaultRemoteName = "origin"; + private string dynamicGitRepositoryPath; - public GitPreparer(ILog log, Arguments arguments) - : this(log, arguments.TargetUrl, arguments.DynamicRepositoryLocation, arguments.Authentication, arguments.NoFetch, arguments.TargetPath) + public GitPreparer(ILog log, IOptions options) { - } - - public GitPreparer(ILog log, string targetUrl, string dynamicRepositoryLocation, Authentication authentication, bool noFetch, string targetPath) - { - this.log = log; - TargetUrl = targetUrl; - this.dynamicRepositoryLocation = dynamicRepositoryLocation; - this.authentication = - new AuthenticationInfo - { - Username = authentication?.Username, - Password = authentication?.Password - }; - this.noFetch = noFetch; - WorkingDirectory = targetPath.TrimEnd('/', '\\'); - } + this.log = log ?? throw new ArgumentNullException(nameof(log)); + var arguments = options.Value; - public string TargetUrl { get; } + TargetUrl = arguments.TargetUrl; + WorkingDirectory = arguments.TargetPath.TrimEnd('/', '\\'); - public string WorkingDirectory { get; } - - private bool IsDynamicGitRepository => !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath); + dynamicRepositoryLocation = arguments.DynamicRepositoryLocation; + authentication = new AuthenticationInfo + { + Username = arguments.Authentication?.Username, + Password = arguments.Authentication?.Password + }; - private string DynamicGitRepositoryPath { get; set; } + noFetch = arguments.NoFetch; + } - public void Initialise(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false) + public void Prepare(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false) { if (string.IsNullOrWhiteSpace(TargetUrl)) { - if (normalizeGitDirectory) + if (!normalizeGitDirectory) return; + using (log.IndentLog($"Normalizing git directory for branch '{currentBranch}'")) { - using (log.IndentLog($"Normalizing git directory for branch '{currentBranch}'")) + if (shouldCleanUpRemotes) { - if (shouldCleanUpRemotes) - { - CleanupDuplicateOrigin(); - } - GitRepositoryHelper.NormalizeGitDirectory(log, GetDotGitDirectory(), authentication, noFetch, currentBranch, IsDynamicGitRepository); + CleanupDuplicateOrigin(); } + GitRepositoryHelper.NormalizeGitDirectory(log, GetDotGitDirectory(), authentication, noFetch, currentBranch, IsDynamicGitRepository()); } return; } var tempRepositoryPath = CalculateTemporaryRepositoryPath(TargetUrl, dynamicRepositoryLocation); - DynamicGitRepositoryPath = CreateDynamicRepository(tempRepositoryPath, authentication, TargetUrl, currentBranch, noFetch); + dynamicGitRepositoryPath = CreateDynamicRepository(tempRepositoryPath, authentication, TargetUrl, currentBranch); } + public TResult WithRepository(Func action) + { + using IRepository repo = new Repository(GetDotGitDirectory()); + return action(repo); + } + + public string GetDotGitDirectory() + { + var dotGitDirectory = IsDynamicGitRepository() ? dynamicGitRepositoryPath : Repository.Discover(WorkingDirectory); + + dotGitDirectory = dotGitDirectory?.TrimEnd('/', '\\'); + if (string.IsNullOrEmpty(dotGitDirectory)) + throw new DirectoryNotFoundException("Can't find the .git directory in " + WorkingDirectory); + + if (dotGitDirectory.Contains(Path.Combine(".git", "worktrees"))) + return Directory.GetParent(Directory.GetParent(dotGitDirectory).FullName).FullName; + + return dotGitDirectory; + } + + public string GetProjectRootDirectory() + { + log.Info($"IsDynamicGitRepository: {IsDynamicGitRepository()}"); + if (IsDynamicGitRepository()) + { + log.Info($"Returning Project Root as {WorkingDirectory}"); + return WorkingDirectory; + } + + var dotGitDirectory = Repository.Discover(WorkingDirectory); + + if (string.IsNullOrEmpty(dotGitDirectory)) + throw new DirectoryNotFoundException($"Can't find the .git directory in {WorkingDirectory}"); + + using var repo = new Repository(dotGitDirectory); + var result = repo.Info.WorkingDirectory; + log.Info($"Returning Project Root from DotGitDirectory: {dotGitDirectory} - {result}"); + return result; + } + + public string TargetUrl { get; } + + public string WorkingDirectory { get; } + + private bool IsDynamicGitRepository() => !string.IsNullOrWhiteSpace(dynamicGitRepositoryPath); + private void CleanupDuplicateOrigin() { - var remoteToKeep = defaultRemoteName; + var remoteToKeep = DefaultRemoteName; var repo = new Repository(GetDotGitDirectory()); // check that we have a remote that matches defaultRemoteName if not take the first remote - if (!repo.Network.Remotes.Any(remote => remote.Name.Equals(defaultRemoteName, StringComparison.InvariantCultureIgnoreCase))) + if (!repo.Network.Remotes.Any(remote => remote.Name.Equals(DefaultRemoteName, StringComparison.InvariantCultureIgnoreCase))) { remoteToKeep = repo.Network.Remotes.First().Name; } @@ -91,14 +127,6 @@ private void CleanupDuplicateOrigin() } } - public TResult WithRepository(Func action) - { - using (IRepository repo = new Repository(GetDotGitDirectory())) - { - return action(repo); - } - } - private static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation) { var userTemp = dynamicRepositoryLocation ?? Path.GetTempPath(); @@ -128,10 +156,8 @@ private static bool GitRepoHasMatchingRemote(string possiblePath, string targetU { try { - using (var repository = new Repository(possiblePath)) - { - return repository.Network.Remotes.Any(r => r.Url == targetUrl); - } + using var repository = new Repository(possiblePath); + return repository.Network.Remotes.Any(r => r.Url == targetUrl); } catch (Exception) { @@ -139,43 +165,7 @@ private static bool GitRepoHasMatchingRemote(string possiblePath, string targetU } } - public string GetDotGitDirectory() - { - var dotGitDirectory = IsDynamicGitRepository ? DynamicGitRepositoryPath : Repository.Discover(WorkingDirectory); - - dotGitDirectory = dotGitDirectory?.TrimEnd('/', '\\'); - if (string.IsNullOrEmpty(dotGitDirectory)) - throw new DirectoryNotFoundException("Can't find the .git directory in " + WorkingDirectory); - - if (dotGitDirectory.Contains(Path.Combine(".git", "worktrees"))) - return Directory.GetParent(Directory.GetParent(dotGitDirectory).FullName).FullName; - - return dotGitDirectory; - } - - public string GetProjectRootDirectory() - { - log.Info($"IsDynamicGitRepository: {IsDynamicGitRepository}"); - if (IsDynamicGitRepository) - { - log.Info($"Returning Project Root as {WorkingDirectory}"); - return WorkingDirectory; - } - - var dotGitDirectory = Repository.Discover(WorkingDirectory); - - if (string.IsNullOrEmpty(dotGitDirectory)) - throw new DirectoryNotFoundException($"Can't find the .git directory in {WorkingDirectory}"); - - using (var repo = new Repository(dotGitDirectory)) - { - var result = repo.Info.WorkingDirectory; - log.Info($"Returning Project Root from DotGitDirectory: {dotGitDirectory} - {result}"); - return result; - } - } - - private string CreateDynamicRepository(string targetPath, AuthenticationInfo auth, string repositoryUrl, string targetBranch, bool noFetch) + private string CreateDynamicRepository(string targetPath, AuthenticationInfo auth, string repositoryUrl, string targetBranch) { if (string.IsNullOrWhiteSpace(targetBranch)) { diff --git a/src/GitVersionCore/GitRepoMetadataProvider.cs b/src/GitVersionCore/GitRepoMetadataProvider.cs index e3af94a214..137ea07dbb 100644 --- a/src/GitVersionCore/GitRepoMetadataProvider.cs +++ b/src/GitVersionCore/GitRepoMetadataProvider.cs @@ -4,20 +4,20 @@ using System.Linq; using System.Text.RegularExpressions; using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersion { public class GitRepoMetadataProvider { - private Dictionary> mergeBaseCommitsCache; - private Dictionary, MergeBaseData> mergeBaseCache; - private Dictionary> semanticVersionTagsOnBranchCache; - private IRepository Repository { get; set; } - private const string missingTipFormat = "{0} has no tip. Please see http://example.com/docs for information on how to fix this."; + private readonly Dictionary> mergeBaseCommitsCache; + private readonly Dictionary, MergeBaseData> mergeBaseCache; + private readonly Dictionary> semanticVersionTagsOnBranchCache; + private IRepository Repository { get; } + private const string MissingTipFormat = "{0} has no tip. Please see http://example.com/docs for information on how to fix this."; private readonly ILog log; - private Config configuration; + private readonly Config configuration; public GitRepoMetadataProvider(IRepository repository, ILog log, Config configuration) { @@ -29,7 +29,7 @@ public GitRepoMetadataProvider(IRepository repository, ILog log, Config configur this.configuration = configuration; } - public static IEnumerable> GetValidVersionTags(IRepository repository, string tagPrefixRegex, DateTimeOffset? olderThan = null) + public IEnumerable> GetValidVersionTags(IRepository repository, string tagPrefixRegex, DateTimeOffset? olderThan = null) { var tags = new List>(); @@ -207,7 +207,7 @@ public BranchCommit FindCommitBranchWasBranchedFrom(Branch branch, params Branch { if (branch.Tip == null) { - log.Warning(string.Format(missingTipFormat, branch.FriendlyName)); + log.Warning(string.Format(MissingTipFormat, branch.FriendlyName)); return BranchCommit.Empty; } @@ -253,7 +253,7 @@ private List GetMergeCommitsForBranch(Branch branch, Branch[] excl { if (otherBranch.Tip == null) { - log.Warning(string.Format(missingTipFormat, otherBranch.FriendlyName)); + log.Warning(string.Format(MissingTipFormat, otherBranch.FriendlyName)); return BranchCommit.Empty; } @@ -270,11 +270,11 @@ private List GetMergeCommitsForBranch(Branch branch, Branch[] excl private class MergeBaseData { - public Branch Branch { get; private set; } - public Branch OtherBranch { get; private set; } - public IRepository Repository { get; private set; } + public Branch Branch { get; } + public Branch OtherBranch { get; } + public IRepository Repository { get; } - public Commit MergeBase { get; private set; } + public Commit MergeBase { get; } public MergeBaseData(Branch branch, Branch otherBranch, IRepository repository, Commit mergeBase) { diff --git a/src/GitVersionCore/GitVersionCalculator.cs b/src/GitVersionCore/GitVersionCalculator.cs new file mode 100644 index 0000000000..5116440529 --- /dev/null +++ b/src/GitVersionCore/GitVersionCalculator.cs @@ -0,0 +1,131 @@ +using System; +using GitVersion.Configuration; +using GitVersion.OutputVariables; +using GitVersion.Cache; +using GitVersion.Logging; +using Microsoft.Extensions.Options; + +namespace GitVersion +{ + public class GitVersionCalculator : IGitVersionCalculator + { + private readonly IFileSystem fileSystem; + private readonly ILog log; + private readonly IConfigFileLocator configFileLocator; + private readonly IConfigProvider configProvider; + private readonly IBuildServerResolver buildServerResolver; + private readonly IGitVersionCache gitVersionCache; + private readonly IGitVersionFinder gitVersionFinder; + private readonly IGitPreparer gitPreparer; + private readonly IVariableProvider variableProvider; + private readonly Arguments arguments; + + public GitVersionCalculator(IFileSystem fileSystem, ILog log, IConfigFileLocator configFileLocator, + IConfigProvider configProvider, + IBuildServerResolver buildServerResolver, IGitVersionCache gitVersionCache, + IGitVersionFinder gitVersionFinder, IGitPreparer gitPreparer, IVariableProvider variableProvider, IOptions options) + { + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.configFileLocator = configFileLocator ?? throw new ArgumentNullException(nameof(configFileLocator)); + this.configProvider = configProvider ?? throw new ArgumentNullException(nameof(configProvider)); + this.buildServerResolver = buildServerResolver ?? throw new ArgumentNullException(nameof(buildServerResolver)); + this.gitVersionCache = gitVersionCache ?? throw new ArgumentNullException(nameof(gitVersionCache)); + this.gitVersionFinder = gitVersionFinder ?? throw new ArgumentNullException(nameof(gitVersionFinder)); + this.gitPreparer = gitPreparer ?? throw new ArgumentNullException(nameof(gitPreparer)); + this.variableProvider = variableProvider ?? throw new ArgumentNullException(nameof(variableProvider)); + this.arguments = options.Value; + } + + public VersionVariables CalculateVersionVariables() + { + var buildServer = buildServerResolver.Resolve(); + + // Normalize if we are running on build server + var normalizeGitDirectory = !arguments.NoNormalize && buildServer != null; + var shouldCleanUpRemotes = buildServer != null && buildServer.ShouldCleanUpRemotes(); + + var currentBranch = ResolveCurrentBranch(buildServer, arguments.TargetBranch, !string.IsNullOrWhiteSpace(arguments.DynamicRepositoryLocation)); + + gitPreparer.Prepare(normalizeGitDirectory, currentBranch, shouldCleanUpRemotes); + + var dotGitDirectory = gitPreparer.GetDotGitDirectory(); + var projectRoot = gitPreparer.GetProjectRootDirectory(); + + log.Info($"Project root is: {projectRoot}"); + log.Info($"DotGit directory is: {dotGitDirectory}"); + if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot)) + { + // TODO Link to wiki article + throw new Exception($"Failed to prepare or find the .git directory in path '{arguments.TargetPath}'."); + } + + return GetCachedGitVersionInfo(arguments.TargetBranch, arguments.CommitId, arguments.OverrideConfig, arguments.NoCache); + } + + public bool TryCalculateVersionVariables(out VersionVariables versionVariables) + { + try + { + versionVariables = CalculateVersionVariables(); + return true; + } + catch (Exception ex) + { + log.Warning("Could not determine assembly version: " + ex); + versionVariables = null; + return false; + } + } + + private string ResolveCurrentBranch(IBuildServer buildServer, string targetBranch, bool isDynamicRepository) + { + if (buildServer == null) + { + return targetBranch; + } + + var currentBranch = buildServer.GetCurrentBranch(isDynamicRepository) ?? targetBranch; + log.Info("Branch from build environment: " + currentBranch); + + return currentBranch; + } + + private VersionVariables GetCachedGitVersionInfo(string targetBranch, string commitId, Config overrideConfig, bool noCache) + { + var cacheKey = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, configFileLocator, overrideConfig); + var versionVariables = noCache ? default : gitVersionCache.LoadVersionVariablesFromDiskCache(gitPreparer, cacheKey); + if (versionVariables == null) + { + versionVariables = ExecuteInternal(targetBranch, commitId, overrideConfig); + + if (!noCache) + { + try + { + gitVersionCache.WriteVariablesToDiskCache(gitPreparer, cacheKey, versionVariables); + } + catch (AggregateException e) + { + log.Warning($"One or more exceptions during cache write:{System.Environment.NewLine}{e}"); + } + } + } + + return versionVariables; + } + + private VersionVariables ExecuteInternal(string targetBranch, string commitId, Config overrideConfig) + { + var configuration = configProvider.Provide(overrideConfig: overrideConfig); + + return gitPreparer.WithRepository(repo => + { + var gitVersionContext = new GitVersionContext(repo, log, targetBranch, configuration, commitId: commitId); + var semanticVersion = gitVersionFinder.FindVersion(gitVersionContext); + + return variableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged); + }); + } + } +} diff --git a/src/GitVersionCore/GitVersionContext.cs b/src/GitVersionCore/GitVersionContext.cs index bc30367527..364ed7bf8f 100644 --- a/src/GitVersionCore/GitVersionContext.cs +++ b/src/GitVersionCore/GitVersionContext.cs @@ -2,8 +2,8 @@ using System; using System.Linq; using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersion { @@ -12,7 +12,7 @@ namespace GitVersion /// public class GitVersionContext { - public ILog Log { get; set; } + public ILog Log { get; } public GitVersionContext(IRepository repository, ILog log, string targetBranch, Config configuration, bool onlyEvaluateTrackedBranches = true, string commitId = null) : this(repository, log, GetTargetBranch(repository, targetBranch), configuration, onlyEvaluateTrackedBranches, commitId) @@ -181,7 +181,7 @@ private static Branch GetTargetBranch(IRepository repository, string targetBranc b.NameWithoutRemote() == targetBranch); // Failsafe in case the specified branch is invalid - desiredBranch = desiredBranch ?? repository.Head; + desiredBranch ??= repository.Head; } } diff --git a/src/GitVersionCore/GitVersionCore.csproj b/src/GitVersionCore/GitVersionCore.csproj index 9348e172bb..fdc30639b7 100644 --- a/src/GitVersionCore/GitVersionCore.csproj +++ b/src/GitVersionCore/GitVersionCore.csproj @@ -12,11 +12,15 @@ Derives SemVer information from a repository following GitFlow or GitHubFlow. This is the Core library which both GitVersion cli and Task use allowing programatic usage of GitVersion. $(AssemblyName) + + 8 + + diff --git a/src/GitVersionCore/GitVersionCoreModule.cs b/src/GitVersionCore/GitVersionCoreModule.cs new file mode 100644 index 0000000000..22a67d8031 --- /dev/null +++ b/src/GitVersionCore/GitVersionCoreModule.cs @@ -0,0 +1,72 @@ +using GitVersion.BuildServers; +using GitVersion.Cache; +using Microsoft.Extensions.DependencyInjection; +using GitVersion.Configuration; +using GitVersion.Logging; +using GitVersion.OutputVariables; +using GitVersion.VersionCalculation; +using GitVersion.VersionCalculation.BaseVersionCalculators; +using GitVersion.Configuration.Init; +using GitVersion.Extensions; + +namespace GitVersion +{ + public class GitVersionCoreModule : IGitVersionModule + { + public void RegisterTypes(IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddSingleton(sp => sp.GetService().Create()); + + RegisterBuildServers(services); + + RegisterVersionStrategies(services); + + services.AddModule(new GitVersionInitModule()); + } + + private static void RegisterBuildServers(IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + } + + private static void RegisterVersionStrategies(IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + } + } +} diff --git a/src/GitVersionCore/GitVersionFinder.cs b/src/GitVersionCore/GitVersionFinder.cs index fc11298c56..44e44cd7de 100644 --- a/src/GitVersionCore/GitVersionFinder.cs +++ b/src/GitVersionCore/GitVersionFinder.cs @@ -1,14 +1,24 @@ +using System; using System.IO; using GitVersion.Exceptions; using GitVersion.VersionCalculation; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersion { - public class GitVersionFinder + public class GitVersionFinder : IGitVersionFinder { - public SemanticVersion FindVersion(ILog log, GitVersionContext context) + private readonly ILog log; + private readonly INextVersionCalculator nextVersionCalculator; + + public GitVersionFinder(ILog log, INextVersionCalculator nextVersionCalculator) + { + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.nextVersionCalculator = nextVersionCalculator ?? throw new ArgumentNullException(nameof(nextVersionCalculator)); + } + + public SemanticVersion FindVersion(GitVersionContext context) { log.Info($"Running against branch: {context.CurrentBranch.FriendlyName} ({(context.CurrentCommit == null ? "-" : context.CurrentCommit.Sha)})"); if (context.IsCurrentCommitTagged) @@ -24,7 +34,7 @@ public SemanticVersion FindVersion(ILog log, GitVersionContext context) throw new WarningException("NextVersion.txt has been deprecated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement"); } - return new NextVersionCalculator(log).FindVersion(context); + return nextVersionCalculator.FindVersion(context); } private void EnsureMainTopologyConstraints(GitVersionContext context) diff --git a/src/GitVersionCore/Helpers/EncodingHelper.cs b/src/GitVersionCore/Helpers/EncodingHelper.cs index ea9cf5ee82..cf2a1f8efd 100644 --- a/src/GitVersionCore/Helpers/EncodingHelper.cs +++ b/src/GitVersionCore/Helpers/EncodingHelper.cs @@ -7,9 +7,9 @@ namespace GitVersion.Helpers { public static class EncodingHelper { - private static IList EncodingsWithPreambles; + private static IList encodingsWithPreambles; - private static int MaxPreambleLength; + private static int maxPreambleLength; /// /// Detects the encoding of a file if and only if it includes a preamble . @@ -23,26 +23,24 @@ public static Encoding DetectEncoding(string filename) return null; } - if (EncodingsWithPreambles == null) + if (encodingsWithPreambles == null) { ScanEncodings(); } - using (var stream = File.OpenRead(filename)) + using var stream = File.OpenRead(filename); + // No bytes? No encoding! + if (stream.Length == 0) { - // No bytes? No encoding! - if (stream.Length == 0) - { - return null; - } + return null; + } - // Read the minimum amount necessary. - var length = stream.Length > MaxPreambleLength ? MaxPreambleLength : stream.Length; + // Read the minimum amount necessary. + var length = stream.Length > maxPreambleLength ? maxPreambleLength : stream.Length; - var bytes = new byte[length]; - stream.Read(bytes, 0, (int)length); - return DetectEncoding(bytes); - } + var bytes = new byte[length]; + stream.Read(bytes, 0, (int)length); + return DetectEncoding(bytes); } /// @@ -57,12 +55,12 @@ public static Encoding DetectEncoding(IList bytes) return null; } - if (EncodingsWithPreambles == null) + if (encodingsWithPreambles == null) { ScanEncodings(); } - return EncodingsWithPreambles.FirstOrDefault(encoding => PreambleMatches(encoding, bytes)); + return encodingsWithPreambles.FirstOrDefault(encoding => PreambleMatches(encoding, bytes)); } /// @@ -74,15 +72,15 @@ public static Encoding DetectEncoding(IList bytes) private static void ScanEncodings() { var encodings = (Encoding.GetEncodings()); - EncodingsWithPreambles = (from info in encodings + encodingsWithPreambles = (from info in encodings let encoding = info.GetEncoding() let preamble = encoding.GetPreamble() where preamble.Length > 0 orderby preamble.Length descending select encoding).ToList(); - var encodingWithLongestPreamble = EncodingsWithPreambles.FirstOrDefault(); - MaxPreambleLength = encodingWithLongestPreamble?.GetPreamble().Length ?? 0; + var encodingWithLongestPreamble = encodingsWithPreambles.FirstOrDefault(); + maxPreambleLength = encodingWithLongestPreamble?.GetPreamble().Length ?? 0; } /// diff --git a/src/GitVersionCore/Helpers/EnvironmentHelper.cs b/src/GitVersionCore/Helpers/EnvironmentHelper.cs deleted file mode 100644 index 84d35afe0d..0000000000 --- a/src/GitVersionCore/Helpers/EnvironmentHelper.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace GitVersion.Helpers -{ - public class EnvironmentHelper - { - public static string GetEnvironmentVariableForProcess(string envVar) - { - return Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process); - } - } -} diff --git a/src/GitVersionCore/Helpers/ExtensionMethods.cs b/src/GitVersionCore/Helpers/ExtensionMethods.cs deleted file mode 100644 index f7137df2e6..0000000000 --- a/src/GitVersionCore/Helpers/ExtensionMethods.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; - -namespace GitVersion.Helpers -{ - internal static class ExtensionMethods - { - public static bool IsBranch(this string branchName, string branchNameToCompareAgainst) - { - // "develop" == "develop" - if (string.Equals(branchName, branchNameToCompareAgainst, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - // "refs/head/develop" == "develop" - if (branchName.EndsWith($"/{branchNameToCompareAgainst}", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - return false; - } - - public static void AppendLineFormat(this StringBuilder stringBuilder, string format, params object[] args) - { - stringBuilder.AppendFormat(format, args); - stringBuilder.AppendLine(); - } - - public static string RegexReplace(this string input, string pattern, string replace, RegexOptions options = RegexOptions.None) - { - return Regex.Replace(input, pattern, replace, options); - } - - public static T OnlyOrDefault(this IEnumerable source) - { - if (source == null) throw new ArgumentNullException(nameof(source)); - - if (source is IList list && list.Count == 1) - { - return list[0]; - } - - using (var e = source.GetEnumerator()) - { - if (!e.MoveNext()) return default; - var result = e.Current; - if (!e.MoveNext()) return result; - } - - return default; - } - } -} diff --git a/src/GitVersionCore/Helpers/GitRepositoryHelper.cs b/src/GitVersionCore/Helpers/GitRepositoryHelper.cs index a160a36aec..8ce46dbc3c 100644 --- a/src/GitVersionCore/Helpers/GitRepositoryHelper.cs +++ b/src/GitVersionCore/Helpers/GitRepositoryHelper.cs @@ -1,9 +1,9 @@ -using System; using System.Collections.Generic; using System.Linq; using GitVersion.Exceptions; using GitVersion.Logging; using LibGit2Sharp; +using GitVersion.Extensions; namespace GitVersion.Helpers { @@ -16,120 +16,118 @@ public static class GitRepositoryHelper public static void NormalizeGitDirectory(ILog log, string gitDirectory, AuthenticationInfo authentication, bool noFetch, string currentBranch, bool isDynamicRepository) { - using (var repo = new Repository(gitDirectory)) + using var repo = new Repository(gitDirectory); + // Need to ensure the HEAD does not move, this is essentially a BugCheck + var expectedSha = repo.Head.Tip.Sha; + var expectedBranchName = repo.Head.CanonicalName; + + try { - // Need to ensure the HEAD does not move, this is essentially a BugCheck - var expectedSha = repo.Head.Tip.Sha; - var expectedBranchName = repo.Head.CanonicalName; + var remote = EnsureOnlyOneRemoteIsDefined(log, repo); + + AddMissingRefSpecs(log, repo, remote); - try + //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required. + if (noFetch) { - var remote = EnsureOnlyOneRemoteIsDefined(log, repo); + log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories"); + } + else + { + Fetch(log, authentication, remote, repo); + } - AddMissingRefSpecs(log, repo, remote); + EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch); + CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name); - //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required. - if (noFetch) - { - log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories"); - } - else - { - Fetch(log, authentication, remote, repo); - } - - EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch); - CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name); + // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed + // if this is a dynamic repository. But only allow this in case the branches are different (branch switch) + if (expectedSha != repo.Head.Tip.Sha && + (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch))) + { + var newExpectedSha = repo.Head.Tip.Sha; + var newExpectedBranchName = repo.Head.CanonicalName; - // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed - // if this is a dynamic repository. But only allow this in case the branches are different (branch switch) - if (expectedSha != repo.Head.Tip.Sha && - (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch))) - { - var newExpectedSha = repo.Head.Tip.Sha; - var newExpectedBranchName = repo.Head.CanonicalName; + log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); - log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); + expectedSha = newExpectedSha; + } - expectedSha = newExpectedSha; - } + var headSha = repo.Refs.Head.TargetIdentifier; - var headSha = repo.Refs.Head.TargetIdentifier; + if (!repo.Info.IsHeadDetached) + { + log.Info($"HEAD points at branch '{headSha}'."); + return; + } - if (!repo.Info.IsHeadDetached) - { - log.Info($"HEAD points at branch '{headSha}'."); - return; - } + log.Info($"HEAD is detached and points at commit '{headSha}'."); + log.Info(string.Format("Local Refs:\r\n" + string.Join(System.Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})")))); - log.Info($"HEAD is detached and points at commit '{headSha}'."); - log.Info(string.Format("Local Refs:\r\n" + string.Join(Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})")))); + // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA. + // If they do, go ahead and checkout that branch + // If no, go ahead and check out a new branch, using the known commit SHA as the pointer + var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList(); - // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA. - // If they do, go ahead and checkout that branch - // If no, go ahead and check out a new branch, using the known commit SHA as the pointer - var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList(); + var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch) + ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/")) + : null; + if (matchingCurrentBranch != null) + { + log.Info($"Checking out local branch '{currentBranch}'."); + Commands.Checkout(repo, matchingCurrentBranch); + } + else if (localBranchesWhereCommitShaIsHead.Count > 1) + { + var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName); + var csvNames = string.Join(", ", branchNames); + const string moveBranchMsg = "Move one of the branches along a commit to remove warning"; - var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch) - ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/")) - : null; - if (matchingCurrentBranch != null) + log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames})."); + var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master"); + if (master != null) { - log.Info($"Checking out local branch '{currentBranch}'."); - Commands.Checkout(repo, matchingCurrentBranch); + log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg); + Commands.Checkout(repo, master); } - else if (localBranchesWhereCommitShaIsHead.Count > 1) + else { - var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName); - var csvNames = string.Join(", ", branchNames); - const string moveBranchMsg = "Move one of the branches along a commit to remove warning"; - - log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames})."); - var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master"); - if (master != null) + var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList(); + if (branchesWithoutSeparators.Count == 1) { - log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg); - Commands.Checkout(repo, master); + var branchWithoutSeparator = branchesWithoutSeparators[0]; + log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg); + Commands.Checkout(repo, branchWithoutSeparator); } else { - var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList(); - if (branchesWithoutSeparators.Count == 1) - { - var branchWithoutSeparator = branchesWithoutSeparators[0]; - log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg); - Commands.Checkout(repo, branchWithoutSeparator); - } - else - { - throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg); - } + throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg); } } - else if (localBranchesWhereCommitShaIsHead.Count == 0) - { - log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); - CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication); - } - else - { - log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'."); - Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]); - } } - finally + else if (localBranchesWhereCommitShaIsHead.Count == 0) + { + log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); + CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication); + } + else { - if (repo.Head.Tip.Sha != expectedSha) + log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'."); + Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]); + } + } + finally + { + if (repo.Head.Tip.Sha != expectedSha) + { + if (System.Environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1") { - if (Environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1") - { - // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation - throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation. + // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation + throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation. To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1 Please run `git {CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion"); - } } } } @@ -205,7 +203,7 @@ private static void CreateFakeBranchPointingAtThePullRequestTip(ILog log, Reposi GetRemoteTipsUsingUsernamePasswordCredentials(repo, remote, authentication.Username, authentication.Password)) .ToList(); - log.Info("Remote Refs:\r\n" + string.Join(Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); + log.Info("Remote Refs:\r\n" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); var headTipSha = repo.Head.Tip.Sha; diff --git a/src/GitVersionCore/Helpers/LambdaEqualityHelper.cs b/src/GitVersionCore/Helpers/LambdaEqualityHelper.cs index 4001fde062..2a9675642f 100644 --- a/src/GitVersionCore/Helpers/LambdaEqualityHelper.cs +++ b/src/GitVersionCore/Helpers/LambdaEqualityHelper.cs @@ -7,7 +7,7 @@ namespace GitVersion.Helpers // see https://github.com/libgit2/libgit2sharp/blob/7af5c60f22f9bd6064204f84467cfa62bedd1147/LibGit2Sharp/Core/LambdaEqualityHelper.cs internal class LambdaEqualityHelper { - private Func[] equalityContributorAccessors; + private readonly Func[] equalityContributorAccessors; public LambdaEqualityHelper(params Func[] equalityContributorAccessors) { diff --git a/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs b/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs index f438b3e7a6..365e9028b0 100644 --- a/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs +++ b/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs @@ -1,56 +1,55 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using GitVersion.Common; using GitVersion.Logging; namespace GitVersion.Helpers { internal class OperationWithExponentialBackoff where T : Exception { - private IThreadSleep ThreadSleep; + private readonly IThreadSleep threadSleep; private readonly ILog log; - private Action Operation; - private int MaxRetries; + private readonly Action operation; + private readonly int maxRetries; public OperationWithExponentialBackoff(IThreadSleep threadSleep, ILog log, Action operation, int maxRetries = 5) { if (maxRetries < 0) throw new ArgumentOutOfRangeException(nameof(maxRetries)); - ThreadSleep = threadSleep ?? throw new ArgumentNullException(nameof(threadSleep)); + this.threadSleep = threadSleep ?? throw new ArgumentNullException(nameof(threadSleep)); this.log = log; - Operation = operation; - MaxRetries = maxRetries; + this.operation = operation; + this.maxRetries = maxRetries; } public async Task ExecuteAsync() { var exceptions = new List(); - int tries = 0; - int sleepMSec = 500; + var tries = 0; + var sleepMSec = 500; - while (tries <= MaxRetries) + while (tries <= maxRetries) { tries++; try { - Operation(); + operation(); break; } catch (T e) { exceptions.Add(e); - if (tries > MaxRetries) + if (tries > maxRetries) { throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions); } } log.Info($"Operation failed, retrying in {sleepMSec} milliseconds."); - await ThreadSleep.SleepAsync(sleepMSec); + await threadSleep.SleepAsync(sleepMSec); sleepMSec *= 2; } diff --git a/src/GitVersionCore/Helpers/ProcessHelper.cs b/src/GitVersionCore/Helpers/ProcessHelper.cs index f101766b2c..8d4f5e04eb 100644 --- a/src/GitVersionCore/Helpers/ProcessHelper.cs +++ b/src/GitVersionCore/Helpers/ProcessHelper.cs @@ -10,14 +10,14 @@ namespace GitVersion.Helpers { public static class ProcessHelper { - private static volatile object lockObject = new object(); + private static readonly object LockObject = new object(); // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3 private static Process Start(ProcessStartInfo startInfo) { Process process; - lock (lockObject) + lock (LockObject) { using (new ChangeErrorMode(ErrorModes.FailCriticalErrors | ErrorModes.NoGpFaultErrorBox)) { @@ -86,7 +86,7 @@ public static int Run(Action output, Action errorOutput, TextRea if (output == null) throw new ArgumentNullException(nameof(output)); - workingDirectory = workingDirectory ?? Environment.CurrentDirectory; + workingDirectory ??= System.Environment.CurrentDirectory; var psi = new ProcessStartInfo { @@ -117,42 +117,40 @@ public static int Run(Action output, Action errorOutput, TextRea } } - using (var process = Start(psi)) - using (var mreOut = new ManualResetEvent(false)) - using (var mreErr = new ManualResetEvent(false)) + using var process = Start(psi); + using var mreOut = new ManualResetEvent(false); + using var mreErr = new ManualResetEvent(false); + process.EnableRaisingEvents = true; + process.OutputDataReceived += (o, e) => { - process.EnableRaisingEvents = true; - process.OutputDataReceived += (o, e) => - { - // ReSharper disable once AccessToDisposedClosure - if (e.Data == null) - mreOut.Set(); - else - output(e.Data); - }; - process.BeginOutputReadLine(); - process.ErrorDataReceived += (o, e) => - { - // ReSharper disable once AccessToDisposedClosure - if (e.Data == null) - mreErr.Set(); - else - errorOutput(e.Data); - }; - process.BeginErrorReadLine(); + // ReSharper disable once AccessToDisposedClosure + if (e.Data == null) + mreOut.Set(); + else + output(e.Data); + }; + process.BeginOutputReadLine(); + process.ErrorDataReceived += (o, e) => + { + // ReSharper disable once AccessToDisposedClosure + if (e.Data == null) + mreErr.Set(); + else + errorOutput(e.Data); + }; + process.BeginErrorReadLine(); - string line; - while (input != null && null != (line = input.ReadLine())) - process.StandardInput.WriteLine(line); + string line; + while (input != null && null != (line = input.ReadLine())) + process.StandardInput.WriteLine(line); - process.StandardInput.Close(); - process.WaitForExit(); + process.StandardInput.Close(); + process.WaitForExit(); - mreOut.WaitOne(); - mreErr.WaitOne(); + mreOut.WaitOne(); + mreErr.WaitOne(); - return process.ExitCode; - } + return process.ExitCode; } /// diff --git a/src/GitVersionCore/Helpers/StringComparerUtils.cs b/src/GitVersionCore/Helpers/StringComparerUtils.cs index 013f6e2baa..d454f1471c 100644 --- a/src/GitVersionCore/Helpers/StringComparerUtils.cs +++ b/src/GitVersionCore/Helpers/StringComparerUtils.cs @@ -5,6 +5,6 @@ namespace GitVersion.Helpers public static class StringComparerUtils { public static readonly StringComparer IgnoreCaseComparer = StringComparer.InvariantCultureIgnoreCase; - public static readonly StringComparison OSDependentComparison = Environment.OSVersion.Platform == PlatformID.Unix ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; + public static readonly StringComparison OsDependentComparison = System.Environment.OSVersion.Platform == PlatformID.Unix ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase; } } diff --git a/src/GitVersionCore/Helpers/StringFormatWith.cs b/src/GitVersionCore/Helpers/StringFormatWith.cs index ac3ef7d79c..5bf14c2029 100644 --- a/src/GitVersionCore/Helpers/StringFormatWith.cs +++ b/src/GitVersionCore/Helpers/StringFormatWith.cs @@ -39,14 +39,14 @@ public static string FormatWith(this string template, T source) { memberAccessExpression = memberAccessExpression.Substring(memberAccessExpression.IndexOf(':') + 1); string envVar = memberAccessExpression, fallback = null; - string[] components = (memberAccessExpression.Contains("??")) ? memberAccessExpression.Split(new[] { "??" }, StringSplitOptions.None) : null; + var components = (memberAccessExpression.Contains("??")) ? memberAccessExpression.Split(new[] { "??" }, StringSplitOptions.None) : null; if (components != null) { envVar = components[0].Trim(); fallback = components[1].Trim(); } - propertyValue = EnvironmentHelper.GetEnvironmentVariableForProcess(envVar); + propertyValue = System.Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.Process); if (propertyValue == null) { if (fallback != null) @@ -57,7 +57,7 @@ public static string FormatWith(this string template, T source) } else { - Func expression = CompileDataBinder(objType, memberAccessExpression); + var expression = CompileDataBinder(objType, memberAccessExpression); propertyValue = expression(source); } template = template.Replace(match.Value, propertyValue); diff --git a/src/GitVersionCore/IGitPreparer.cs b/src/GitVersionCore/IGitPreparer.cs new file mode 100644 index 0000000000..690a4f692f --- /dev/null +++ b/src/GitVersionCore/IGitPreparer.cs @@ -0,0 +1,15 @@ +using System; +using LibGit2Sharp; + +namespace GitVersion +{ + public interface IGitPreparer + { + void Prepare(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false); + TResult WithRepository(Func action); + string GetDotGitDirectory(); + string GetProjectRootDirectory(); + string TargetUrl { get; } + string WorkingDirectory { get; } + } +} diff --git a/src/GitVersionCore/IGitVersionCalculator.cs b/src/GitVersionCore/IGitVersionCalculator.cs new file mode 100644 index 0000000000..31ef0d82ab --- /dev/null +++ b/src/GitVersionCore/IGitVersionCalculator.cs @@ -0,0 +1,10 @@ +using GitVersion.OutputVariables; + +namespace GitVersion +{ + public interface IGitVersionCalculator + { + VersionVariables CalculateVersionVariables(); + bool TryCalculateVersionVariables(out VersionVariables versionVariables); + } +} diff --git a/src/GitVersionCore/IGitVersionFinder.cs b/src/GitVersionCore/IGitVersionFinder.cs new file mode 100644 index 0000000000..7ecf9cbb68 --- /dev/null +++ b/src/GitVersionCore/IGitVersionFinder.cs @@ -0,0 +1,7 @@ +namespace GitVersion +{ + public interface IGitVersionFinder + { + SemanticVersion FindVersion(GitVersionContext context); + } +} diff --git a/src/GitVersionCore/Configuration/IncrementStrategy.cs b/src/GitVersionCore/IncrementStrategy.cs similarity index 53% rename from src/GitVersionCore/Configuration/IncrementStrategy.cs rename to src/GitVersionCore/IncrementStrategy.cs index ad4b9f8a4e..4f98f11ea3 100644 --- a/src/GitVersionCore/Configuration/IncrementStrategy.cs +++ b/src/GitVersionCore/IncrementStrategy.cs @@ -1,6 +1,7 @@ using System; +using GitVersion.Configuration; -namespace GitVersion.Configuration +namespace GitVersion { public enum IncrementStrategy { @@ -19,19 +20,14 @@ public static class IncrementStrategyExtensions { public static VersionField ToVersionField(this IncrementStrategy strategy) { - switch (strategy) + return strategy switch { - case IncrementStrategy.None: - return VersionField.None; - case IncrementStrategy.Major: - return VersionField.Major; - case IncrementStrategy.Minor: - return VersionField.Minor; - case IncrementStrategy.Patch: - return VersionField.Patch; - default: - throw new ArgumentOutOfRangeException(nameof(strategy), strategy, null); - } + IncrementStrategy.None => VersionField.None, + IncrementStrategy.Major => VersionField.Major, + IncrementStrategy.Minor => VersionField.Minor, + IncrementStrategy.Patch => VersionField.Patch, + _ => throw new ArgumentOutOfRangeException(nameof(strategy), strategy, null) + }; } } } diff --git a/src/GitVersionCore/IncrementStrategyFinder.cs b/src/GitVersionCore/IncrementStrategyFinder.cs index 2d58b70add..231e8c3639 100644 --- a/src/GitVersionCore/IncrementStrategyFinder.cs +++ b/src/GitVersionCore/IncrementStrategyFinder.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using GitVersion.Configuration; using GitVersion.VersionCalculation.BaseVersionCalculators; using LibGit2Sharp; -using GitVersion.Helpers; +using GitVersion.Configuration; +using GitVersion.Extensions; namespace GitVersion { @@ -91,8 +91,6 @@ public static class IncrementStrategyFinder return null; } - - private static IEnumerable GetIntermediateCommits(IRepository repo, Commit baseCommit, Commit headCommit) { if (baseCommit == null) yield break; @@ -131,7 +129,6 @@ private static IEnumerable GetIntermediateCommits(IRepository repo, Comm return version; } - private static VersionField? FindIncrementFromMessage(string message, string majorRegex, string minorRegex, string patchRegex, string noneRegex) { if(IsMatch(message, majorRegex)) return VersionField.Major; @@ -153,8 +150,8 @@ private static bool IsMatch(string message, string regex) return match; } - private static IDictionary MatchCache = new Dictionary(); - private static IDictionary VersionFieldCache = new Dictionary(); + private static readonly IDictionary MatchCache = new Dictionary(); + private static readonly IDictionary VersionFieldCache = new Dictionary(); public static VersionField FindDefaultIncrementForBranch( GitVersionContext context, string branch = null ) { diff --git a/src/GitVersionCore/Logging/ConsoleAppender.cs b/src/GitVersionCore/Logging/ConsoleAppender.cs index 40b58e0b49..19242409ab 100644 --- a/src/GitVersionCore/Logging/ConsoleAppender.cs +++ b/src/GitVersionCore/Logging/ConsoleAppender.cs @@ -5,20 +5,20 @@ namespace GitVersion.Logging { public class ConsoleAppender : ILogAppender { - private readonly object _lock; - private IDictionary _palettes; + private readonly object locker; + private readonly IDictionary palettes; public ConsoleAppender() { - _lock = new object(); - _palettes = CreatePalette(); + locker = new object(); + palettes = CreatePalette(); } public void WriteTo(LogLevel level, string message) { - lock (_lock) + lock (locker) { try { - var (backgroundColor, foregroundColor) = _palettes[level]; + var (backgroundColor, foregroundColor) = palettes[level]; Console.BackgroundColor = backgroundColor; Console.ForegroundColor = foregroundColor; diff --git a/src/GitVersionCore/Logging/Disposable.cs b/src/GitVersionCore/Logging/Disposable.cs index 00e7e25ed2..cae65a6ded 100644 --- a/src/GitVersionCore/Logging/Disposable.cs +++ b/src/GitVersionCore/Logging/Disposable.cs @@ -17,16 +17,16 @@ private sealed class AnonymousDisposable : IDisposable { public AnonymousDisposable(Action disposer) { - _disposer = disposer ?? throw new ArgumentNullException(nameof(disposer)); + this.disposer = disposer ?? throw new ArgumentNullException(nameof(disposer)); } public void Dispose() { - _disposer?.Invoke(); - _disposer = null; + disposer?.Invoke(); + disposer = null; } - private Action _disposer; + private Action disposer; } } } \ No newline at end of file diff --git a/src/GitVersionCore/Logging/FileAppender.cs b/src/GitVersionCore/Logging/FileAppender.cs index 6218e51643..55541356f8 100644 --- a/src/GitVersionCore/Logging/FileAppender.cs +++ b/src/GitVersionCore/Logging/FileAppender.cs @@ -6,7 +6,7 @@ namespace GitVersion.Logging { public class FileAppender : ILogAppender { - private static readonly ReaderWriterLock locker = new ReaderWriterLock(); + private static readonly ReaderWriterLock Locker = new ReaderWriterLock(); private readonly string filePath; public FileAppender(string filePath) diff --git a/src/GitVersionCore/Logging/Log.cs b/src/GitVersionCore/Logging/Log.cs index 5603ec9c76..f4c42395a4 100644 --- a/src/GitVersionCore/Logging/Log.cs +++ b/src/GitVersionCore/Logging/Log.cs @@ -10,7 +10,7 @@ namespace GitVersion.Logging public sealed class Log : ILog { private IEnumerable appenders; - private readonly Regex ObscurePasswordRegex = new Regex("(https?://)(.+)(:.+@)", RegexOptions.Compiled); + private readonly Regex obscurePasswordRegex = new Regex("(https?://)(.+)(:.+@)", RegexOptions.Compiled); private readonly StringBuilder sb; private string indent = string.Empty; @@ -70,7 +70,7 @@ public override string ToString() private string FormatMessage(string message, string level) { - var obscuredMessage = ObscurePasswordRegex.Replace(message, "$1$2:*******@"); + var obscuredMessage = obscurePasswordRegex.Replace(message, "$1$2:*******@"); return string.Format(CultureInfo.InvariantCulture, "{0}{1} [{2:MM/dd/yy H:mm:ss:ff}] {3}", indent, level, DateTime.Now, obscuredMessage); } } diff --git a/src/GitVersionCore/Logging/LogExtensions.cs b/src/GitVersionCore/Logging/LogExtensions.cs index 75aa8f9826..5bdff2e95d 100644 --- a/src/GitVersionCore/Logging/LogExtensions.cs +++ b/src/GitVersionCore/Logging/LogExtensions.cs @@ -164,9 +164,9 @@ public static IDisposable WithVerbosity(this ILog log, Verbosity verbosity) return Disposable.Create(() => log.Verbosity = lastVerbosity); } - public static Verbosity GetVerbosityForLevel(LogLevel level) => verbosityMaps[level]; + public static Verbosity GetVerbosityForLevel(LogLevel level) => VerbosityMaps[level]; - private static readonly IDictionary verbosityMaps = new Dictionary + private static readonly IDictionary VerbosityMaps = new Dictionary { { LogLevel.Debug, Verbosity.Diagnostic }, { LogLevel.Info, Verbosity.Normal }, diff --git a/src/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs b/src/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs index eabd568321..484c6d5946 100644 --- a/src/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs +++ b/src/GitVersionCore/OutputFormatters/BuildOutputFormatter.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using GitVersion.OutputVariables; -using GitVersion.Common; namespace GitVersion.OutputFormatters { diff --git a/src/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs b/src/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs index b4fdbd5009..cf4b52cb04 100644 --- a/src/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs +++ b/src/GitVersionCore/OutputFormatters/JsonOutputFormatter.cs @@ -2,7 +2,7 @@ using System.Linq; using System.Text; using GitVersion.OutputVariables; -using GitVersion.Helpers; +using GitVersion.Extensions; namespace GitVersion.OutputFormatters { diff --git a/src/GitVersionCore/OutputVariables/VariableProvider.cs b/src/GitVersionCore/OutputVariables/VariableProvider.cs index f23c416c69..573d646d4b 100644 --- a/src/GitVersionCore/OutputVariables/VariableProvider.cs +++ b/src/GitVersionCore/OutputVariables/VariableProvider.cs @@ -5,18 +5,18 @@ using GitVersion.VersioningModes; using GitVersion.Configuration; using GitVersion.Helpers; -using GitVersion.Logging; namespace GitVersion.OutputVariables { public class VariableProvider : IVariableProvider { - private readonly ILog log; + private readonly INextVersionCalculator nextVersionCalculator; - public VariableProvider(ILog log) + public VariableProvider(INextVersionCalculator nextVersionCalculator) { - this.log = log; + this.nextVersionCalculator = nextVersionCalculator ?? throw new ArgumentNullException(nameof(nextVersionCalculator)); } + public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, EffectiveConfiguration config, bool isCurrentCommitTagged) { var isContinuousDeploymentMode = config.VersioningMode == VersioningMode.ContinuousDeployment && !isCurrentCommitTagged; @@ -26,7 +26,6 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti // Continuous Deployment always requires a pre-release tag unless the commit is tagged if (!semanticVersion.PreReleaseTag.HasTag()) { - var nextVersionCalculator = new NextVersionCalculator(log); semanticVersion.PreReleaseTag.Name = nextVersionCalculator.GetBranchSpecificTag(config, semanticVersion.BuildMetaData.Branch, null); if (string.IsNullOrEmpty(semanticVersion.PreReleaseTag.Name)) { @@ -54,13 +53,13 @@ public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, Effecti var semverFormatValues = new SemanticVersionFormatValues(semanticVersion, config); - string informationalVersion = CheckAndFormatString(config.AssemblyInformationalFormat, semverFormatValues, + var informationalVersion = CheckAndFormatString(config.AssemblyInformationalFormat, semverFormatValues, semverFormatValues.DefaultInformationalVersion, "AssemblyInformationalVersion"); - string assemblyFileSemVer = CheckAndFormatString(config.AssemblyFileVersioningFormat, semverFormatValues, + var assemblyFileSemVer = CheckAndFormatString(config.AssemblyFileVersioningFormat, semverFormatValues, semverFormatValues.AssemblyFileSemVer, "AssemblyFileVersioningFormat"); - string assemblySemVer = CheckAndFormatString(config.AssemblyVersioningFormat, semverFormatValues, + var assemblySemVer = CheckAndFormatString(config.AssemblyVersioningFormat, semverFormatValues, semverFormatValues.AssemblySemVer, "AssemblyVersioningFormat"); var variables = new VersionVariables( diff --git a/src/GitVersionCore/OutputVariables/VersionVariables.cs b/src/GitVersionCore/OutputVariables/VersionVariables.cs index 869457ff94..fcc5bcc426 100644 --- a/src/GitVersionCore/OutputVariables/VersionVariables.cs +++ b/src/GitVersionCore/OutputVariables/VersionVariables.cs @@ -4,7 +4,6 @@ using System.IO; using System.Linq; using YamlDotNet.Serialization; -using GitVersion.Common; namespace GitVersion.OutputVariables { @@ -154,16 +153,12 @@ public static VersionVariables FromDictionary(IEnumerable>(reader); - var versionVariables = FromDictionary(dictionary); - versionVariables.FileName = filePath; - return versionVariables; - } - } + using var stream = fileSystem.OpenRead(filePath); + using var reader = new StreamReader(stream); + var dictionary = new Deserializer().Deserialize>(reader); + var versionVariables = FromDictionary(dictionary); + versionVariables.FileName = filePath; + return versionVariables; } public bool TryGetValue(string variable, out string variableValue) diff --git a/src/GitVersionCore/SemanticVersionFormatValues.cs b/src/GitVersionCore/SemanticVersionFormatValues.cs deleted file mode 100644 index 876ee99076..0000000000 --- a/src/GitVersionCore/SemanticVersionFormatValues.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System.Globalization; -using GitVersion.Configuration; -using GitVersion.Extensions; - -namespace GitVersion -{ - public class SemanticVersionFormatValues - { - private readonly SemanticVersion _semver; - private readonly EffectiveConfiguration _config; - - public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguration config) - { - _semver = semver; - _config = config; - } - - public string Major => _semver.Major.ToString(); - - public string Minor => _semver.Minor.ToString(); - - public string Patch => _semver.Patch.ToString(); - - public string PreReleaseTag => _semver.PreReleaseTag; - - public string PreReleaseTagWithDash => _semver.PreReleaseTag.HasTag() ? "-" + _semver.PreReleaseTag : null; - - public string PreReleaseLabel => _semver.PreReleaseTag.HasTag() ? _semver.PreReleaseTag.Name : null; - - public string PreReleaseNumber => _semver.PreReleaseTag.HasTag() ? _semver.PreReleaseTag.Number.ToString() : null; - - public string WeightedPreReleaseNumber => _semver.PreReleaseTag.HasTag() ? (_semver.PreReleaseTag.Number + _config.PreReleaseWeight).ToString() : null; - - public string BuildMetaData => _semver.BuildMetaData; - - public string BuildMetaDataPadded => _semver.BuildMetaData.ToString("p" + _config.BuildMetaDataPadding); - - public string FullBuildMetaData => _semver.BuildMetaData.ToString("f"); - - public string MajorMinorPatch => $"{_semver.Major}.{_semver.Minor}.{_semver.Patch}"; - - public string SemVer => _semver.ToString(); - - public string LegacySemVer => _semver.ToString("l"); - - public string LegacySemVerPadded => _semver.ToString("lp" + _config.LegacySemVerPadding); - - public string AssemblySemVer => _semver.GetAssemblyVersion(_config.AssemblyVersioningScheme); - - public string AssemblyFileSemVer => _semver.GetAssemblyFileVersion(_config.AssemblyFileVersioningScheme); - - public string FullSemVer => _semver.ToString("f"); - - public string BranchName => _semver.BuildMetaData.Branch; - - public string Sha => _semver.BuildMetaData.Sha; - - public string ShortSha => _semver.BuildMetaData.ShortSha; - - public string CommitDate => _semver.BuildMetaData.CommitDate.UtcDateTime.ToString(_config.CommitDateFormat, CultureInfo.InvariantCulture); - - // TODO When NuGet 3 is released: public string NuGetVersionV3 { get { return ??; } } - - public string NuGetVersionV2 => LegacySemVerPadded.ToLower(); - - public string NuGetVersion => NuGetVersionV2; - - public string NuGetPreReleaseTagV2 => _semver.PreReleaseTag.HasTag() ? _semver.PreReleaseTag.ToString("lp").ToLower() : null; - - public string NuGetPreReleaseTag => NuGetPreReleaseTagV2; - - public string DefaultInformationalVersion => _semver.ToString("i"); - - public string VersionSourceSha => _semver.BuildMetaData.VersionSourceSha; - - public string CommitsSinceVersionSource => _semver.BuildMetaData.CommitsSinceVersionSource.ToString(CultureInfo.InvariantCulture); - - public string CommitsSinceVersionSourcePadded => _semver.BuildMetaData.CommitsSinceVersionSource.ToString(CultureInfo.InvariantCulture).PadLeft(_config.CommitsSinceVersionSourcePadding, '0'); - } -} diff --git a/src/GitVersionCore/SemanticVersion.cs b/src/GitVersionCore/SemanticVersioning/SemanticVersion.cs similarity index 99% rename from src/GitVersionCore/SemanticVersion.cs rename to src/GitVersionCore/SemanticVersioning/SemanticVersion.cs index 27052ed83f..13c31be697 100644 --- a/src/GitVersionCore/SemanticVersion.cs +++ b/src/GitVersionCore/SemanticVersioning/SemanticVersion.cs @@ -8,7 +8,7 @@ public class SemanticVersion : IFormattable, IComparable { public static SemanticVersion Empty = new SemanticVersion(); - private static Regex ParseSemVer = new Regex( + private static readonly Regex ParseSemVer = new Regex( @"^(?(?\d+)(\.(?\d+))(\.(?\d+))?)(\.(?\d+))?(-(?[^\+]*))?(\+(?.*))?$", RegexOptions.Compiled); diff --git a/src/GitVersionCore/SemanticVersionBuildMetaData.cs b/src/GitVersionCore/SemanticVersioning/SemanticVersionBuildMetaData.cs similarity index 85% rename from src/GitVersionCore/SemanticVersionBuildMetaData.cs rename to src/GitVersionCore/SemanticVersioning/SemanticVersionBuildMetaData.cs index dbc62b2709..cff5dd1b33 100644 --- a/src/GitVersionCore/SemanticVersionBuildMetaData.cs +++ b/src/GitVersionCore/SemanticVersioning/SemanticVersionBuildMetaData.cs @@ -6,11 +6,11 @@ namespace GitVersion { public class SemanticVersionBuildMetaData : IFormattable, IEquatable { - private static Regex ParseRegex = new Regex( + private static readonly Regex ParseRegex = new Regex( @"(?\d+)?(\.?Branch(Name)?\.(?[^\.]+))?(\.?Sha?\.(?[^\.]+))?(?.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase); - private static LambdaEqualityHelper equalityHelper = + private static readonly LambdaEqualityHelper EqualityHelper = new LambdaEqualityHelper(x => x.CommitsSinceTag, x => x.Branch, x => x.Sha); public int? CommitsSinceTag; @@ -57,12 +57,12 @@ public override bool Equals(object obj) public bool Equals(SemanticVersionBuildMetaData other) { - return equalityHelper.Equals(this, other); + return EqualityHelper.Equals(this, other); } public override int GetHashCode() { - return equalityHelper.GetHashCode(this); + return EqualityHelper.GetHashCode(this); } public override string ToString() @@ -104,19 +104,14 @@ public string ToString(string format, IFormatProvider formatProvider = null) return CommitsSinceTag != null ? CommitsSinceTag.Value.ToString("D" + padding) : string.Empty; } - - switch (format.ToLower()) + + return format.ToLower() switch { - case "b": - return CommitsSinceTag.ToString(); - case "s": - return $"{CommitsSinceTag}{(string.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}".TrimStart('.'); - case "f": - return $"{CommitsSinceTag}{(string.IsNullOrEmpty(Branch) ? null : ".Branch." + FormatMetaDataPart(Branch))}{(string.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}{(string.IsNullOrEmpty(OtherMetaData) ? null : "." + FormatMetaDataPart(OtherMetaData))}" - .TrimStart('.'); - default: - throw new ArgumentException("Unrecognised format", nameof(format)); - } + "b" => CommitsSinceTag.ToString(), + "s" => $"{CommitsSinceTag}{(string.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}".TrimStart('.'), + "f" => $"{CommitsSinceTag}{(string.IsNullOrEmpty(Branch) ? null : ".Branch." + FormatMetaDataPart(Branch))}{(string.IsNullOrEmpty(Sha) ? null : ".Sha." + Sha)}{(string.IsNullOrEmpty(OtherMetaData) ? null : "." + FormatMetaDataPart(OtherMetaData))}".TrimStart('.'), + _ => throw new ArgumentException("Unrecognised format", nameof(format)) + }; } public static bool operator ==(SemanticVersionBuildMetaData left, SemanticVersionBuildMetaData right) diff --git a/src/GitVersionCore/SemanticVersionExtensions.cs b/src/GitVersionCore/SemanticVersioning/SemanticVersionExtensions.cs similarity index 100% rename from src/GitVersionCore/SemanticVersionExtensions.cs rename to src/GitVersionCore/SemanticVersioning/SemanticVersionExtensions.cs diff --git a/src/GitVersionCore/SemanticVersioning/SemanticVersionFormatValues.cs b/src/GitVersionCore/SemanticVersioning/SemanticVersionFormatValues.cs new file mode 100644 index 0000000000..9ba80b4be7 --- /dev/null +++ b/src/GitVersionCore/SemanticVersioning/SemanticVersionFormatValues.cs @@ -0,0 +1,80 @@ +using System.Globalization; +using GitVersion.Configuration; +using GitVersion.Extensions; + +namespace GitVersion +{ + public class SemanticVersionFormatValues + { + private readonly SemanticVersion semver; + private readonly EffectiveConfiguration config; + + public SemanticVersionFormatValues(SemanticVersion semver, EffectiveConfiguration config) + { + this.semver = semver; + this.config = config; + } + + public string Major => semver.Major.ToString(); + + public string Minor => semver.Minor.ToString(); + + public string Patch => semver.Patch.ToString(); + + public string PreReleaseTag => semver.PreReleaseTag; + + public string PreReleaseTagWithDash => semver.PreReleaseTag.HasTag() ? "-" + semver.PreReleaseTag : null; + + public string PreReleaseLabel => semver.PreReleaseTag.HasTag() ? semver.PreReleaseTag.Name : null; + + public string PreReleaseNumber => semver.PreReleaseTag.HasTag() ? semver.PreReleaseTag.Number.ToString() : null; + + public string WeightedPreReleaseNumber => semver.PreReleaseTag.HasTag() ? (semver.PreReleaseTag.Number + config.PreReleaseWeight).ToString() : null; + + public string BuildMetaData => semver.BuildMetaData; + + public string BuildMetaDataPadded => semver.BuildMetaData.ToString("p" + config.BuildMetaDataPadding); + + public string FullBuildMetaData => semver.BuildMetaData.ToString("f"); + + public string MajorMinorPatch => $"{semver.Major}.{semver.Minor}.{semver.Patch}"; + + public string SemVer => semver.ToString(); + + public string LegacySemVer => semver.ToString("l"); + + public string LegacySemVerPadded => semver.ToString("lp" + config.LegacySemVerPadding); + + public string AssemblySemVer => semver.GetAssemblyVersion(config.AssemblyVersioningScheme); + + public string AssemblyFileSemVer => semver.GetAssemblyFileVersion(config.AssemblyFileVersioningScheme); + + public string FullSemVer => semver.ToString("f"); + + public string BranchName => semver.BuildMetaData.Branch; + + public string Sha => semver.BuildMetaData.Sha; + + public string ShortSha => semver.BuildMetaData.ShortSha; + + public string CommitDate => semver.BuildMetaData.CommitDate.UtcDateTime.ToString(config.CommitDateFormat, CultureInfo.InvariantCulture); + + // TODO When NuGet 3 is released: public string NuGetVersionV3 { get { return ??; } } + + public string NuGetVersionV2 => LegacySemVerPadded.ToLower(); + + public string NuGetVersion => NuGetVersionV2; + + public string NuGetPreReleaseTagV2 => semver.PreReleaseTag.HasTag() ? semver.PreReleaseTag.ToString("lp").ToLower() : null; + + public string NuGetPreReleaseTag => NuGetPreReleaseTagV2; + + public string DefaultInformationalVersion => semver.ToString("i"); + + public string VersionSourceSha => semver.BuildMetaData.VersionSourceSha; + + public string CommitsSinceVersionSource => semver.BuildMetaData.CommitsSinceVersionSource.ToString(CultureInfo.InvariantCulture); + + public string CommitsSinceVersionSourcePadded => semver.BuildMetaData.CommitsSinceVersionSource.ToString(CultureInfo.InvariantCulture).PadLeft(config.CommitsSinceVersionSourcePadding, '0'); + } +} diff --git a/src/GitVersionCore/SemanticVersionPreReleaseTag.cs b/src/GitVersionCore/SemanticVersioning/SemanticVersionPreReleaseTag.cs similarity index 91% rename from src/GitVersionCore/SemanticVersionPreReleaseTag.cs rename to src/GitVersionCore/SemanticVersioning/SemanticVersionPreReleaseTag.cs index 396e1879ca..303e3025b4 100644 --- a/src/GitVersionCore/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersionCore/SemanticVersioning/SemanticVersionPreReleaseTag.cs @@ -8,7 +8,7 @@ namespace GitVersion public class SemanticVersionPreReleaseTag : IFormattable, IComparable, IEquatable { - private static LambdaEqualityHelper equalityHelper = + private static readonly LambdaEqualityHelper EqualityHelper = new LambdaEqualityHelper(x => x.Name, x => x.Number); public SemanticVersionPreReleaseTag() @@ -37,12 +37,12 @@ public override bool Equals(object obj) public bool Equals(SemanticVersionPreReleaseTag other) { - return equalityHelper.Equals(this, other); + return EqualityHelper.Equals(this, other); } public override int GetHashCode() { - return equalityHelper.GetHashCode(this); + return EqualityHelper.GetHashCode(this); } public static bool operator ==(SemanticVersionPreReleaseTag left, SemanticVersionPreReleaseTag right) @@ -166,16 +166,12 @@ public string ToString(string format, IFormatProvider formatProvider = null) return Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString("D" + padding)) : FormatLegacy(GetLegacyName()); } - - switch (format) + return format switch { - case "t": - return Number.HasValue ? $"{Name}.{Number}" : Name; - case "l": - return Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString()) : FormatLegacy(GetLegacyName()); - default: - throw new ArgumentException("Unknown format", nameof(format)); - } + "t" => (Number.HasValue ? $"{Name}.{Number}" : Name), + "l" => (Number.HasValue ? FormatLegacy(GetLegacyName(), Number.Value.ToString()) : FormatLegacy(GetLegacyName())), + _ => throw new ArgumentException("Unknown format", nameof(format)) + }; } private string FormatLegacy(string tag, string number = "") diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs index 84b2c1a9c1..847f79b52b 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs @@ -10,12 +10,12 @@ namespace GitVersion.VersionCalculation public class BaseVersionCalculator : IBaseVersionCalculator { private readonly ILog log; - private readonly BaseVersionStrategy[] strategies; + private readonly IVersionStrategy[] strategies; - public BaseVersionCalculator(ILog log, params BaseVersionStrategy[] strategies) + public BaseVersionCalculator(ILog log, IEnumerable strategies) { - this.log = log; - this.strategies = strategies; + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.strategies = strategies?.ToArray() ?? Array.Empty(); } public BaseVersion GetBaseVersion(GitVersionContext context) @@ -104,7 +104,7 @@ private void FixTheBaseVersionSourceOfMergeMessageStrategyIfReleaseBranchWasMerg foreach (var baseVersion in baseVersions) { if (baseVersion.Version.Source.Contains( - MergeMessageBaseVersionStrategy.MergeMessageStrategyPrefix) + MergeMessageVersionStrategy.MergeMessageStrategyPrefix) && baseVersion.Version.Source.Contains("Merge branch") && baseVersion.Version.Source.Contains("release")) { diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs index e03be9f63c..b0460eb6e2 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/BaseVersion.cs @@ -1,10 +1,10 @@ -using LibGit2Sharp; +using LibGit2Sharp; namespace GitVersion.VersionCalculation.BaseVersionCalculators { public class BaseVersion { - private GitVersionContext _context; + private readonly GitVersionContext context; public BaseVersion(GitVersionContext context, string source, bool shouldIncrement, SemanticVersion semanticVersion, Commit baseVersionSource, string branchNameOverride) { @@ -13,7 +13,7 @@ public BaseVersion(GitVersionContext context, string source, bool shouldIncremen SemanticVersion = semanticVersion; BaseVersionSource = baseVersionSource; BranchNameOverride = branchNameOverride; - _context = context; + this.context = context; } public string Source { get; private set; } @@ -28,7 +28,7 @@ public BaseVersion(GitVersionContext context, string source, bool shouldIncremen public override string ToString() { - return $"{Source}: {SemanticVersion.ToString("f")} with commit count source {(BaseVersionSource == null ? "External Source" : BaseVersionSource.Sha)} (Incremented: {(ShouldIncrement ? BaseVersionCalculator.MaybeIncrement(_context, this).ToString("t") : "None")})"; + return $"{Source}: {SemanticVersion.ToString("f")} with commit count source {(BaseVersionSource == null ? "External Source" : BaseVersionSource.Sha)} (Incremented: {(ShouldIncrement ? BaseVersionCalculator.MaybeIncrement(context, this).ToString("t") : "None")})"; } } } diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionBaseVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs similarity index 77% rename from src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionBaseVersionStrategy.cs rename to src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs index 0fbe8e6559..41a676e174 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionBaseVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/ConfigNextVersionVersionStrategy.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; namespace GitVersion.VersionCalculation.BaseVersionCalculators { @@ -7,9 +7,9 @@ namespace GitVersion.VersionCalculation.BaseVersionCalculators /// BaseVersionSource is null. /// Does not increment. /// - public class ConfigNextVersionBaseVersionStrategy : BaseVersionStrategy + public class ConfigNextVersionVersionStrategy : IVersionStrategy { - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { if (string.IsNullOrEmpty(context.Configuration.NextVersion) || context.IsCurrentCommitTagged) yield break; @@ -17,4 +17,4 @@ public override IEnumerable GetVersions(GitVersionContext context) yield return new BaseVersion(context, "NextVersion in GitVersion configuration file", false, semanticVersion, null, null); } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/VersionCalculation/FallbackBaseVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs similarity index 78% rename from src/GitVersionCore/VersionCalculation/FallbackBaseVersionStrategy.cs rename to src/GitVersionCore/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs index 46d487aa51..ba01948c7a 100644 --- a/src/GitVersionCore/VersionCalculation/FallbackBaseVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/FallbackVersionStrategy.cs @@ -1,19 +1,18 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using GitVersion.VersionCalculation.BaseVersionCalculators; using GitVersion.Exceptions; using LibGit2Sharp; -namespace GitVersion.VersionCalculation +namespace GitVersion.VersionCalculation.BaseVersionCalculators { /// /// Version is 0.1.0. /// BaseVersionSource is the "root" commit reachable from the current commit. /// Does not increment. /// - public class FallbackBaseVersionStrategy : BaseVersionStrategy + public class FallbackVersionStrategy : IVersionStrategy { - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { Commit baseVersionSource; var currentBranchTip = context.CurrentBranch.Tip; @@ -33,4 +32,4 @@ public override IEnumerable GetVersions(GitVersionContext context) yield return new BaseVersion(context, "Fallback base version", false, new SemanticVersion(minor : 1), baseVersionSource, null); } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs similarity index 92% rename from src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs rename to src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs index 48c025e51f..54459dbc08 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageVersionStrategy.cs @@ -2,8 +2,9 @@ using System.Linq; using System.Text.RegularExpressions; using LibGit2Sharp; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Configuration; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation.BaseVersionCalculators { @@ -12,9 +13,9 @@ namespace GitVersion.VersionCalculation.BaseVersionCalculators /// BaseVersionSource is the commit where the message was found. /// Increments if PreventIncrementForMergedBranchVersion (from the branch config) is false. /// - public class MergeMessageBaseVersionStrategy : BaseVersionStrategy + public class MergeMessageVersionStrategy : IVersionStrategy { - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { var commitsPriorToThan = context.CurrentBranch .CommitsPriorToThan(context.CurrentCommit.When()); diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs index a19304fd3e..fc5a3f0c7c 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TaggedCommitVersionStrategy.cs @@ -1,8 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using LibGit2Sharp; -using GitVersion.Helpers; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation.BaseVersionCalculators { @@ -11,16 +11,17 @@ namespace GitVersion.VersionCalculation.BaseVersionCalculators /// BaseVersionSource is the tag's commit. /// Increments if the tag is not the current commit. /// - public class TaggedCommitVersionStrategy : BaseVersionStrategy + public class TaggedCommitVersionStrategy : IVersionStrategy { - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { return GetTaggedVersions(context, context.CurrentBranch, context.CurrentCommit.When()); } public IEnumerable GetTaggedVersions(GitVersionContext context, Branch currentBranch, DateTimeOffset? olderThan) { - var allTags = GitRepoMetadataProvider.GetValidVersionTags(context.Repository, context.Configuration.GitTagPrefix, olderThan); + var gitRepoMetadataProvider = new GitRepoMetadataProvider(context.Repository, context.Log, context.FullConfiguration); + var allTags = gitRepoMetadataProvider.GetValidVersionTags(context.Repository, context.Configuration.GitTagPrefix, olderThan); var tagsOnBranch = currentBranch .Commits @@ -70,4 +71,4 @@ public VersionTaggedCommit(Commit commit, SemanticVersion semVer, string tag) } } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/VersionCalculation/TrackReleaseBranchesVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs similarity index 85% rename from src/GitVersionCore/VersionCalculation/TrackReleaseBranchesVersionStrategy.cs rename to src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs index daf09b87d4..07e078708f 100644 --- a/src/GitVersionCore/VersionCalculation/TrackReleaseBranchesVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/TrackReleaseBranchesVersionStrategy.cs @@ -1,17 +1,16 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using GitVersion.VersionCalculation.BaseVersionCalculators; using LibGit2Sharp; -using GitVersion.Helpers; +using GitVersion.Extensions; -namespace GitVersion.VersionCalculation +namespace GitVersion.VersionCalculation.BaseVersionCalculators { /// /// Active only when the branch is marked as IsDevelop. /// Two different algorithms (results are merged): /// - /// Using : + /// Using : /// Version is that of any child branches marked with IsReleaseBranch (except if they have no commits of their own). /// BaseVersionSource is the commit where the child branch was created. /// Always increments. @@ -23,12 +22,12 @@ namespace GitVersion.VersionCalculation /// Increments if the tag is not the current commit (same as base strategy). /// /// - public class TrackReleaseBranchesVersionStrategy : BaseVersionStrategy + public class TrackReleaseBranchesVersionStrategy : IVersionStrategy { - private VersionInBranchNameBaseVersionStrategy releaseVersionStrategy = new VersionInBranchNameBaseVersionStrategy(); - private TaggedCommitVersionStrategy taggedCommitVersionStrategy = new TaggedCommitVersionStrategy(); + private readonly VersionInBranchNameVersionStrategy releaseVersionStrategy = new VersionInBranchNameVersionStrategy(); + private readonly TaggedCommitVersionStrategy taggedCommitVersionStrategy = new TaggedCommitVersionStrategy(); - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { if (context.Configuration.TracksReleaseBranches) { diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameBaseVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs similarity index 90% rename from src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameBaseVersionStrategy.cs rename to src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs index 8aa487806f..6e7d7dd84a 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameBaseVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; using LibGit2Sharp; -using GitVersion.Helpers; +using GitVersion.Configuration; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation.BaseVersionCalculators { @@ -10,9 +11,9 @@ namespace GitVersion.VersionCalculation.BaseVersionCalculators /// BaseVersionSource is the commit where the branch was branched from its parent. /// Does not increment. /// - public class VersionInBranchNameBaseVersionStrategy : BaseVersionStrategy + public class VersionInBranchNameVersionStrategy : IVersionStrategy { - public override IEnumerable GetVersions(GitVersionContext context) + public virtual IEnumerable GetVersions(GitVersionContext context) { var currentBranch = context.CurrentBranch; var tagPrefixRegex = context.Configuration.GitTagPrefix; diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionStrategy.cs deleted file mode 100644 index d26389d62e..0000000000 --- a/src/GitVersionCore/VersionCalculation/BaseVersionStrategy.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Collections.Generic; -using GitVersion.VersionCalculation.BaseVersionCalculators; - -namespace GitVersion.VersionCalculation -{ - public abstract class BaseVersionStrategy - { - /// - /// Calculates the values for the given . - /// - /// - /// The context for calculating the . - /// - /// - /// An of the base version values found by the strategy. - /// - public abstract IEnumerable GetVersions(GitVersionContext context); - } -} \ No newline at end of file diff --git a/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs index 92a66e235b..55d9247c69 100644 --- a/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs @@ -2,8 +2,8 @@ namespace GitVersion.VersionCalculation { - internal interface IMainlineVersionCalculator + public interface IMainlineVersionCalculator { SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersionContext context); } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs b/src/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs index aa027fd8ec..c574d6651e 100644 --- a/src/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/IMetaDataCalculator.cs @@ -1,4 +1,4 @@ -using LibGit2Sharp; +using LibGit2Sharp; namespace GitVersion.VersionCalculation { @@ -6,4 +6,4 @@ public interface IMetaDataCalculator { SemanticVersionBuildMetaData Create(Commit baseVersionSource, GitVersionContext context); } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/VersionCalculation/INextVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/INextVersionCalculator.cs new file mode 100644 index 0000000000..0167068618 --- /dev/null +++ b/src/GitVersionCore/VersionCalculation/INextVersionCalculator.cs @@ -0,0 +1,10 @@ +using GitVersion.Configuration; + +namespace GitVersion.VersionCalculation +{ + public interface INextVersionCalculator + { + SemanticVersion FindVersion(GitVersionContext context); + string GetBranchSpecificTag(EffectiveConfiguration configuration, string branchFriendlyName, string branchNameOverride); + } +} diff --git a/src/GitVersionCore/VersionCalculation/IVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/IVersionStrategy.cs new file mode 100644 index 0000000000..d023bbfe7c --- /dev/null +++ b/src/GitVersionCore/VersionCalculation/IVersionStrategy.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using GitVersion.VersionCalculation.BaseVersionCalculators; + +namespace GitVersion.VersionCalculation +{ + public interface IVersionStrategy + { + /// + /// Calculates the values for the given . + /// + /// + /// The context for calculating the . + /// + /// + /// An of the base version values found by the strategy. + /// + IEnumerable GetVersions(GitVersionContext context); + } +} diff --git a/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs index eea69d413b..3678369055 100644 --- a/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs @@ -4,21 +4,21 @@ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; -using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Configuration; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation { internal class MainlineVersionCalculator : IMainlineVersionCalculator { - private IMetaDataCalculator metaDataCalculator; + private readonly IMetaDataCalculator metaDataCalculator; private readonly ILog log; - public MainlineVersionCalculator(IMetaDataCalculator metaDataCalculator, ILog log) + public MainlineVersionCalculator(ILog log, IMetaDataCalculator metaDataCalculator) { - this.metaDataCalculator = metaDataCalculator; - this.log = log; + this.metaDataCalculator = metaDataCalculator ?? throw new ArgumentNullException(nameof(metaDataCalculator)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); } public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersionContext context) diff --git a/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs b/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs index e7e8d89053..a623bb945f 100644 --- a/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs @@ -1,7 +1,7 @@ using System.Linq; using LibGit2Sharp; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation { diff --git a/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs index 0455260ded..835642d6cb 100644 --- a/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs @@ -1,31 +1,28 @@ +using System; using System.Linq; using System.Text.RegularExpressions; using GitVersion.VersionCalculation.BaseVersionCalculators; using GitVersion.VersioningModes; using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.Logging; +using GitVersion.Extensions; namespace GitVersion.VersionCalculation { - public class NextVersionCalculator + public class NextVersionCalculator : INextVersionCalculator { private readonly ILog log; - private IBaseVersionCalculator baseVersionFinder; - private IMetaDataCalculator metaDataCalculator; + private readonly IBaseVersionCalculator baseVersionCalculator; + private readonly IMainlineVersionCalculator mainlineVersionCalculator; + private readonly IMetaDataCalculator metaDataCalculator; - public NextVersionCalculator(ILog log, IBaseVersionCalculator baseVersionCalculator = null, IMetaDataCalculator metaDataCalculator = null) + public NextVersionCalculator(ILog log, IMetaDataCalculator metaDataCalculator, IBaseVersionCalculator baseVersionCalculator, IMainlineVersionCalculator mainlineVersionCalculator) { - this.log = log; - this.metaDataCalculator = metaDataCalculator ?? new MetaDataCalculator(); - baseVersionFinder = baseVersionCalculator ?? - new BaseVersionCalculator(log, - new FallbackBaseVersionStrategy(), - new ConfigNextVersionBaseVersionStrategy(), - new TaggedCommitVersionStrategy(), - new MergeMessageBaseVersionStrategy(), - new VersionInBranchNameBaseVersionStrategy(), - new TrackReleaseBranchesVersionStrategy()); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.metaDataCalculator = metaDataCalculator ?? throw new ArgumentNullException(nameof(metaDataCalculator)); + + this.baseVersionCalculator = baseVersionCalculator ?? throw new ArgumentNullException(nameof(baseVersionCalculator)); + this.mainlineVersionCalculator = mainlineVersionCalculator ?? throw new ArgumentNullException(nameof(mainlineVersionCalculator)); } public SemanticVersion FindVersion(GitVersionContext context) @@ -45,12 +42,11 @@ public SemanticVersion FindVersion(GitVersionContext context) taggedSemanticVersion = semanticVersion; } - var baseVersion = baseVersionFinder.GetBaseVersion(context); + var baseVersion = baseVersionCalculator.GetBaseVersion(context); SemanticVersion semver; if (context.Configuration.VersioningMode == VersioningMode.Mainline) { - var mainlineMode = new MainlineVersionCalculator(metaDataCalculator, log); - semver = mainlineMode.FindMainlineModeVersion(baseVersion, context); + semver = mainlineVersionCalculator.FindMainlineModeVersion(baseVersion, context); } else { diff --git a/src/GitVersionCore/VersionFilters/MinDateVersionFilter.cs b/src/GitVersionCore/VersionFilters/MinDateVersionFilter.cs index aac74905a9..7c2324327d 100644 --- a/src/GitVersionCore/VersionFilters/MinDateVersionFilter.cs +++ b/src/GitVersionCore/VersionFilters/MinDateVersionFilter.cs @@ -1,6 +1,6 @@ using System; using GitVersion.VersionCalculation.BaseVersionCalculators; -using GitVersion.Helpers; +using GitVersion.Extensions; namespace GitVersion.VersionFilters { diff --git a/src/GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs b/src/GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs index ebb890172c..7e78e4fbc2 100644 --- a/src/GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs +++ b/src/GitVersionCore/VersioningModes/ContinuousDeliveryMode.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using LibGit2Sharp; -using GitVersion.Helpers; +using GitVersion.Extensions; namespace GitVersion.VersioningModes { diff --git a/src/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs b/src/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs index 77e773e3cb..0609da116e 100644 --- a/src/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs +++ b/src/GitVersionCore/VersioningModes/ContinuousDeploymentMode.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; - +using System.Collections.Generic; using LibGit2Sharp; namespace GitVersion.VersioningModes @@ -11,4 +10,4 @@ public override SemanticVersionPreReleaseTag GetPreReleaseTag(GitVersionContext return context.Configuration.Tag + "." + numberOfCommits; } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/VersioningModes/VersioningModeBase.cs b/src/GitVersionCore/VersioningModes/VersioningModeBase.cs index 1f9a166cee..23004a493a 100644 --- a/src/GitVersionCore/VersioningModes/VersioningModeBase.cs +++ b/src/GitVersionCore/VersioningModes/VersioningModeBase.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; - +using System.Collections.Generic; using LibGit2Sharp; namespace GitVersion.VersioningModes diff --git a/src/GitVersionCore/VersioningModes/VersioningModeExtension.cs b/src/GitVersionCore/VersioningModes/VersioningModeExtension.cs index 9fa35d522a..fe2594d50a 100644 --- a/src/GitVersionCore/VersioningModes/VersioningModeExtension.cs +++ b/src/GitVersionCore/VersioningModes/VersioningModeExtension.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace GitVersion.VersioningModes { @@ -6,15 +6,12 @@ public static class VersioningModeExtension { public static VersioningModeBase GetInstance(this VersioningMode _this) { - switch (_this) + return _this switch { - case VersioningMode.ContinuousDelivery: - return new ContinuousDeliveryMode(); - case VersioningMode.ContinuousDeployment: - return new ContinuousDeploymentMode(); - default: - throw new ArgumentException("No instance exists for this versioning mode."); - } + VersioningMode.ContinuousDelivery => (VersioningModeBase) new ContinuousDeliveryMode(), + VersioningMode.ContinuousDeployment => new ContinuousDeploymentMode(), + _ => throw new ArgumentException("No instance exists for this versioning mode.") + }; } } -} \ No newline at end of file +} diff --git a/src/GitVersionExe.Tests/ArgumentParserTests.cs b/src/GitVersionExe.Tests/ArgumentParserTests.cs index 65eb830a50..d2a146a68d 100644 --- a/src/GitVersionExe.Tests/ArgumentParserTests.cs +++ b/src/GitVersionExe.Tests/ArgumentParserTests.cs @@ -1,4 +1,3 @@ -using System; using GitVersion; using NUnit.Framework; using Shouldly; @@ -20,16 +19,16 @@ public void SetUp() } [Test] - public void Empty_means_use_current_directory() + public void EmptyMeansUseCurrentDirectory() { var arguments = argumentParser.ParseArguments(""); - arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); + arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] - public void Single_means_use_as_target_directory() + public void SingleMeansUseAsTargetDirectory() { var arguments = argumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); @@ -38,16 +37,16 @@ public void Single_means_use_as_target_directory() } [Test] - public void No_path_and_logfile_should_use_current_directory_TargetDirectory() + public void NoPathAndLogfileShouldUseCurrentDirectoryTargetDirectory() { var arguments = argumentParser.ParseArguments("-l logFilePath"); - arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); + arguments.TargetPath.ShouldBe(System.Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] - public void H_means_IsHelp() + public void HMeansIsHelp() { var arguments = argumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); @@ -63,7 +62,7 @@ public void Exec() } [Test] - public void Exec_with_args() + public void ExecWithArgs() { var arguments = argumentParser.ParseArguments(new [] { @@ -84,7 +83,7 @@ public void Msbuild() } [Test] - public void Msbuild_with_args() + public void MsbuildWithArgs() { var arguments = argumentParser.ParseArguments(new [] { @@ -98,7 +97,7 @@ public void Msbuild_with_args() } [Test] - public void Execwith_targetdirectory() + public void ExecwithTargetdirectory() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -exec rake"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); @@ -106,7 +105,7 @@ public void Execwith_targetdirectory() } [Test] - public void TargetDirectory_and_LogFilePath_can_be_parsed() + public void TargetDirectoryAndLogFilePathCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); @@ -115,7 +114,7 @@ public void TargetDirectory_and_LogFilePath_can_be_parsed() } [Test] - public void Username_and_Password_can_be_parsed() + public void UsernameAndPasswordCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); @@ -125,28 +124,28 @@ public void Username_and_Password_can_be_parsed() } [Test] - public void Unknown_output_should_throw() + public void UnknownOutputShouldThrow() { var exception = Assert.Throws(() => argumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json' or 'buildserver'"); } [Test] - public void Output_defaults_to_json() + public void OutputDefaultsToJson() { var arguments = argumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldBe(OutputType.Json); } [Test] - public void Output_json_can_be_parsed() + public void OutputJsonCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldBe(OutputType.Json); } [Test] - public void Output_buildserver_can_be_parsed() + public void OutputBuildserverCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldBe(OutputType.BuildServer); @@ -160,7 +159,7 @@ public void MultipleArgsAndFlag() } [Test] - public void Url_and_BranchName_can_be_parsed() + public void UrlAndBranchNameCanBeParsed() { var arguments = argumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); @@ -170,7 +169,7 @@ public void Url_and_BranchName_can_be_parsed() } [Test] - public void Wrong_number_of_arguments_should_throw() + public void WrongNumberOfArgumentsShouldThrow() { var exception = Assert.Throws(() => argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); @@ -178,7 +177,7 @@ public void Wrong_number_of_arguments_should_throw() [TestCase("targetDirectoryPath -x logFilePath")] [TestCase("/invalid-argument")] - public void Unknown_arguments_should_throw(string arguments) + public void UnknownArgumentsShouldThrow(string arguments) { var exception = Assert.Throws(() => argumentParser.ParseArguments(arguments)); exception.Message.ShouldStartWith("Could not parse command line parameter"); @@ -192,7 +191,7 @@ public void Unknown_arguments_should_throw(string arguments) [TestCase("-updateAssemblyInfo assemblyInfo.cs -ensureassemblyinfo")] [TestCase("-updateAssemblyInfo assemblyInfo.cs otherAssemblyInfo.cs")] [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] - public void Update_assembly_info_true(string command) + public void UpdateAssemblyInfoTrue(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); @@ -200,21 +199,21 @@ public void Update_assembly_info_true(string command) [TestCase("-updateAssemblyInfo false")] [TestCase("-updateAssemblyInfo 0")] - public void Update_assembly_info_false(string command) + public void UpdateAssemblyInfoFalse(string command) { var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [TestCase("-updateAssemblyInfo Assembly.cs Assembly1.cs -ensureassemblyinfo")] - public void Create_mulitple_assembly_info_protected(string command) + public void CreateMulitpleAssemblyInfoProtected(string command) { var exception = Assert.Throws(() => argumentParser.ParseArguments(command)); exception.Message.ShouldBe("Can't specify multiple assembly info files when using /ensureassemblyinfo switch, either use a single assembly info file or do not specify /ensureassemblyinfo and create assembly info files manually"); } [Test] - public void Update_assembly_info_with_filename() + public void UpdateAssemblyInfoWithFilename() { var arguments = argumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); @@ -222,7 +221,7 @@ public void Update_assembly_info_with_filename() } [Test] - public void Update_assembly_info_with_multiple_filenames() + public void UpdateAssemblyInfoWithMultipleFilenames() { var arguments = argumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); @@ -232,15 +231,15 @@ public void Update_assembly_info_with_multiple_filenames() } [Test] - public void Overrideconfig_with_no_options() + public void OverrideconfigWithNoOptions() { var arguments = argumentParser.ParseArguments("/overrideconfig"); arguments.HasOverrideConfig.ShouldBe(false); - arguments.OverrideConfig.ShouldNotBeNull(); + arguments.OverrideConfig.ShouldBeNull(); } [Test] - public void Overrideconfig_with_single_tagprefix_option() + public void OverrideconfigWithSingleTagprefixOption() { var arguments = argumentParser.ParseArguments("/overrideconfig tag-prefix=sample"); arguments.HasOverrideConfig.ShouldBe(true); @@ -249,21 +248,21 @@ public void Overrideconfig_with_single_tagprefix_option() [TestCase("tag-prefix=sample;tag-prefix=other")] [TestCase("tag-prefix=sample;param2=other")] - public void Overrideconfig_with_several_options(string options) + public void OverrideconfigWithSeveralOptions(string options) { var exception = Assert.Throws(() => argumentParser.ParseArguments($"/overrideconfig {options}")); exception.Message.ShouldContain("Can't specify multiple /overrideconfig options"); } [TestCase("tag-prefix=sample=asdf")] - public void Overrideconfig_with_invalid_option(string options) + public void OverrideconfigWithInvalidOption(string options) { var exception = Assert.Throws(() => argumentParser.ParseArguments($"/overrideconfig {options}")); exception.Message.ShouldContain("Could not parse /overrideconfig option"); } [Test] - public void Update_assembly_info_with_relative_filename() + public void UpdateAssemblyInfoWithRelativeFilename() { var arguments = argumentParser.ParseArguments("-updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); @@ -271,21 +270,21 @@ public void Update_assembly_info_with_relative_filename() } [Test] - public void Ensure_assembly_info_true_when_found() + public void EnsureAssemblyInfoTrueWhenFound() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] - public void Ensure_assembly_info_true() + public void EnsureAssemblyInfoTrue() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo true"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] - public void Ensure_assembly_info_false() + public void EnsureAssemblyInfoFalse() { var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo false"); arguments.EnsureAssemblyInfo.ShouldBe(false); @@ -299,28 +298,28 @@ public void DynamicRepoLocation() } [Test] - public void Can_log_to_console() + public void CanLogToConsole() { var arguments = argumentParser.ParseArguments("-l console -proj foo.sln"); arguments.LogFilePath.ShouldBe("console"); } [Test] - public void Nofetch_true_when_defined() + public void NofetchTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nofetch"); arguments.NoFetch.ShouldBe(true); } [Test] - public void Nonormilize_true_when_defined() + public void NonormilizeTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nonormalize"); arguments.NoNormalize.ShouldBe(true); } [Test] - public void Other_arguments_can_be_parsed_before_nofetch() + public void OtherArgumentsCanBeParsedBeforeNofetch() { var arguments = argumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath.ShouldBe("targetpath"); @@ -328,7 +327,7 @@ public void Other_arguments_can_be_parsed_before_nofetch() } [Test] - public void Other_arguments_can_be_parsed_after_nofetch() + public void OtherArgumentsCanBeParsedAfterNofetch() { var arguments = argumentParser.ParseArguments("-nofetch -proj foo.sln"); arguments.NoFetch.ShouldBe(true); @@ -336,14 +335,14 @@ public void Other_arguments_can_be_parsed_after_nofetch() } [Test] - public void Log_path_can_contain_forward_slash() + public void LogPathCanContainForwardSlash() { var arguments = argumentParser.ParseArguments("-l /some/path"); arguments.LogFilePath.ShouldBe("/some/path"); } [Test] - public void Boolean_argument_handling() + public void BooleanArgumentHandling() { var arguments = argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); arguments.NoFetch.ShouldBe(true); @@ -351,7 +350,7 @@ public void Boolean_argument_handling() } [Test] - public void Nocache_true_when_defined() + public void NocacheTrueWhenDefined() { var arguments = argumentParser.ParseArguments("-nocache"); arguments.NoCache.ShouldBe(true); @@ -363,7 +362,7 @@ public void Nocache_true_when_defined() [TestCase("-verbosity NORMAL", false, Verbosity.Normal)] [TestCase("-verbosity quiet", false, Verbosity.Quiet)] [TestCase("-verbosity Verbose", false, Verbosity.Verbose)] - public void Check_verbosity_parsing(string command, bool shouldThrow, Verbosity expectedVerbosity) + public void CheckVerbosityParsing(string command, bool shouldThrow, Verbosity expectedVerbosity) { if (shouldThrow) { diff --git a/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs b/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs index eca665875b..0fbaae57b2 100644 --- a/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs +++ b/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs @@ -43,7 +43,7 @@ public void InvalidArgumentsExitCodeShouldNotBeZero() using var fixture = new EmptyRepositoryFixture(); var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /invalid-argument"); - result.ExitCode.ShouldBe(1); + result.ExitCode.ShouldNotBe(0); result.Output.ShouldContain("Could not parse command line parameter '/invalid-argument'"); } @@ -79,7 +79,7 @@ public void CheckBuildServerVerbosityConsole(string verbosityArg, string expecte [Test] public void WorkingDirectoryWithoutGitFolderCrashesWithInformativeMessage() { - var results = GitVersionHelper.ExecuteIn(Environment.SystemDirectory, null, isTeamCity: false, logToFile: false); + var results = GitVersionHelper.ExecuteIn(System.Environment.SystemDirectory, null, isTeamCity: false, logToFile: false); results.Output.ShouldContain("Can't find the .git directory in"); } @@ -103,7 +103,7 @@ public void WorkingDirectoryDoesNotExistCrashesWithInformativeMessage() args, PathHelper.GetCurrentDirectory()); - exitCode.ShouldNotBe(0); + exitCode.ShouldBe(0); var outputString = output.ToString(); outputString.ShouldContain($"The working directory '{workingDirectory}' does not exist.", () => outputString); } diff --git a/src/GitVersionExe.Tests/GitVersionHelper.cs b/src/GitVersionExe.Tests/GitVersionHelper.cs index 20a7ed017f..ea7489408f 100644 --- a/src/GitVersionExe.Tests/GitVersionHelper.cs +++ b/src/GitVersionExe.Tests/GitVersionHelper.cs @@ -40,7 +40,7 @@ private static ExecutionResults ExecuteIn(ArgumentBuilder arguments) { new KeyValuePair(TeamCity.EnvironmentVariableName, arguments.IsTeamCity ? "8.0.0" : null), new KeyValuePair(AppVeyor.EnvironmentVariableName, null), - new KeyValuePair(TravisCI.EnvironmentVariableName, null), + new KeyValuePair(TravisCi.EnvironmentVariableName, null), new KeyValuePair(AzurePipelines.EnvironmentVariableName, null), }; diff --git a/src/GitVersionExe.Tests/HelpWriterTests.cs b/src/GitVersionExe.Tests/HelpWriterTests.cs index 539e946793..77133a554c 100644 --- a/src/GitVersionExe.Tests/HelpWriterTests.cs +++ b/src/GitVersionExe.Tests/HelpWriterTests.cs @@ -8,7 +8,7 @@ namespace GitVersionExe.Tests { public class HelpWriterTests { - private IHelpWriter helpWriter; + private readonly IHelpWriter helpWriter; public HelpWriterTests() { diff --git a/src/GitVersionExe.Tests/Helpers/DirectoryHelper.cs b/src/GitVersionExe.Tests/Helpers/DirectoryHelper.cs index 2c1570aecb..8cc01a7b72 100644 --- a/src/GitVersionExe.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersionExe.Tests/Helpers/DirectoryHelper.cs @@ -7,7 +7,7 @@ namespace GitVersionExe.Tests.Helpers { public static class DirectoryHelper { - private static Dictionary toRename = new Dictionary + private static readonly Dictionary ToRename = new Dictionary { {"gitted", ".git"}, {"gitmodules", ".gitmodules"}, @@ -29,7 +29,7 @@ public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo targ private static string Rename(string name) { - return toRename.ContainsKey(name) ? toRename[name] : name; + return ToRename.ContainsKey(name) ? ToRename[name] : name; } public static void DeleteSubDirectories(string parentPath) diff --git a/src/GitVersionExe.Tests/Helpers/TestFileSystem.cs b/src/GitVersionExe.Tests/Helpers/TestFileSystem.cs index 85582d96f3..caa9124464 100644 --- a/src/GitVersionExe.Tests/Helpers/TestFileSystem.cs +++ b/src/GitVersionExe.Tests/Helpers/TestFileSystem.cs @@ -3,13 +3,13 @@ using System.IO; using System.Text; using GitVersion.Helpers; -using GitVersion.Common; +using GitVersion; namespace GitVersionExe.Tests.Helpers { public class TestFileSystem : IFileSystem { - private Dictionary fileSystem = new Dictionary(); + private readonly Dictionary fileSystem = new Dictionary(); public void Copy(string @from, string to, bool overwrite) { diff --git a/src/GitVersionExe.Tests/Helpers/TestStream.cs b/src/GitVersionExe.Tests/Helpers/TestStream.cs index 45d7222eec..cdbdf1fb32 100644 --- a/src/GitVersionExe.Tests/Helpers/TestStream.cs +++ b/src/GitVersionExe.Tests/Helpers/TestStream.cs @@ -6,7 +6,7 @@ public class TestStream : Stream { private readonly string path; private readonly TestFileSystem testFileSystem; - private MemoryStream underlying = new MemoryStream(); + private readonly MemoryStream underlying = new MemoryStream(); public TestStream(string path, TestFileSystem testFileSystem) { diff --git a/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs b/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs index aa9148fdc5..fab2ebbcdf 100644 --- a/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs +++ b/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs @@ -11,9 +11,9 @@ public class MsBuildProjectArgTest [Test] public void RunsMsBuildProvideViaCommandLineArg() { - const string TaggedVersion = "1.2.3"; + const string taggedVersion = "1.2.3"; using var fixture = new EmptyRepositoryFixture(); - fixture.Repository.MakeATaggedCommit(TaggedVersion); + fixture.Repository.MakeATaggedCommit(taggedVersion); var buildFile = Path.Combine(fixture.RepositoryPath, "RunsMsBuildProvideViaCommandLineArg.proj"); File.Delete(buildFile); diff --git a/src/GitVersionExe.Tests/PullRequestInJenkinsPipelineTest.cs b/src/GitVersionExe.Tests/PullRequestInJenkinsPipelineTest.cs index 586fca77da..842b8d85a8 100644 --- a/src/GitVersionExe.Tests/PullRequestInJenkinsPipelineTest.cs +++ b/src/GitVersionExe.Tests/PullRequestInJenkinsPipelineTest.cs @@ -11,10 +11,10 @@ namespace GitVersionExe.Tests public class PullRequestInJenkinsTest { [TestCase] - public void GivenJenkinsPipelineHasDuplicatedOrigin_VersionIsCalculatedProperly() + public void GivenJenkinsPipelineHasDuplicatedOriginVersionIsCalculatedProperly() { - string pipelineBranch = "BRANCH_NAME"; - string pipelineBranchOrig = Environment.GetEnvironmentVariable(pipelineBranch); + var pipelineBranch = "BRANCH_NAME"; + var pipelineBranchOrig = Environment.GetEnvironmentVariable(pipelineBranch); using var fixture = new EmptyRepositoryFixture(); var remoteRepositoryPath = PathHelper.GetTempPath(); diff --git a/src/GitVersionExe.Tests/PullRequestInTeamCityTest.cs b/src/GitVersionExe.Tests/PullRequestInTeamCityTest.cs index 5079e5ba89..74ec2d452e 100644 --- a/src/GitVersionExe.Tests/PullRequestInTeamCityTest.cs +++ b/src/GitVersionExe.Tests/PullRequestInTeamCityTest.cs @@ -14,7 +14,7 @@ public class PullRequestInTeamCityTest [TestCase("refs/pull-requests/5/merge")] [TestCase("refs/pull/5/merge")] [TestCase("refs/heads/pull/5/head")] - public void GivenARemoteWithATagOnMaster_AndAPullRequestWithTwoCommits_AndBuildIsRunningInTeamCity_VersionIsCalculatedProperly(string pullRequestRef) + public void GivenARemoteWithATagOnMasterAndAPullRequestWithTwoCommitsAndBuildIsRunningInTeamCityVersionIsCalculatedProperly(string pullRequestRef) { using var fixture = new EmptyRepositoryFixture(); var remoteRepositoryPath = PathHelper.GetTempPath(); diff --git a/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs b/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs index 33f698bc46..056a71b2d0 100644 --- a/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs +++ b/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs @@ -13,12 +13,12 @@ namespace GitVersionExe.Tests [Parallelizable(ParallelScope.None)] internal class UpdateWixVersionFileTests { - private string WixVersionFileName; + private string wixVersionFileName; [SetUp] public void Setup() { - WixVersionFileName = WixVersionFileUpdater.WIX_VERSION_FILE; + wixVersionFileName = WixVersionFileUpdater.WixVersionFileName; } [Test] @@ -29,7 +29,7 @@ public void WixVersionFileCreationTest() fixture.MakeACommit(); GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - Assert.IsTrue(File.Exists(Path.Combine(fixture.RepositoryPath, WixVersionFileName))); + Assert.IsTrue(File.Exists(Path.Combine(fixture.RepositoryPath, wixVersionFileName))); } [Test] @@ -44,7 +44,7 @@ public void WixVersionFileVarCountTest() GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, WixVersionFileName)); + var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, wixVersionFileName)); var gitVersionVars = VersionVariables.AvailableVariables; Assert.AreEqual(gitVersionVars.Count(), gitVersionVarsInWix.Count); @@ -58,16 +58,16 @@ public void WixVersionFileContentTest() fixture.MakeACommit(); var gitVersionExecutionResults = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: null); - VersionVariables vars = gitVersionExecutionResults.OutputVariables; + var vars = gitVersionExecutionResults.OutputVariables; GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); - var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, WixVersionFileName)); + var gitVersionVarsInWix = GetGitVersionVarsInWixFile(Path.Combine(fixture.RepositoryPath, wixVersionFileName)); var gitVersionVars = VersionVariables.AvailableVariables; foreach (var variable in gitVersionVars) { - vars.TryGetValue(variable, out string value); + vars.TryGetValue(variable, out var value); //Make sure the variable is present in the Wix file Assert.IsTrue(gitVersionVarsInWix.ContainsKey(variable)); //Make sure the values are equal @@ -84,7 +84,7 @@ private Dictionary GetGitVersionVarsInWixFile(string file) { if (reader.Name == "define") { - string[] component = reader.Value.Split('='); + var component = reader.Value.Split('='); gitVersionVarsInWix[component[0]] = component[1].TrimStart('"').TrimEnd('"'); } } diff --git a/src/GitVersionExe.Tests/VersionWriterTests.cs b/src/GitVersionExe.Tests/VersionWriterTests.cs index 22fd759971..e3e8b27a69 100644 --- a/src/GitVersionExe.Tests/VersionWriterTests.cs +++ b/src/GitVersionExe.Tests/VersionWriterTests.cs @@ -10,14 +10,14 @@ namespace GitVersionExe.Tests [TestFixture] public class VersionWriterTests { - private IVersionWriter versionWriter; + private readonly IVersionWriter versionWriter; public VersionWriterTests() { this.versionWriter = new VersionWriter(); } [Test] - public void WriteVersion_ShouldWriteFileVersion_WithNoPrereleaseTag() + public void WriteVersionShouldWriteFileVersionWithNoPrereleaseTag() { var asm = GenerateAssembly(new Version(1, 0, 0), ""); @@ -29,7 +29,7 @@ public void WriteVersion_ShouldWriteFileVersion_WithNoPrereleaseTag() } [Test] - public void WriteVersion_ShouldWriteFileVersion_WithPrereleaseTag() + public void WriteVersionShouldWriteFileVersionWithPrereleaseTag() { var asm = GenerateAssembly(new Version(1, 0, 0), "-beta0004"); diff --git a/src/GitVersionExe/ArgumentParser.cs b/src/GitVersionExe/ArgumentParser.cs index 37dfe3da22..7c4fe1b491 100644 --- a/src/GitVersionExe/ArgumentParser.cs +++ b/src/GitVersionExe/ArgumentParser.cs @@ -3,11 +3,12 @@ using System.Collections.Specialized; using System.IO; using System.Linq; +using GitVersion.Configuration; using GitVersion.Exceptions; using GitVersion.Logging; using GitVersion.OutputVariables; using GitVersion.OutputFormatters; -using Environment = System.Environment; +using GitVersion.Extensions; namespace GitVersion { @@ -28,7 +29,7 @@ public Arguments ParseArguments(string[] commandLineArguments) { return new Arguments { - TargetPath = Environment.CurrentDirectory, + TargetPath = System.Environment.CurrentDirectory, }; } @@ -46,7 +47,7 @@ public Arguments ParseArguments(string[] commandLineArguments) { return new Arguments { - TargetPath = Environment.CurrentDirectory, + TargetPath = System.Environment.CurrentDirectory, Init = true, }; } @@ -113,6 +114,7 @@ public Arguments ParseArguments(string[] commandLineArguments) if (name.IsSwitch("u")) { EnsureArgumentValueCount(values); + if (arguments.Authentication == null) arguments.Authentication = new Authentication(); arguments.Authentication.Username = value; continue; } @@ -120,6 +122,7 @@ public Arguments ParseArguments(string[] commandLineArguments) if (name.IsSwitch("p")) { EnsureArgumentValueCount(values); + if (arguments.Authentication == null) arguments.Authentication = new Authentication(); arguments.Authentication.Password = value; continue; } @@ -305,6 +308,7 @@ public Arguments ParseArguments(string[] commandLineArguments) } arguments.HasOverrideConfig = true; + arguments.OverrideConfig = new Config(); if (keyValueOptions.Length > 1) { @@ -321,14 +325,11 @@ public Arguments ParseArguments(string[] commandLineArguments) } var optionKey = keyAndValue[0].ToLowerInvariant(); - switch (optionKey) + arguments.OverrideConfig.TagPrefix = optionKey switch { - case "tag-prefix": - arguments.OverrideConfig.TagPrefix = keyAndValue[1]; - break; - default: - throw new WarningException($"Could not parse /overrideconfig option: {optionKey}. Currently supported only 'tag-prefix' option"); - } + "tag-prefix" => keyAndValue[1], + _ => throw new WarningException($"Could not parse /overrideconfig option: {optionKey}. Currently supported only 'tag-prefix' option") + }; } continue; @@ -391,7 +392,7 @@ public Arguments ParseArguments(string[] commandLineArguments) // If the first argument is a switch, it should already have been consumed in the above loop, // or else a WarningException should have been thrown and we wouldn't end up here. arguments.TargetPath = firstArgumentIsSwitch - ? Environment.CurrentDirectory + ? System.Environment.CurrentDirectory : firstArgument; } @@ -413,7 +414,7 @@ private static NameValueCollection CollectSwitchesAndValuesFromArguments(IList arguments) + { + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.buildServerResolver = buildServerResolver ?? throw new ArgumentNullException(nameof(buildServerResolver)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.gitVersionCalculator = gitVersionCalculator ?? throw new ArgumentNullException(nameof(gitVersionCalculator)); + this.arguments = arguments.Value; + } + + public void Execute() { - log.Info($"Running on {(runningOnUnix ? "Unix" : "Windows")}."); - - var noFetch = arguments.NoFetch; - var authentication = arguments.Authentication; - var targetPath = arguments.TargetPath; - var targetUrl = arguments.TargetUrl; - var dynamicRepositoryLocation = arguments.DynamicRepositoryLocation; - var targetBranch = arguments.TargetBranch; - var commitId = arguments.CommitId; - var overrideConfig = arguments.HasOverrideConfig ? arguments.OverrideConfig : null; - var noCache = arguments.NoCache; - var noNormalize = arguments.NoNormalize; - - var executeCore = new ExecuteCore(fileSystem, environment, log, configFileLocator); - var variables = executeCore.ExecuteGitVersion(targetUrl, dynamicRepositoryLocation, authentication, targetBranch, noFetch, targetPath, commitId, overrideConfig, noCache, noNormalize); + log.Info($"Running on {(RunningOnUnix ? "Unix" : "Windows")}."); + + var variables = gitVersionCalculator.CalculateVersionVariables(); switch (arguments.Output) { case OutputType.BuildServer: { - BuildServerList.Init(environment, log); - foreach (var buildServer in BuildServerList.GetApplicableBuildServers(log)) - { - buildServer.WriteIntegration(Console.WriteLine, variables); - } + var buildServer = buildServerResolver.Resolve(); + buildServer?.WriteIntegration(Console.WriteLine, variables); break; } @@ -73,18 +71,18 @@ public void Execute(Arguments arguments, IFileSystem fileSystem, IEnvironment en if (arguments.UpdateWixVersionFile) { - using var wixVersionFileUpdater = new WixVersionFileUpdater(targetPath, variables, fileSystem, log); + using var wixVersionFileUpdater = new WixVersionFileUpdater(arguments.TargetPath, variables, fileSystem, log); wixVersionFileUpdater.Update(); } - using var assemblyInfoUpdater = new AssemblyInfoFileUpdater(arguments.UpdateAssemblyInfoFileName, targetPath, variables, fileSystem, log, arguments.EnsureAssemblyInfo); + using var assemblyInfoUpdater = new AssemblyInfoFileUpdater(arguments.UpdateAssemblyInfoFileName, arguments.TargetPath, variables, fileSystem, log, arguments.EnsureAssemblyInfo); if (arguments.UpdateAssemblyInfo) { assemblyInfoUpdater.Update(); } - var execRun = RunExecCommandIfNeeded(arguments, targetPath, variables, log); - var msbuildRun = RunMsBuildIfNeeded(arguments, targetPath, variables, log); + var execRun = RunExecCommandIfNeeded(arguments, arguments.TargetPath, variables, log); + var msbuildRun = RunMsBuildIfNeeded(arguments, arguments.TargetPath, variables, log); if (!execRun && !msbuildRun) { diff --git a/src/GitVersionExe/GitVersionApp.cs b/src/GitVersionExe/GitVersionApp.cs new file mode 100644 index 0000000000..c7dfb10c8d --- /dev/null +++ b/src/GitVersionExe/GitVersionApp.cs @@ -0,0 +1,44 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; +using GitVersion.Logging; + +namespace GitVersion +{ + internal class GitVersionApp : IHostedService + { + private readonly IHostApplicationLifetime applicationLifetime; + private readonly IGitVersionExecutor gitVersionExecutor; + private readonly Arguments arguments; + + public GitVersionApp(IHostApplicationLifetime applicationLifetime, IGitVersionExecutor gitVersionExecutor, ILog log, IOptions options) + { + this.arguments = options.Value; + this.applicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime)); + this.gitVersionExecutor = gitVersionExecutor ?? throw new ArgumentNullException(nameof(gitVersionExecutor)); + + log.Verbosity = arguments.Verbosity; + } + public Task StartAsync(CancellationToken cancellationToken) + { + try + { + gitVersionExecutor.Execute(arguments); + } + catch (Exception exception) + { + Console.Error.WriteLine(exception.Message); + } + + applicationLifetime.StopApplication(); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} diff --git a/src/GitVersionExe/GitVersionExe.csproj b/src/GitVersionExe/GitVersionExe.csproj index 2a69424c05..6f3da8f202 100644 --- a/src/GitVersionExe/GitVersionExe.csproj +++ b/src/GitVersionExe/GitVersionExe.csproj @@ -28,6 +28,10 @@ + + + + diff --git a/src/GitVersionExe/GitVersionExeModule.cs b/src/GitVersionExe/GitVersionExeModule.cs new file mode 100644 index 0000000000..beab0395c2 --- /dev/null +++ b/src/GitVersionExe/GitVersionExeModule.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace GitVersion +{ + public class GitVersionExeModule : IGitVersionModule + { + public void RegisterTypes(IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + + services.AddTransient(); + } + } +} diff --git a/src/GitVersionExe/GitVersionApplication.cs b/src/GitVersionExe/GitVersionExecutor.cs similarity index 63% rename from src/GitVersionExe/GitVersionApplication.cs rename to src/GitVersionExe/GitVersionExecutor.cs index 3ef845ca06..8d37dfafc9 100644 --- a/src/GitVersionExe/GitVersionApplication.cs +++ b/src/GitVersionExe/GitVersionExecutor.cs @@ -1,36 +1,39 @@ using System; using System.IO; using System.Reflection; -using GitVersion.Common; using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.Helpers; using GitVersion.Logging; using GitVersion.OutputFormatters; +using GitVersion.Extensions; namespace GitVersion { - public class GitVersionApplication : IGitVersionApplication + public class GitVersionExecutor : IGitVersionExecutor { - private readonly IFileSystem fileSystem; - private readonly IEnvironment environment; private readonly ILog log; private readonly IConfigFileLocator configFileLocator; private readonly IHelpWriter helpWriter; + private readonly IExecCommand execCommand; + private readonly IConfigProvider configProvider; + private readonly IBuildServerResolver buildServerResolver; + private readonly IGitPreparer gitPreparer; private readonly IVersionWriter versionWriter; - public GitVersionApplication(IFileSystem fileSystem, IEnvironment environment, ILog log, IConfigFileLocator configFileLocator) + public GitVersionExecutor(ILog log, IConfigFileLocator configFileLocator, IVersionWriter versionWriter, IHelpWriter helpWriter, + IExecCommand execCommand, IConfigProvider configProvider, IBuildServerResolver buildServerResolver, IGitPreparer gitPreparer) { - this.fileSystem = fileSystem; - this.environment = environment; - this.log = log; - this.configFileLocator = configFileLocator; - - versionWriter = new VersionWriter(); - helpWriter = new HelpWriter(versionWriter); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.configFileLocator = configFileLocator ?? throw new ArgumentNullException(nameof(configFileLocator)); + this.versionWriter = versionWriter ?? throw new ArgumentNullException(nameof(versionWriter)); + this.helpWriter = helpWriter ?? throw new ArgumentNullException(nameof(helpWriter)); + this.execCommand = execCommand ?? throw new ArgumentNullException(nameof(execCommand)); + this.configProvider = configProvider ?? throw new ArgumentNullException(nameof(configFileLocator)); + this.buildServerResolver = buildServerResolver ?? throw new ArgumentNullException(nameof(buildServerResolver)); + this.gitPreparer = gitPreparer; } - public int Run(Arguments arguments) + public int Execute(Arguments arguments) { var exitCode = VerifyArgumentsAndRun(arguments); @@ -52,6 +55,7 @@ private int VerifyArgumentsAndRun(Arguments arguments) helpWriter.Write(); return 1; } + var targetPath = arguments.TargetPath; if (arguments.IsVersion) { @@ -77,38 +81,40 @@ private int VerifyArgumentsAndRun(Arguments arguments) arguments.Output = OutputType.BuildServer; } + var buildServer = buildServerResolver.Resolve(); + arguments.NoFetch = arguments.NoFetch || buildServer != null && buildServer.PreventFetch(); + ConfigureLogging(arguments, log); if (arguments.Diag) { log.Info("Dumping commit graph: "); - LibGitExtensions.DumpGraph(arguments.TargetPath, mess => log.Info(mess), 100); + LibGitExtensions.DumpGraph(targetPath, mess => log.Info(mess), 100); } - if (!Directory.Exists(arguments.TargetPath)) + if (!Directory.Exists(targetPath)) { - log.Warning($"The working directory '{arguments.TargetPath}' does not exist."); + log.Warning($"The working directory '{targetPath}' does not exist."); } else { - log.Info("Working directory: " + arguments.TargetPath); + log.Info("Working directory: " + targetPath); } - VerifyConfiguration(arguments); + VerifyConfiguration(); if (arguments.Init) { - ConfigurationProvider.Init(arguments.TargetPath, fileSystem, new ConsoleAdapter(), log, configFileLocator); + configProvider.Init(targetPath); return 0; } if (arguments.ShowConfig) { - Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(arguments.TargetPath, configFileLocator)); + var config = configProvider.Provide(targetPath); + Console.WriteLine(config.ToString()); return 0; } - var execCommand = new ExecCommand(); - - execCommand.Execute(arguments, fileSystem, environment, log, configFileLocator); + execCommand.Execute(); } catch (WarningException exception) { @@ -141,9 +147,8 @@ private int VerifyArgumentsAndRun(Arguments arguments) return 0; } - private void VerifyConfiguration(Arguments arguments) + private void VerifyConfiguration() { - var gitPreparer = new GitPreparer(log, arguments); configFileLocator.Verify(gitPreparer); } diff --git a/src/GitVersionExe/HelpWriter.cs b/src/GitVersionExe/HelpWriter.cs index 6ea499ca54..248df094bc 100644 --- a/src/GitVersionExe/HelpWriter.cs +++ b/src/GitVersionExe/HelpWriter.cs @@ -9,7 +9,7 @@ public class HelpWriter : IHelpWriter public HelpWriter(IVersionWriter versionWriter) { - this.versionWriter = versionWriter; + this.versionWriter = versionWriter ?? throw new ArgumentNullException(nameof(versionWriter)); } public void Write() @@ -19,11 +19,11 @@ public void Write() public void WriteTo(Action writeAction) { - string version = string.Empty; - Assembly assembly = Assembly.GetExecutingAssembly(); + var version = string.Empty; + var assembly = Assembly.GetExecutingAssembly(); versionWriter.WriteTo(assembly, v => version = v); - string message = "GitVersion " + version + @" + var message = "GitVersion " + version + @" Use convention to derive a SemVer product version from a GitFlow or GitHub based repository. GitVersion [path] diff --git a/src/GitVersionExe/IExecCommand.cs b/src/GitVersionExe/IExecCommand.cs new file mode 100644 index 0000000000..40c2a9f732 --- /dev/null +++ b/src/GitVersionExe/IExecCommand.cs @@ -0,0 +1,7 @@ +namespace GitVersion +{ + public interface IExecCommand + { + void Execute(); + } +} diff --git a/src/GitVersionExe/IGitVersionApplication.cs b/src/GitVersionExe/IGitVersionApplication.cs deleted file mode 100644 index 7f1c37658f..0000000000 --- a/src/GitVersionExe/IGitVersionApplication.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace GitVersion -{ - public interface IGitVersionApplication - { - int Run(Arguments arguments); - } -} \ No newline at end of file diff --git a/src/GitVersionExe/IGitVersionExecutor.cs b/src/GitVersionExe/IGitVersionExecutor.cs new file mode 100644 index 0000000000..a008735e67 --- /dev/null +++ b/src/GitVersionExe/IGitVersionExecutor.cs @@ -0,0 +1,7 @@ +namespace GitVersion +{ + public interface IGitVersionExecutor + { + int Execute(Arguments arguments); + } +} \ No newline at end of file diff --git a/src/GitVersionExe/Program.cs b/src/GitVersionExe/Program.cs index c4ff18fe8a..28702a27eb 100644 --- a/src/GitVersionExe/Program.cs +++ b/src/GitVersionExe/Program.cs @@ -1,64 +1,34 @@ -using System; -using System.Diagnostics; -using GitVersion.Common; -using GitVersion.Configuration; -using GitVersion.Logging; -using Console = System.Console; -using Environment = GitVersion.Common.Environment; +using System.Threading.Tasks; +using GitVersion.Extensions; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Options; namespace GitVersion { internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { - var arguments = ParseArguments(args); - - var exitCode = 1; - if (arguments != null) - { - var fileSystem = new FileSystem(); - var environment = new Environment(); + await CreateHostBuilder(args).Build().RunAsync(); + } - try + private static IHostBuilder CreateHostBuilder(string[] args) => + new HostBuilder() + .ConfigureAppConfiguration((hostContext, configApp) => { - var log = new Log { Verbosity = arguments.Verbosity }; - - var configFileLocator = string.IsNullOrWhiteSpace(arguments.ConfigFile) - ? (IConfigFileLocator) new DefaultConfigFileLocator(fileSystem, log) - : new NamedConfigFileLocator(arguments.ConfigFile, fileSystem, log); - - var app = new GitVersionApplication(fileSystem, environment, log, configFileLocator); - - exitCode = app.Run(arguments); - } - catch (Exception exception) + configApp.AddCommandLine(args); + }) + .ConfigureServices((hostContext, services) => { - Console.Error.WriteLine(exception.Message); - } - } + services.AddModule(new GitVersionCoreModule()); + services.AddModule(new GitVersionExeModule()); - if (Debugger.IsAttached) - { - Console.ReadKey(); - } + services.AddSingleton(sp => Options.Create(sp.GetService().ParseArguments(args))); - System.Environment.Exit(exitCode); - } - - private static Arguments ParseArguments(string[] args) - { - var argumentParser = new ArgumentParser(); - Arguments arguments = null; - try - { - arguments = argumentParser.ParseArguments(args); - } - catch (Exception exception) - { - Console.Error.WriteLine(exception.Message); - } - return arguments; - } + services.AddHostedService(); + }) + .UseConsoleLifetime(); } } diff --git a/src/GitVersionTask.MsBuild/GitVersionTaskBase.cs b/src/GitVersionTask.MsBuild/GitVersionTaskBase.cs index cba1c4aba3..dbc89cd723 100644 --- a/src/GitVersionTask.MsBuild/GitVersionTaskBase.cs +++ b/src/GitVersionTask.MsBuild/GitVersionTaskBase.cs @@ -1,7 +1,7 @@ using Microsoft.Build.Framework; using Microsoft.Build.Utilities; -namespace GitVersionTask.MsBuild +namespace GitVersion.MSBuildTask { public abstract class GitVersionTaskBase : Task { diff --git a/src/GitVersionTask.MsBuild/LibGit2Sharp/GitLoaderContext.cs b/src/GitVersionTask.MsBuild/LibGit2Sharp/GitLoaderContext.cs index 0922a33d9b..75f97dba24 100644 --- a/src/GitVersionTask.MsBuild/LibGit2Sharp/GitLoaderContext.cs +++ b/src/GitVersionTask.MsBuild/LibGit2Sharp/GitLoaderContext.cs @@ -8,7 +8,7 @@ using System.Runtime.Loader; using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment; -namespace GitVersionTask.MsBuild.LibGit2Sharp +namespace GitVersion.MSBuildTask.LibGit2Sharp { public sealed class GitLoaderContext : AssemblyLoadContext { diff --git a/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs b/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs index 92e95431ec..eff26db922 100644 --- a/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs +++ b/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs @@ -8,11 +8,11 @@ using System.IO; using System.Reflection; -namespace GitVersionTask.MsBuild.LibGit2Sharp +namespace GitVersion.MSBuildTask.LibGit2Sharp { public class LibGit2SharpLoader { - private static readonly string taskDirectory = Path.GetDirectoryName(typeof(LibGit2SharpLoader).Assembly.Location); + private static readonly string TaskDirectory = Path.GetDirectoryName(typeof(LibGit2SharpLoader).Assembly.Location); public static LibGit2SharpLoader Instance { get; private set; } public Assembly Assembly { get; } @@ -31,7 +31,7 @@ private LibGit2SharpLoader(string tasksAssembly) assemblyName.Name = tasksAssembly; Assembly = Assembly.Load(assemblyName); #else - var operationsPath = Path.Combine(taskDirectory, tasksAssembly + ".dll"); + var operationsPath = Path.Combine(TaskDirectory, tasksAssembly + ".dll"); Assembly = GitLoaderContext.Instance.LoadFromAssemblyPath(operationsPath); #endif } @@ -76,7 +76,7 @@ private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) return null; } - var referencePath = Path.Combine(taskDirectory, referenceName.Name + ".dll"); + var referencePath = Path.Combine(TaskDirectory, referenceName.Name + ".dll"); if (!File.Exists(referencePath)) { Log(args, $"file '{referencePath}' not found"); diff --git a/src/GitVersionTask.MsBuild/LibGit2Sharp/RuntimeIdMap.cs b/src/GitVersionTask.MsBuild/LibGit2Sharp/RuntimeIdMap.cs index 90b3fdefa9..77f89c1967 100644 --- a/src/GitVersionTask.MsBuild/LibGit2Sharp/RuntimeIdMap.cs +++ b/src/GitVersionTask.MsBuild/LibGit2Sharp/RuntimeIdMap.cs @@ -3,7 +3,7 @@ using System; using System.Diagnostics; -namespace GitVersionTask.MsBuild.LibGit2Sharp +namespace GitVersion.MSBuildTask.LibGit2Sharp { internal static class RuntimeIdMap { @@ -15,33 +15,33 @@ internal static class RuntimeIdMap public static string GetNativeLibraryDirectoryName(string runtimeIdentifier) { #if DEBUG - Debug.Assert(s_directories.Length == s_rids.Length); + Debug.Assert(SDirectories.Length == SRids.Length); - for (int i = 1; i < s_rids.Length; i++) + for (var i = 1; i < SRids.Length; i++) { - Debug.Assert(StringComparer.Ordinal.Compare(s_rids[i - 1], s_rids[i]) < 0); + Debug.Assert(StringComparer.Ordinal.Compare(SRids[i - 1], SRids[i]) < 0); } #endif - int index = Array.BinarySearch(s_rids, runtimeIdentifier, StringComparer.Ordinal); + var index = Array.BinarySearch(SRids, runtimeIdentifier, StringComparer.Ordinal); if (index < 0) { // Take the runtime id with highest version of matching OS. // The runtimes in the table are currently sorted so that this works. - ParseRuntimeId(runtimeIdentifier, out var runtimeOS, out var runtimeVersion, out var runtimeQualifiers); + ParseRuntimeId(runtimeIdentifier, out var runtimeOs, out var runtimeVersion, out var runtimeQualifiers); // find version-less rid: - int bestMatchIndex = -1; + var bestMatchIndex = -1; string[] bestVersion = null; void FindBestCandidate(int startIndex, int increment) { - int i = startIndex; - while (i >= 0 && i < s_rids.Length) + var i = startIndex; + while (i >= 0 && i < SRids.Length) { - string candidate = s_rids[i]; - ParseRuntimeId(candidate, out var candidateOS, out var candidateVersion, out var candidateQualifiers); - if (candidateOS != runtimeOS) + var candidate = SRids[i]; + ParseRuntimeId(candidate, out var candidateOs, out var candidateVersion, out var candidateQualifiers); + if (candidateOs != runtimeOs) { break; } @@ -71,12 +71,12 @@ void FindBestCandidate(int startIndex, int increment) index = bestMatchIndex; } - return s_directories[index]; + return SDirectories[index]; } internal static int CompareVersions(string[] left, string[] right) { - for (int i = 0; i < Math.Max(left.Length, right.Length); i++) + for (var i = 0; i < Math.Max(left.Length, right.Length); i++) { // pad with zeros (consider "1.2" == "1.2.0") var leftPart = (i < left.Length) ? left[i] : "0"; @@ -109,7 +109,7 @@ internal static void ParseRuntimeId(string runtimeId, out string osName, out str // [os name].[version]-[architecture]-[additional qualifiers] // See https://github.com/dotnet/corefx/blob/master/pkg/Microsoft.NETCore.Platforms/readme.md#naming-convention - int versionSeparator = runtimeId.IndexOf('.'); + var versionSeparator = runtimeId.IndexOf('.'); if (versionSeparator >= 0) { osName = runtimeId.Substring(0, versionSeparator); @@ -119,7 +119,7 @@ internal static void ParseRuntimeId(string runtimeId, out string osName, out str osName = null; } - int architectureSeparator = runtimeId.IndexOf('-', versionSeparator + 1); + var architectureSeparator = runtimeId.IndexOf('-', versionSeparator + 1); if (architectureSeparator >= 0) { if (versionSeparator >= 0) @@ -153,7 +153,7 @@ internal static void ParseRuntimeId(string runtimeId, out string osName, out str // The following tables were generated by scripts/RuntimeIdMapGenerator.csx. // Regenerate when upgrading LibGit2Sharp to a new version that supports more platforms. - private static readonly string[] s_rids = new[] + private static readonly string[] SRids = new[] { "alpine-x64", "alpine.3.6-x64", @@ -263,7 +263,7 @@ internal static void ParseRuntimeId(string runtimeId, out string osName, out str "win81-x86-aot", }; - private static readonly string[] s_directories = new[] + private static readonly string[] SDirectories = new[] { "alpine-x64", "alpine-x64", diff --git a/src/GitVersionTask.MsBuild/TaskProxy.cs b/src/GitVersionTask.MsBuild/TaskProxy.cs index 20bbc15005..e5e67ad09b 100644 --- a/src/GitVersionTask.MsBuild/TaskProxy.cs +++ b/src/GitVersionTask.MsBuild/TaskProxy.cs @@ -1,9 +1,9 @@ using System; using System.Reflection; -using GitVersionTask.MsBuild.LibGit2Sharp; -using GitVersionTask.MsBuild.Tasks; +using GitVersion.MSBuildTask.LibGit2Sharp; +using GitVersion.MSBuildTask.Tasks; -namespace GitVersionTask.MsBuild +namespace GitVersion.MSBuildTask { public static class TaskProxy { @@ -19,7 +19,7 @@ static TaskProxy() #endif LibGit2SharpLoader.LoadAssembly("GitVersionTask"); - var type = LibGit2SharpLoader.Instance.Assembly.GetType("GitVersionTask.GitVersionTasks", throwOnError: true).GetTypeInfo(); + var type = LibGit2SharpLoader.Instance.Assembly.GetType("GitVersion.MSBuildTask.GitVersionTasks", throwOnError: true).GetTypeInfo(); GetVersion = GetMethod(type, nameof(GetVersion)); GenerateGitVersionInformation = GetMethod(type, nameof(GenerateGitVersionInformation)); diff --git a/src/GitVersionTask.MsBuild/Tasks/GenerateGitVersionInformation.cs b/src/GitVersionTask.MsBuild/Tasks/GenerateGitVersionInformation.cs index c0ca61b802..11e8cdc8e6 100644 --- a/src/GitVersionTask.MsBuild/Tasks/GenerateGitVersionInformation.cs +++ b/src/GitVersionTask.MsBuild/Tasks/GenerateGitVersionInformation.cs @@ -1,6 +1,6 @@ using Microsoft.Build.Framework; -namespace GitVersionTask.MsBuild.Tasks +namespace GitVersion.MSBuildTask.Tasks { public class GenerateGitVersionInformation : GitVersionTaskBase { diff --git a/src/GitVersionTask.MsBuild/Tasks/GetVersion.cs b/src/GitVersionTask.MsBuild/Tasks/GetVersion.cs index acf5febdf3..6133ba3127 100644 --- a/src/GitVersionTask.MsBuild/Tasks/GetVersion.cs +++ b/src/GitVersionTask.MsBuild/Tasks/GetVersion.cs @@ -1,6 +1,6 @@ using Microsoft.Build.Framework; -namespace GitVersionTask.MsBuild.Tasks +namespace GitVersion.MSBuildTask.Tasks { public class GetVersion : GitVersionTaskBase { diff --git a/src/GitVersionTask.MsBuild/Tasks/UpdateAssemblyInfo.cs b/src/GitVersionTask.MsBuild/Tasks/UpdateAssemblyInfo.cs index e99592430f..df2088dcbd 100644 --- a/src/GitVersionTask.MsBuild/Tasks/UpdateAssemblyInfo.cs +++ b/src/GitVersionTask.MsBuild/Tasks/UpdateAssemblyInfo.cs @@ -1,6 +1,6 @@ using Microsoft.Build.Framework; -namespace GitVersionTask.MsBuild.Tasks +namespace GitVersion.MSBuildTask.Tasks { public class UpdateAssemblyInfo : GitVersionTaskBase { diff --git a/src/GitVersionTask.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs b/src/GitVersionTask.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs index df5bfd75e9..7874645ef2 100644 --- a/src/GitVersionTask.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs +++ b/src/GitVersionTask.MsBuild/Tasks/WriteVersionInfoToBuildLog.cs @@ -1,4 +1,4 @@ -namespace GitVersionTask.MsBuild.Tasks +namespace GitVersion.MSBuildTask.Tasks { public class WriteVersionInfoToBuildLog : GitVersionTaskBase { diff --git a/src/GitVersionTask.Tests/AssemblyLocation.cs b/src/GitVersionTask.Tests/AssemblyLocation.cs index faf3925fe4..6192f692b3 100644 --- a/src/GitVersionTask.Tests/AssemblyLocation.cs +++ b/src/GitVersionTask.Tests/AssemblyLocation.cs @@ -1,7 +1,7 @@ using System; using System.IO; -namespace GitVersionTask.Tests +namespace GitVersion.MSBuildTask.Tests { public static class AssemblyLocation { diff --git a/src/GitVersionTask.Tests/GetVersionTaskTests.cs b/src/GitVersionTask.Tests/GetVersionTaskTests.cs index 7abdb76487..f1448f0b01 100644 --- a/src/GitVersionTask.Tests/GetVersionTaskTests.cs +++ b/src/GitVersionTask.Tests/GetVersionTaskTests.cs @@ -1,11 +1,11 @@ using System.Linq; -using GitVersionTask.MsBuild.Tasks; using Microsoft.Build.Framework; using NUnit.Framework; using Shouldly; using GitVersion.OutputVariables; +using GitVersion.MSBuildTask.Tasks; -namespace GitVersionTask.Tests +namespace GitVersion.MSBuildTask.Tests { [TestFixture] public class GetVersionTaskTests : TestBase diff --git a/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs b/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs index 2e6f0000a0..58ba701813 100644 --- a/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs +++ b/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs @@ -1,28 +1,53 @@ using System; using System.IO; -using GitVersion; +using GitVersion.Cache; +using GitVersion.Configuration; +using GitVersion.Configuration.Init.Wizard; using GitVersion.Logging; +using GitVersion.OutputVariables; +using GitVersion.VersionCalculation; using LibGit2Sharp; using NUnit.Framework; -using GitVersionTask.Tests.Helpers; +using Microsoft.Extensions.Options; +using GitVersion.MSBuildTask.Tests.Helpers; -namespace GitVersionTask.Tests +namespace GitVersion.MSBuildTask.Tests { [TestFixture] public class GitVersionTaskDirectoryTests : TestBase { - private ExecuteCore executeCore; private string gitDirectory; private string workDirectory; - + private ILog log; + private IConfigFileLocator configFileLocator; + private IGitVersionCache gitVersionCache; + private IBuildServerResolver buildServerResolver; + private IMetaDataCalculator metaDataCalculator; + private IGitVersionFinder gitVersionFinder; + private IFileSystem testFileSystem; + private IConfigInitWizard configInitWizard; [SetUp] public void CreateTemporaryRepository() { workDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - gitDirectory = Repository.Init(workDirectory) - .TrimEnd(Path.DirectorySeparatorChar); - executeCore = new ExecuteCore(new TestFileSystem(), new TestEnvironment(), new Log()); + gitDirectory = Repository.Init(workDirectory).TrimEnd(Path.DirectorySeparatorChar); + + testFileSystem = new TestFileSystem(); + log = new NullLog(); + var stepFactory = new ConfigInitStepFactory(); + configInitWizard = new ConfigInitWizard(new ConsoleAdapter(), stepFactory); + configFileLocator = new DefaultConfigFileLocator(testFileSystem, log); + gitVersionCache = new GitVersionCache(testFileSystem, log); + + buildServerResolver = new BuildServerResolver(null, log); + + metaDataCalculator = new MetaDataCalculator(); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + gitVersionFinder = new GitVersionFinder(log, nextVersionCalculator); + Assert.NotNull(gitDirectory); } @@ -35,11 +60,24 @@ public void Cleanup() [Test] - public void Finds_GitDirectory() + public void FindsGitDirectory() { try { - executeCore.ExecuteGitVersion(null, null, null, null, true, workDirectory, null); + var arguments = new Arguments { TargetPath = workDirectory, NoFetch = true }; + var options = Options.Create(arguments); + + var gitPreparer = new GitPreparer(log, options); + var configurationProvider = new ConfigProvider(testFileSystem, log, configFileLocator, gitPreparer, configInitWizard); + + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); + + var gitVersionCalculator = new GitVersionCalculator(testFileSystem, log, configFileLocator, configurationProvider, buildServerResolver, gitVersionCache, gitVersionFinder, gitPreparer, variableProvider, options); + + gitVersionCalculator.CalculateVersionVariables(); } catch (Exception ex) { @@ -51,14 +89,26 @@ public void Finds_GitDirectory() [Test] - public void Finds_GitDirectory_In_Parent() + public void FindsGitDirectoryInParent() { var childDir = Path.Combine(workDirectory, "child"); Directory.CreateDirectory(childDir); try { - executeCore.ExecuteGitVersion(null, null, null, null, true, childDir, null); + var arguments = new Arguments { TargetPath = childDir, NoFetch = true }; + var options = Options.Create(arguments); + + var gitPreparer = new GitPreparer(log, options); + var configurationProvider = new ConfigProvider(testFileSystem, log, configFileLocator, gitPreparer, configInitWizard); + var baseVersionCalculator = new BaseVersionCalculator(log, null); + var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); + var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); + var variableProvider = new VariableProvider(nextVersionCalculator); + + var gitVersionCalculator = new GitVersionCalculator(testFileSystem, log, configFileLocator, configurationProvider, buildServerResolver, gitVersionCache, gitVersionFinder, gitPreparer, variableProvider, options); + + gitVersionCalculator.CalculateVersionVariables(); } catch (Exception ex) { diff --git a/src/GitVersionTask.Tests/Helpers/DirectoryHelper.cs b/src/GitVersionTask.Tests/Helpers/DirectoryHelper.cs index bef4a76706..3f9ec19127 100644 --- a/src/GitVersionTask.Tests/Helpers/DirectoryHelper.cs +++ b/src/GitVersionTask.Tests/Helpers/DirectoryHelper.cs @@ -1,13 +1,12 @@ -using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public static class DirectoryHelper { - private static Dictionary toRename = new Dictionary + private static readonly Dictionary ToRename = new Dictionary { {"gitted", ".git"}, {"gitmodules", ".gitmodules"}, @@ -29,7 +28,7 @@ public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo targ private static string Rename(string name) { - return toRename.ContainsKey(name) ? toRename[name] : name; + return ToRename.ContainsKey(name) ? ToRename[name] : name; } public static void DeleteSubDirectories(string parentPath) @@ -79,8 +78,8 @@ public static void DeleteDirectory(string directoryPath) "{0}Known and common causes include:" + "{0}- Windows Search Indexer (go to the Indexing Options, in the Windows Control Panel, and exclude the bin folder of LibGit2Sharp.Tests)" + "{0}- Antivirus (exclude the bin folder of LibGit2Sharp.Tests from the paths scanned by your real-time antivirus){0}", - Environment.NewLine, Path.GetFullPath(directoryPath))); + System.Environment.NewLine, Path.GetFullPath(directoryPath))); } } } -} \ No newline at end of file +} diff --git a/src/GitVersionTask.Tests/Helpers/IPostTestDirectoryRemover.cs b/src/GitVersionTask.Tests/Helpers/IPostTestDirectoryRemover.cs index a308293be4..4ec0eeabc4 100644 --- a/src/GitVersionTask.Tests/Helpers/IPostTestDirectoryRemover.cs +++ b/src/GitVersionTask.Tests/Helpers/IPostTestDirectoryRemover.cs @@ -1,4 +1,4 @@ -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public interface IPostTestDirectoryRemover { diff --git a/src/GitVersionTask.Tests/Helpers/PathHelper.cs b/src/GitVersionTask.Tests/Helpers/PathHelper.cs index e85c6f16a2..21700fccff 100644 --- a/src/GitVersionTask.Tests/Helpers/PathHelper.cs +++ b/src/GitVersionTask.Tests/Helpers/PathHelper.cs @@ -2,7 +2,7 @@ using System.IO; using System.Reflection; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public static class PathHelper { diff --git a/src/GitVersionTask.Tests/Helpers/Scrubbers.cs b/src/GitVersionTask.Tests/Helpers/Scrubbers.cs index eb5f91b906..796ef7e7ba 100644 --- a/src/GitVersionTask.Tests/Helpers/Scrubbers.cs +++ b/src/GitVersionTask.Tests/Helpers/Scrubbers.cs @@ -1,6 +1,6 @@ using System.Text.RegularExpressions; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public static class Scrubbers { diff --git a/src/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs b/src/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs index e5b7d465ad..bdd84edb3e 100644 --- a/src/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs +++ b/src/GitVersionTask.Tests/Helpers/SelfCleaningDirectory.cs @@ -1,7 +1,7 @@ using System; using System.IO; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public class SelfCleaningDirectory { diff --git a/src/GitVersionTask.Tests/Helpers/TestEffectiveConfiguration.cs b/src/GitVersionTask.Tests/Helpers/TestEffectiveConfiguration.cs index 2e05e3200c..c2eeb0b276 100644 --- a/src/GitVersionTask.Tests/Helpers/TestEffectiveConfiguration.cs +++ b/src/GitVersionTask.Tests/Helpers/TestEffectiveConfiguration.cs @@ -1,12 +1,11 @@ using System.Collections.Generic; using System.Linq; -using GitVersion; using GitVersion.Configuration; using GitVersion.VersionFilters; using GitVersion.VersioningModes; using GitVersion.Extensions; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public class TestEffectiveConfiguration : EffectiveConfiguration { @@ -47,4 +46,4 @@ public TestEffectiveConfiguration( { } } -} \ No newline at end of file +} diff --git a/src/GitVersionTask.Tests/Helpers/TestEnvironment.cs b/src/GitVersionTask.Tests/Helpers/TestEnvironment.cs index 3d1d0c02b2..4707ab8bc4 100644 --- a/src/GitVersionTask.Tests/Helpers/TestEnvironment.cs +++ b/src/GitVersionTask.Tests/Helpers/TestEnvironment.cs @@ -1,11 +1,10 @@ using System.Collections.Generic; -using GitVersion.Common; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public class TestEnvironment : IEnvironment { - private IDictionary map; + private readonly IDictionary map; public TestEnvironment() { diff --git a/src/GitVersionTask.Tests/Helpers/TestFileSystem.cs b/src/GitVersionTask.Tests/Helpers/TestFileSystem.cs index a23f128752..64a76d08b3 100644 --- a/src/GitVersionTask.Tests/Helpers/TestFileSystem.cs +++ b/src/GitVersionTask.Tests/Helpers/TestFileSystem.cs @@ -3,13 +3,12 @@ using System.IO; using System.Text; using GitVersion.Helpers; -using GitVersion.Common; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public class TestFileSystem : IFileSystem { - private Dictionary fileSystem = new Dictionary(); + private readonly Dictionary fileSystem = new Dictionary(); public void Copy(string @from, string to, bool overwrite) { diff --git a/src/GitVersionTask.Tests/Helpers/TestStream.cs b/src/GitVersionTask.Tests/Helpers/TestStream.cs index f7594e0763..59a63ca267 100644 --- a/src/GitVersionTask.Tests/Helpers/TestStream.cs +++ b/src/GitVersionTask.Tests/Helpers/TestStream.cs @@ -1,12 +1,12 @@ using System.IO; -namespace GitVersionTask.Tests.Helpers +namespace GitVersion.MSBuildTask.Tests.Helpers { public class TestStream : Stream { private readonly string path; private readonly TestFileSystem testFileSystem; - private MemoryStream underlying = new MemoryStream(); + private readonly MemoryStream underlying = new MemoryStream(); public TestStream(string path, TestFileSystem testFileSystem) { diff --git a/src/GitVersionTask.Tests/InvalidFileCheckerTests.cs b/src/GitVersionTask.Tests/InvalidFileCheckerTests.cs index 480b22e9cf..d4a3aefe4f 100644 --- a/src/GitVersionTask.Tests/InvalidFileCheckerTests.cs +++ b/src/GitVersionTask.Tests/InvalidFileCheckerTests.cs @@ -1,11 +1,11 @@ using System; using System.IO; -using GitVersionTask.Tests.Mocks; using Microsoft.Build.Framework; using NUnit.Framework; using GitVersion.Exceptions; +using GitVersion.MSBuildTask.Tests.Mocks; -namespace GitVersionTask.Tests +namespace GitVersion.MSBuildTask.Tests { [TestFixture] public class InvalidFileCheckerTests : TestBase diff --git a/src/GitVersionTask.Tests/Mocks/MockTaskItem.cs b/src/GitVersionTask.Tests/Mocks/MockTaskItem.cs index fff805e85c..feb3fb59a6 100644 --- a/src/GitVersionTask.Tests/Mocks/MockTaskItem.cs +++ b/src/GitVersionTask.Tests/Mocks/MockTaskItem.cs @@ -2,7 +2,7 @@ using System.Collections; using Microsoft.Build.Framework; -namespace GitVersionTask.Tests.Mocks +namespace GitVersion.MSBuildTask.Tests.Mocks { internal class MockTaskItem : ITaskItem { diff --git a/src/GitVersionTask.Tests/TestBase.cs b/src/GitVersionTask.Tests/TestBase.cs index 1b1911195f..f6838409f1 100644 --- a/src/GitVersionTask.Tests/TestBase.cs +++ b/src/GitVersionTask.Tests/TestBase.cs @@ -1,4 +1,4 @@ -namespace GitVersionTask.Tests +namespace GitVersion.MSBuildTask.Tests { public class TestBase { diff --git a/src/GitVersionTask/FileHelper.cs b/src/GitVersionTask/FileHelper.cs index 79ade1da97..9fb844152b 100644 --- a/src/GitVersionTask/FileHelper.cs +++ b/src/GitVersionTask/FileHelper.cs @@ -6,7 +6,7 @@ using Microsoft.Build.Framework; using GitVersion.Exceptions; -namespace GitVersionTask +namespace GitVersion.MSBuildTask { public sealed class FileWriteInfo { @@ -24,7 +24,7 @@ public FileWriteInfo(string workingDirectory, string fileName, string fileExtens public static class FileHelper { - private static readonly Dictionary> versionAttributeFinders = new Dictionary>() + private static readonly Dictionary> VersionAttributeFinders = new Dictionary>() { { ".cs", CSharpFileContainsVersionAttribute }, { ".vb", VisualBasicFileContainsVersionAttribute } @@ -63,17 +63,13 @@ public static void DeleteTempFiles() public static string GetFileExtension(string language) { - switch (language) + return language switch { - case "C#": - return "cs"; - case "F#": - return "fs"; - case "VB": - return "vb"; - default: - throw new ArgumentException($"Unknown language detected: '{language}'"); - } + "C#" => "cs", + "F#" => "fs", + "VB" => "vb", + _ => throw new ArgumentException($"Unknown language detected: '{language}'") + }; } public static void CheckForInvalidFiles(IEnumerable compileFiles, string projectFile) @@ -88,7 +84,7 @@ private static bool FileContainsVersionAttribute(string compileFile, string proj { var compileFileExtension = Path.GetExtension(compileFile); - if (versionAttributeFinders.TryGetValue(compileFileExtension, out var languageSpecificFileContainsVersionAttribute)) + if (VersionAttributeFinders.TryGetValue(compileFileExtension, out var languageSpecificFileContainsVersionAttribute)) { return languageSpecificFileContainsVersionAttribute(compileFile, projectFile); } @@ -108,7 +104,7 @@ private static bool CSharpFileContainsVersionAttribute(string compileFile, strin var noCommentsOrStrings = Regex.Replace(allText, blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings, - me => me.Value.StartsWith("//") ? Environment.NewLine : string.Empty, + me => me.Value.StartsWith("//") ? System.Environment.NewLine : string.Empty, RegexOptions.Singleline); return Regex.IsMatch(noCommentsOrStrings, @"(?x) # IgnorePatternWhitespace @@ -132,7 +128,7 @@ private static bool VisualBasicFileContainsVersionAttribute(string compileFile, var noCommentsOrStrings = Regex.Replace(allText, lineComments + "|" + strings, - me => me.Value.StartsWith("'") ? Environment.NewLine : string.Empty, + me => me.Value.StartsWith("'") ? System.Environment.NewLine : string.Empty, RegexOptions.Singleline); return Regex.IsMatch(noCommentsOrStrings, @"(?x) # IgnorePatternWhitespace diff --git a/src/GitVersionTask/GitVersionTask.csproj b/src/GitVersionTask/GitVersionTask.csproj index a2159bbed5..4cb15601e8 100644 --- a/src/GitVersionTask/GitVersionTask.csproj +++ b/src/GitVersionTask/GitVersionTask.csproj @@ -17,6 +17,7 @@ + diff --git a/src/GitVersionTask/GitVersionTask.nuspec b/src/GitVersionTask/GitVersionTask.nuspec index 978dd6d8f7..5f2f4d9382 100644 --- a/src/GitVersionTask/GitVersionTask.nuspec +++ b/src/GitVersionTask/GitVersionTask.nuspec @@ -25,18 +25,20 @@ - - - - + + + + + - - - + + + + - - - + + + diff --git a/src/GitVersionTask/GitVersionTaskExecutor.cs b/src/GitVersionTask/GitVersionTaskExecutor.cs new file mode 100644 index 0000000000..337c0d0c48 --- /dev/null +++ b/src/GitVersionTask/GitVersionTaskExecutor.cs @@ -0,0 +1,79 @@ +using System; +using System.IO; +using GitVersion.Extensions.GitVersionInformationResources; +using GitVersion.Extensions.VersionAssemblyInfoResources; +using GitVersion.Logging; +using GitVersion.OutputFormatters; +using GitVersion.MSBuildTask.Tasks; + +namespace GitVersion.MSBuildTask +{ + public class GitVersionTaskExecutor : IGitVersionTaskExecutor + { + private readonly IFileSystem fileSystem; + private readonly ILog log; + private readonly IBuildServerResolver buildServerResolver; + private readonly IGitVersionCalculator gitVersionCalculator; + + public GitVersionTaskExecutor(IFileSystem fileSystem, ILog log, IBuildServerResolver buildServerResolver, IGitVersionCalculator gitVersionCalculator) + { + this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); + this.log = log ?? throw new ArgumentNullException(nameof(log)); + this.buildServerResolver = buildServerResolver ?? throw new ArgumentNullException(nameof(buildServerResolver)); + this.gitVersionCalculator = gitVersionCalculator ?? throw new ArgumentNullException(nameof(gitVersionCalculator)); + } + + public void GetVersion(GetVersion task) + { + gitVersionCalculator.TryCalculateVersionVariables(out var versionVariables); + var outputType = typeof(GetVersion); + foreach (var variable in versionVariables) + { + outputType.GetProperty(variable.Key)?.SetValue(task, variable.Value, null); + } + } + + public void UpdateAssemblyInfo(UpdateAssemblyInfo task) + { + FileHelper.DeleteTempFiles(); + FileHelper.CheckForInvalidFiles(task.CompileFiles, task.ProjectFile); + + gitVersionCalculator.TryCalculateVersionVariables(out var versionVariables); + var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "AssemblyInfo"); + + task.AssemblyInfoTempFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); + + using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(fileWriteInfo.FileName, fileWriteInfo.WorkingDirectory, versionVariables, fileSystem, log, true); + assemblyInfoFileUpdater.Update(); + assemblyInfoFileUpdater.CommitChanges(); + } + + public void GenerateGitVersionInformation(GenerateGitVersionInformation task) + { + gitVersionCalculator.TryCalculateVersionVariables(out var versionVariables); + var fileWriteInfo = task.IntermediateOutputPath.GetFileWriteInfo(task.Language, task.ProjectFile, "GitVersionInformation"); + + task.GitVersionInformationFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); + var generator = new GitVersionInformationGenerator(fileWriteInfo.FileName, fileWriteInfo.WorkingDirectory, versionVariables, fileSystem); + generator.Generate(); + } + + public void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) + { + var logger = task.Log; + + gitVersionCalculator.TryCalculateVersionVariables(out var versionVariables); + var buildServer = buildServerResolver.Resolve(); + if (buildServer != null) + { + logger.LogMessage($"Executing GenerateSetVersionMessage for '{buildServer.GetType().Name}'."); + logger.LogMessage(buildServer.GenerateSetVersionMessage(versionVariables)); + logger.LogMessage($"Executing GenerateBuildLogOutput for '{buildServer.GetType().Name}'."); + foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(buildServer, versionVariables)) + { + logger.LogMessage(buildParameter); + } + } + } + } +} diff --git a/src/GitVersionTask/GitVersionTasks.cs b/src/GitVersionTask/GitVersionTasks.cs index db3ea685cc..8269d8f28a 100644 --- a/src/GitVersionTask/GitVersionTasks.cs +++ b/src/GitVersionTask/GitVersionTasks.cs @@ -1,109 +1,32 @@ using System; -using System.IO; -using GitVersion; -using GitVersion.BuildServers; -using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.OutputFormatters; -using GitVersion.OutputVariables; -using GitVersionTask.MsBuild; -using GitVersionTask.MsBuild.Tasks; -using GitVersion.Extensions.GitVersionInformationResources; -using GitVersion.Extensions.VersionAssemblyInfoResources; -using GitVersion.Common; -using GitVersion.Logging; -using Environment = GitVersion.Common.Environment; +using GitVersion.Extensions; +using GitVersion.MSBuildTask.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; -namespace GitVersionTask +namespace GitVersion.MSBuildTask { public static class GitVersionTasks { - private static readonly ILog log; - private static readonly IEnvironment environment; - private static readonly IFileSystem fileSystem; + public static bool GetVersion(GetVersion task) => ExecuteGitVersionTask(task, executor => executor.GetVersion(task)); - static GitVersionTasks() - { - log = new Log(); - environment = new Environment(); - fileSystem = new FileSystem(); - } - - public static bool GetVersion(GetVersion task) - { - return ExecuteGitVersionTask(task, t => - { - if (!GetVersionVariables(t, out var versionVariables)) return; - - var outputType = typeof(GetVersion); - foreach (var variable in versionVariables) - { - outputType.GetProperty(variable.Key)?.SetValue(task, variable.Value, null); - } - }); - } - - public static bool UpdateAssemblyInfo(UpdateAssemblyInfo task) - { - return ExecuteGitVersionTask(task, t => - { - FileHelper.DeleteTempFiles(); - FileHelper.CheckForInvalidFiles(t.CompileFiles, t.ProjectFile); - - if (!GetVersionVariables(t, out var versionVariables)) return; - - var fileWriteInfo = t.IntermediateOutputPath.GetFileWriteInfo(t.Language, t.ProjectFile, "AssemblyInfo"); - - t.AssemblyInfoTempFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - - using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(fileWriteInfo.FileName, fileWriteInfo.WorkingDirectory, versionVariables, new FileSystem(), log, true); - assemblyInfoFileUpdater.Update(); - assemblyInfoFileUpdater.CommitChanges(); - }); - } + public static bool UpdateAssemblyInfo(UpdateAssemblyInfo task) => ExecuteGitVersionTask(task, executor => executor.UpdateAssemblyInfo(task)); - public static bool GenerateGitVersionInformation(GenerateGitVersionInformation task) - { - return ExecuteGitVersionTask(task, t => - { - if (!GetVersionVariables(t, out var versionVariables)) return; - - var fileWriteInfo = t.IntermediateOutputPath.GetFileWriteInfo(t.Language, t.ProjectFile, "GitVersionInformation"); - - t.GitVersionInformationFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - var generator = new GitVersionInformationGenerator(fileWriteInfo.FileName, fileWriteInfo.WorkingDirectory, versionVariables, new FileSystem()); - generator.Generate(); - }); - } + public static bool GenerateGitVersionInformation(GenerateGitVersionInformation task) => ExecuteGitVersionTask(task, executor => executor.GenerateGitVersionInformation(task)); - public static bool WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) - { - return ExecuteGitVersionTask(task, t => - { - if (!GetVersionVariables(task, out var versionVariables)) return; + public static bool WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) => ExecuteGitVersionTask(task, executor => executor.WriteVersionInfoToBuildLog(task)); - var logger = t.Log; - BuildServerList.Init(environment, log); - foreach (var buildServer in BuildServerList.GetApplicableBuildServers(log)) - { - logger.LogMessage($"Executing GenerateSetVersionMessage for '{ buildServer.GetType().Name }'."); - logger.LogMessage(buildServer.GenerateSetVersionMessage(versionVariables)); - logger.LogMessage($"Executing GenerateBuildLogOutput for '{ buildServer.GetType().Name }'."); - foreach (var buildParameter in BuildOutputFormatter.GenerateBuildLogOutput(buildServer, versionVariables)) - { - logger.LogMessage(buildParameter); - } - } - }); - } - - private static bool ExecuteGitVersionTask(T task, Action action) + private static bool ExecuteGitVersionTask(T task, Action action) where T : GitVersionTaskBase { var taskLog = task.Log; try { - action(task); + var sp = BuildServiceProvider(task); + var gitVersionTaskExecutor = sp.GetService(); + + action(gitVersionTaskExecutor); } catch (WarningException errorException) { @@ -119,13 +42,23 @@ private static bool ExecuteGitVersionTask(T task, Action action) return !taskLog.HasLoggedErrors; } - private static bool GetVersionVariables(GitVersionTaskBase task, out VersionVariables versionVariables) - => new ExecuteCore(fileSystem, environment, log, GetLocator(task.ConfigFilePath)) - .TryGetVersion(task.SolutionDirectory, out versionVariables, task.NoFetch, new Authentication()); + private static IServiceProvider BuildServiceProvider(GitVersionTaskBase task) + { + var services = new ServiceCollection(); - private static IConfigFileLocator GetLocator(string filePath = null) => - !string.IsNullOrEmpty(filePath) - ? (IConfigFileLocator) new NamedConfigFileLocator(filePath, fileSystem, log) - : new DefaultConfigFileLocator(fileSystem, log); + var arguments = new Arguments + { + TargetPath = task.SolutionDirectory, + ConfigFile = task.ConfigFilePath, + NoFetch = task.NoFetch + }; + + services.AddSingleton(_ => Options.Create(arguments)); + services.AddSingleton(); + services.AddModule(new GitVersionCoreModule()); + + var sp = services.BuildServiceProvider(); + return sp; + } } } diff --git a/src/GitVersionTask/IGitVersionTaskExecutor.cs b/src/GitVersionTask/IGitVersionTaskExecutor.cs new file mode 100644 index 0000000000..1c6808e6d5 --- /dev/null +++ b/src/GitVersionTask/IGitVersionTaskExecutor.cs @@ -0,0 +1,12 @@ +using GitVersion.MSBuildTask.Tasks; + +namespace GitVersion.MSBuildTask +{ + public interface IGitVersionTaskExecutor + { + void GetVersion(GetVersion task); + void UpdateAssemblyInfo(UpdateAssemblyInfo task); + void GenerateGitVersionInformation(GenerateGitVersionInformation task); + void WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task); + } +}