diff --git a/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs b/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs index 81dec3a96b..e52e5274ac 100644 --- a/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs +++ b/src/GitVersionCore.Tests/AssemblyInfoFileUpdaterTests.cs @@ -9,6 +9,7 @@ using GitVersion.Extensions; using GitVersion.Extensions.VersionAssemblyInfoResources; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -16,10 +17,15 @@ namespace GitVersionCore.Tests [Parallelizable(ParallelScope.None)] public class AssemblyInfoFileUpdaterTests : TestBase { + private IVariableProvider variableProvider; + private ILog log; + [SetUp] public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); + log = new NullLog(); + variableProvider = new VariableProvider(log); } [TestCase("cs")] @@ -33,9 +39,9 @@ public void ShouldCreateAssemblyInfoFileWhenNotExistsAndEnsureAssemblyInfo(strin var workingDir = Path.GetTempPath(); var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension; var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, true)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, true)) { assemblyInfoFileUpdater.Update(); @@ -54,9 +60,9 @@ public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo var workingDir = Path.GetTempPath(); var assemblyInfoFile = Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension); var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, true)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, true)) { assemblyInfoFileUpdater.Update(); @@ -78,9 +84,9 @@ public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInf "AssemblyInfo." + fileExtension, Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension) }; - var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFiles, workingDir, variables, fileSystem, true)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFiles, workingDir, variables, fileSystem, log, true)) { assemblyInfoFileUpdater.Update(); @@ -101,9 +107,9 @@ public void ShouldNotCreateAssemblyInfoFileWhenNotExistsAndNotEnsureAssemblyInfo var workingDir = Path.GetTempPath(); var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension; var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -118,9 +124,9 @@ public void ShouldNotCreateAssemblyInfoFileForUnknownSourceCodeAndEnsureAssembly var workingDir = Path.GetTempPath(); var assemblyInfoFile = "VersionAssemblyInfo.js"; var fullPath = Path.Combine(workingDir, assemblyInfoFile); - var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, true)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, true)) { assemblyInfoFileUpdater.Update(); @@ -134,9 +140,9 @@ public void ShouldStartSearchFromWorkingDirectory() var fileSystem = Substitute.For(); var workingDir = Path.GetTempPath(); var assemblyInfoFiles = new HashSet(); - var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); + var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFiles, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFiles, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -155,7 +161,7 @@ public void ShouldReplaceAssemblyVersion(string fileExtension, string assemblyFi VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -180,7 +186,7 @@ public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileEx VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, verify: (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -201,7 +207,7 @@ public void ShouldReplaceAssemblyVersionInRelativePath(string fileExtension, str VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -224,7 +230,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithWhiteSpace(string file VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -247,7 +253,7 @@ public void ShouldReplaceAssemblyVersionWithStar(string fileExtension, string as VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -270,7 +276,7 @@ public void ShouldReplaceAssemblyVersionWithAtttributeSuffix(string fileExtensio VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -296,7 +302,7 @@ public void ShouldAddAssemblyVersionIfMissingFromInfoFile(string fileExtension) VerifyAssemblyInfoFile("", fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -319,7 +325,7 @@ public void ShouldReplaceAlreadySubstitutedValues(string fileExtension, string a VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -342,7 +348,7 @@ public void ShouldReplaceAssemblyVersionWhenCreatingAssemblyVersionFileAndEnsure VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -365,7 +371,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariables(string fileE VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -388,7 +394,7 @@ public void ShouldReplaceAssemblyVersionInRelativePathWithVariablesAndWhiteSpace VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -413,7 +419,7 @@ public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -436,7 +442,7 @@ public void Issue1183_ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttr VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -459,7 +465,7 @@ public void ShouldNotAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionF VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, verify: (fileSystem, variables) => { - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, false)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(assemblyInfoFile, workingDir, variables, fileSystem, log, false)) { assemblyInfoFileUpdater.Update(); @@ -469,7 +475,7 @@ public void ShouldNotAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionF }); } - private static void VerifyAssemblyInfoFile( + private void VerifyAssemblyInfoFile( string assemblyFileContent, string fileName, AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch, @@ -493,7 +499,7 @@ private static void VerifyAssemblyInfoFile( }); var config = new TestEffectiveConfiguration(assemblyVersioningScheme: versioningScheme); - var variables = VariableProvider.GetVariablesFor(version, config, false); + var variables = variableProvider.GetVariablesFor(version, config, false); verify?.Invoke(fileSystem, variables); } diff --git a/src/GitVersionCore.Tests/BuildServers/VsoAgentBuildNumberTests.cs b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs similarity index 75% rename from src/GitVersionCore.Tests/BuildServers/VsoAgentBuildNumberTests.cs rename to src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs index c8fe8c14b0..c2c61b4022 100644 --- a/src/GitVersionCore.Tests/BuildServers/VsoAgentBuildNumberTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesBuildNumberTests.cs @@ -2,27 +2,30 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { [TestFixture] - public class VsoAgentBuildNumberTests : TestBase + public class AzurePipelinesBuildNumberTests : TestBase { string key = "BUILD_BUILDNUMBER"; string logPrefix = "##vso[build.updatebuildnumber]"; - VsoAgent versionBuilder; + AzurePipelines versionBuilder; private IEnvironment environment; + private ILog log; [SetUp] public void SetUp() { environment = new TestEnvironment(); - versionBuilder = new VsoAgent(environment); + log = new NullLog(); + versionBuilder = new AzurePipelines(environment, log); } [TearDown] - public void TearDownVsoAgentBuildNumberTest() + public void TearDownAzurePipelinesBuildNumberTest() { environment.SetEnvironmentVariable(key, null); } @@ -32,7 +35,7 @@ public void TearDownVsoAgentBuildNumberTest() [TestCase("$(GITVERSION_FULLSEMVER)", "1.0.0", "1.0.0")] [TestCase("$(GitVersion.FullSemVer)-Build.1234", "1.0.0", "1.0.0-Build.1234")] [TestCase("$(GITVERSION_FULLSEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")] - public void VsoAgentBuildNumberWithFullSemVer(string buildNumberFormat, string myFullSemVer, string expectedBuildNumber) + public void AzurePipelinesBuildNumberWithFullSemVer(string buildNumberFormat, string myFullSemVer, string expectedBuildNumber) { environment.SetEnvironmentVariable(key, buildNumberFormat); var vars = new TestableVersionVariables(fullSemVer: myFullSemVer); @@ -45,7 +48,7 @@ public void VsoAgentBuildNumberWithFullSemVer(string buildNumberFormat, string m [TestCase("$(GITVERSION_SEMVER)", "1.0.0", "1.0.0")] [TestCase("$(GitVersion.SemVer)-Build.1234", "1.0.0", "1.0.0-Build.1234")] [TestCase("$(GITVERSION_SEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")] - public void VsoAgentBuildNumberWithSemVer(string buildNumberFormat, string mySemVer, string expectedBuildNumber) + public void AzurePipelinesBuildNumberWithSemVer(string buildNumberFormat, string mySemVer, string expectedBuildNumber) { environment.SetEnvironmentVariable(key, buildNumberFormat); var vars = new TestableVersionVariables(semVer: mySemVer); diff --git a/src/GitVersionCore.Tests/BuildServers/VsoAgentTests.cs b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs similarity index 84% rename from src/GitVersionCore.Tests/BuildServers/VsoAgentTests.cs rename to src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs index 3b5973f52f..5c0bd15d0f 100644 --- a/src/GitVersionCore.Tests/BuildServers/VsoAgentTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/AzurePipelinesTests.cs @@ -2,20 +2,23 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { [TestFixture] - public class VsoAgentTests : TestBase + public class AzurePipelinesTests : TestBase { string key = "BUILD_BUILDNUMBER"; private IEnvironment environment; + private ILog log; [SetUp] public void SetEnvironmentVariableForTest() { environment = new TestEnvironment(); + log = new NullLog(); environment.SetEnvironmentVariable(key, "Some Build_Value $(GitVersion_FullSemVer) 20151310.3 $(UnknownVar) Release"); } @@ -28,7 +31,7 @@ public void ClearEnvironmentVariableForTest() [Test] public void Develop_branch() { - var versionBuilder = new VsoAgent(environment); + var versionBuilder = new AzurePipelines(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); var vsVersion = versionBuilder.GenerateSetVersionMessage(vars); @@ -38,7 +41,7 @@ public void Develop_branch() [Test] public void EscapeValues() { - var versionBuilder = new VsoAgent(environment); + var versionBuilder = new AzurePipelines(environment, log); var vsVersion = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); vsVersion[0].ShouldBe("##vso[task.setvariable variable=GitVersion.Foo;]0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); @@ -49,7 +52,7 @@ public void MissingEnvShouldNotBlowUp() { environment.SetEnvironmentVariable(key, null); - var versionBuilder = new VsoAgent(environment); + var versionBuilder = new AzurePipelines(environment, log); var semver = "0.0.0-Unstable4"; var vars = new TestableVersionVariables(fullSemVer: semver); var vsVersion = versionBuilder.GenerateSetVersionMessage(vars); diff --git a/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs b/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs index 4e4b09bdfb..68f336c98f 100644 --- a/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/BuildServerBaseTests.cs @@ -5,6 +5,7 @@ using Shouldly; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -13,11 +14,15 @@ public class BuildServerBaseTests : TestBase { private IEnvironment environment; + private ILog log; + private IVariableProvider variableProvider; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); + variableProvider = new VariableProvider(log); } [Test] @@ -38,8 +43,8 @@ public void BuildNumberIsFullSemVer() var config = new TestEffectiveConfiguration(); - var variables = VariableProvider.GetVariablesFor(semanticVersion, config, false); - new BuildServer(environment).WriteIntegration(writes.Add, variables); + var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); + new BuildServer(environment, log).WriteIntegration(writes.Add, variables); writes[1].ShouldBe("1.2.3-beta.1+5"); } @@ -48,7 +53,7 @@ class BuildServer : BuildServerBase { protected override string EnvironmentVariable { get; } - public BuildServer(IEnvironment environment) : base(environment) + public BuildServer(IEnvironment environment, ILog log) : base(environment, log) { } diff --git a/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs b/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs index e043527842..7c016a7b30 100644 --- a/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/CodeBuildTests.cs @@ -8,6 +8,7 @@ using GitVersion.BuildServers; using GitVersion.Common; using GitVersion.OutputVariables; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -15,18 +16,23 @@ namespace GitVersionCore.Tests.BuildServers public sealed class CodeBuildTests : TestBase { private IEnvironment environment; + private ILog log; + private IVariableProvider variableProvider; [SetUp] public void SetUp() { + log = new NullLog(); + environment = new TestEnvironment(); + variableProvider = new VariableProvider(log); } [Test] public void CorrectlyIdentifiesCodeBuildPresence() { environment.SetEnvironmentVariable(CodeBuild.HeadRefEnvironmentName, "a value"); - var cb = new CodeBuild(environment); + var cb = new CodeBuild(environment, log); cb.CanApplyToCurrentContext().ShouldBe(true); } @@ -34,7 +40,7 @@ public void CorrectlyIdentifiesCodeBuildPresence() public void PicksUpBranchNameFromEnvironment() { environment.SetEnvironmentVariable(CodeBuild.HeadRefEnvironmentName, "refs/heads/master"); - var cb = new CodeBuild(environment); + var cb = new CodeBuild(environment, log); cb.GetCurrentBranch(false).ShouldBe("refs/heads/master"); } @@ -71,9 +77,9 @@ private void AssertVariablesAreWrittenToFile(string f) var config = new TestEffectiveConfiguration(); - var variables = VariableProvider.GetVariablesFor(semanticVersion, config, false); + var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); - var j = new CodeBuild(environment, f); + var j = new CodeBuild(environment, log, f); j.WriteIntegration(writes.Add, variables); diff --git a/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs b/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs index 6203682b9b..3aeb25b101 100644 --- a/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/ContinuaCiTests.cs @@ -1,6 +1,7 @@ using NUnit.Framework; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -8,17 +9,19 @@ namespace GitVersionCore.Tests.BuildServers public class ContinuaCiTests : TestBase { private IEnvironment environment; + private ILog log; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); } [Test] public void GenerateBuildVersion() { - var versionBuilder = new ContinuaCi(environment); + var versionBuilder = new ContinuaCi(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); var continuaCiVersion = versionBuilder.GenerateSetVersionMessage(vars); Assert.AreEqual("@@continua[setBuildVersion value='0.0.0-Beta4.7']", continuaCiVersion); diff --git a/src/GitVersionCore.Tests/BuildServers/DroneTests.cs b/src/GitVersionCore.Tests/BuildServers/DroneTests.cs index d9e43f7410..6890d23a9e 100644 --- a/src/GitVersionCore.Tests/BuildServers/DroneTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/DroneTests.cs @@ -1,5 +1,6 @@ using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; using NUnit.Framework; using Shouldly; @@ -9,10 +10,12 @@ namespace GitVersionCore.Tests.BuildServers public class DroneTests : TestBase { private IEnvironment environment; + private ILog log; [SetUp] public void SetUp() { + log = new NullLog(); environment = new TestEnvironment(); environment.SetEnvironmentVariable("DRONE", "true"); } @@ -27,7 +30,7 @@ public void TearDown() public void CanApplyToCurrentContext_ShouldBeTrue_WhenEnvironmentVariableIsSet() { // Arrange - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.CanApplyToCurrentContext(); @@ -41,7 +44,7 @@ public void CanApplyToCurrentContext_ShouldBeFalse_WhenEnvironmentVariableIsNotS { // Arrange environment.SetEnvironmentVariable("DRONE", ""); - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.CanApplyToCurrentContext(); @@ -59,7 +62,7 @@ public void GetCurrentBranch_ShouldDroneBranch_InCaseOfPush() environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", ""); environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.GetCurrentBranch(false); @@ -76,7 +79,7 @@ public void GetCurrentBranch_ShouldUseDroneSourceBranch_InCaseOfPullRequestAndNo environment.SetEnvironmentVariable("DRONE_PULL_REQUEST", "1"); environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", droneSourceBranch); - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.GetCurrentBranch(false); @@ -98,7 +101,7 @@ public void GetCurrentBranch_ShouldUseSourceBranchFromCiCommitRefSpec_InCaseOfPu environment.SetEnvironmentVariable("DRONE_SOURCE_BRANCH", ""); environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ciCommitRefSpec); - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.GetCurrentBranch(false); @@ -118,7 +121,7 @@ public void GetCurrentBranch_ShouldUseDroneBranch_InCaseOfPullRequestAndEmptyDro environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ""); environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.GetCurrentBranch(false); @@ -142,7 +145,7 @@ public void GetCurrentBranch_ShouldUseDroneBranch_InCaseOfPullRequestAndEmptyDro environment.SetEnvironmentVariable("CI_COMMIT_REFSPEC", ciCommitRefSpec); environment.SetEnvironmentVariable("DRONE_BRANCH", droneBranch); - var buildServer = new Drone(environment); + var buildServer = new Drone(environment, log); // Act var result = buildServer.GetCurrentBranch(false); diff --git a/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs b/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs index 8a2f0bfef5..7a66db7d0c 100644 --- a/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/EnvRunTests.cs @@ -3,6 +3,7 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -12,11 +13,13 @@ public class EnvRunTests : TestBase private const string EnvVarName = "ENVRUN_DATABASE"; private string mFilePath; private IEnvironment environment; + private ILog log; [SetUp] public void SetEnvironmentVariableForTest() { environment = new TestEnvironment(); + log = new NullLog(); // set environment variable and create an empty envrun file to indicate that EnvRun is running... mFilePath = Path.Combine(Path.GetTempPath(), "envrun.db"); environment.SetEnvironmentVariable(EnvVarName, mFilePath); @@ -33,7 +36,7 @@ public void ClearEnvironmentVariableForTest() [Test] public void CanApplyToCurrentContext() { - EnvRun envrun = new EnvRun(environment); + EnvRun envrun = new EnvRun(environment, log); bool applys = envrun.CanApplyToCurrentContext(); applys.ShouldBeTrue(); } @@ -42,7 +45,7 @@ public void CanApplyToCurrentContext() public void CanApplyToCurrentContext_EnvironmentVariableNotSet() { environment.SetEnvironmentVariable(EnvVarName, null); - EnvRun envrun = new EnvRun(environment); + EnvRun envrun = new EnvRun(environment, log); bool applys = envrun.CanApplyToCurrentContext(); applys.ShouldBeFalse(); } @@ -51,7 +54,7 @@ public void CanApplyToCurrentContext_EnvironmentVariableNotSet() [TestCase("1.2.3-rc4")] public void GenerateSetVersionMessage(string fullSemVer) { - EnvRun envrun = new EnvRun(environment); + EnvRun envrun = new EnvRun(environment, log); var vars = new TestableVersionVariables(fullSemVer: fullSemVer); var version = envrun.GenerateSetVersionMessage(vars); version.ShouldBe(fullSemVer); @@ -61,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); + EnvRun 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 b3fabfc0dd..98003f1af3 100644 --- a/src/GitVersionCore.Tests/BuildServers/EnvironmentVariableJenkinsTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/EnvironmentVariableJenkinsTests.cs @@ -2,6 +2,7 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -13,11 +14,13 @@ public class EnvironmentVariableJenkinsTests : TestBase string localBranch = "GIT_LOCAL_BRANCH"; string pipelineBranch = "BRANCH_NAME"; private IEnvironment environment; + private ILog log; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); } @@ -35,7 +38,7 @@ private void ClearenvironmentVariableForDetection() public void CanApplyCurrentContextWhenenvironmentVariableIsSet() { SetEnvironmentVariableForDetection(); - var j = new Jenkins(environment); + var j = new Jenkins(environment, log); j.CanApplyToCurrentContext().ShouldBe(true); } @@ -43,7 +46,7 @@ public void CanApplyCurrentContextWhenenvironmentVariableIsSet() public void CanNotApplyCurrentContextWhenenvironmentVariableIsNotSet() { ClearenvironmentVariableForDetection(); - var j = new Jenkins(environment); + var j = new Jenkins(environment, log); j.CanApplyToCurrentContext().ShouldBe(false); } @@ -58,7 +61,7 @@ public void JenkinsTakesLocalBranchNameNotRemoteName() environment.SetEnvironmentVariable(branch, "origin/master"); // Test Jenkins that GetCurrentBranch falls back to GIT_BRANCH if GIT_LOCAL_BRANCH undefined - var j = new Jenkins(environment); + var j = new Jenkins(environment, log); j.GetCurrentBranch(true).ShouldBe("origin/master"); // Set GIT_LOCAL_BRANCH @@ -87,7 +90,7 @@ public void JenkinsTakesBranchNameInPipelineAsCode() environment.SetEnvironmentVariable(localBranch, null); // Test Jenkins GetCurrentBranch method now returns BRANCH_NAME - var j = new Jenkins(environment); + var j = new Jenkins(environment, log); j.GetCurrentBranch(true).ShouldBe("master"); // Restore environment variables diff --git a/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs b/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs index 4c9e89ad00..87e2e5651a 100755 --- a/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs +++ b/src/GitVersionCore.Tests/BuildServers/GitLabCiMessageGenerationTest.cs @@ -7,6 +7,7 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersionCore.Tests.BuildServers @@ -15,17 +16,21 @@ namespace GitVersionCore.Tests.BuildServers public class GitLabCiMessageGenerationTests : TestBase { private IEnvironment environment; + private ILog log; + private IVariableProvider variableProvider; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); + variableProvider = new VariableProvider(log); } [Test] public void GenerateSetVersionMessageReturnsVersionAsIs_AlthoughThisIsNotUsedByJenkins() { - var j = new GitLabCi(environment); + var j = new GitLabCi(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); j.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7"); } @@ -33,7 +38,7 @@ public void GenerateSetVersionMessageReturnsVersionAsIs_AlthoughThisIsNotUsedByJ [Test] public void GenerateMessageTest() { - var j = new GitLabCi(environment); + var j = new GitLabCi(environment, log); var generatedParameterMessages = j.GenerateSetParameterMessage("name", "value"); generatedParameterMessages.Length.ShouldBe(1); generatedParameterMessages[0].ShouldBe("GitVersion_name=value"); @@ -72,9 +77,9 @@ private void AssertVariablesAreWrittenToFile(string f) var config = new TestEffectiveConfiguration(); - var variables = VariableProvider.GetVariablesFor(semanticVersion, config, false); + var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); - var j = new GitLabCi(environment, f); + var j = new GitLabCi(environment, log, f); j.WriteIntegration(writes.Add, variables); diff --git a/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs b/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs index 163c2cee6b..55d0ebb51b 100644 --- a/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/JenkinsMessageGenerationTests.cs @@ -7,6 +7,7 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; using GitVersion.OutputVariables; namespace GitVersionCore.Tests.BuildServers @@ -15,17 +16,21 @@ namespace GitVersionCore.Tests.BuildServers public class JenkinsMessageGenerationTests : TestBase { private IEnvironment environment; + private ILog log; + private IVariableProvider variableProvider; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); + variableProvider = new VariableProvider(log); } [Test] public void GenerateSetVersionMessageReturnsVersionAsIs_AlthoughThisIsNotUsedByJenkins() { - var j = new Jenkins(environment); + var j = new Jenkins(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7"); j.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7"); } @@ -33,7 +38,7 @@ public void GenerateSetVersionMessageReturnsVersionAsIs_AlthoughThisIsNotUsedByJ [Test] public void GenerateMessageTest() { - var j = new Jenkins(environment); + var j = new Jenkins(environment, log); var generatedParameterMessages = j.GenerateSetParameterMessage("name", "value"); generatedParameterMessages.Length.ShouldBe(1); generatedParameterMessages[0].ShouldBe("GitVersion_name=value"); @@ -72,9 +77,9 @@ private void AssertVariablesAreWrittenToFile(string f) var config = new TestEffectiveConfiguration(); - var variables = VariableProvider.GetVariablesFor(semanticVersion, config, false); + var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); - var j = new Jenkins(environment, f); + var j = new Jenkins(environment, log, f); j.WriteIntegration(writes.Add, variables); diff --git a/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs b/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs index 316682dada..79b0539dd4 100644 --- a/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/MyGetTests.cs @@ -1,6 +1,7 @@ using NUnit.Framework; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -8,17 +9,19 @@ namespace GitVersionCore.Tests.BuildServers public class MyGetTests : TestBase { private IEnvironment environment; + private ILog log; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); } [Test] public void Develop_branch() { - var versionBuilder = new MyGet(environment); + var versionBuilder = new MyGet(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); var message = versionBuilder.GenerateSetVersionMessage(vars); Assert.AreEqual(null, message); @@ -27,7 +30,7 @@ public void Develop_branch() [Test] public void EscapeValues() { - var versionBuilder = new MyGet(environment); + var versionBuilder = new MyGet(environment, log); var message = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##myget[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", message[0]); } @@ -35,7 +38,7 @@ public void EscapeValues() [Test] public void BuildNumber() { - var versionBuilder = new MyGet(environment); + var versionBuilder = new MyGet(environment, log); var message = versionBuilder.GenerateSetParameterMessage("LegacySemVerPadded", "0.8.0-unstable568"); Assert.AreEqual("##myget[buildNumber '0.8.0-unstable568']", message[1]); } diff --git a/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs b/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs index b706b57f89..832c6ca275 100644 --- a/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs +++ b/src/GitVersionCore.Tests/BuildServers/TeamCityTests.cs @@ -1,6 +1,7 @@ using NUnit.Framework; using GitVersion.BuildServers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests.BuildServers { @@ -8,17 +9,19 @@ namespace GitVersionCore.Tests.BuildServers public class TeamCityTests : TestBase { private IEnvironment environment; + private ILog log; [SetUp] public void SetUp() { environment = new TestEnvironment(); + log = new NullLog(); } [Test] public void Develop_branch() { - var versionBuilder = new TeamCity(environment); + var versionBuilder = new TeamCity(environment, log); var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Unstable4"); var tcVersion = versionBuilder.GenerateSetVersionMessage(vars); Assert.AreEqual("##teamcity[buildNumber '0.0.0-Unstable4']", tcVersion); @@ -27,7 +30,7 @@ public void Develop_branch() [Test] public void EscapeValues() { - var versionBuilder = new TeamCity(environment); + var versionBuilder = new TeamCity(environment, log); var tcVersion = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##teamcity[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[0]); Assert.AreEqual("##teamcity[setParameter name='system.GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[1]); diff --git a/src/GitVersionCore.Tests/ConfigProviderTests.cs b/src/GitVersionCore.Tests/ConfigProviderTests.cs index 736b0d43da..fbd51f3b02 100644 --- a/src/GitVersionCore.Tests/ConfigProviderTests.cs +++ b/src/GitVersionCore.Tests/ConfigProviderTests.cs @@ -8,10 +8,10 @@ using Shouldly; using YamlDotNet.Serialization; using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.VersioningModes; using GitVersion.Extensions; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -22,13 +22,14 @@ public class ConfigProviderTests : TestBase string repoPath; IFileSystem fileSystem; - ConfigFileLocator configFileLocator; + IConfigFileLocator configFileLocator; [SetUp] public void Setup() { fileSystem = new TestFileSystem(); - configFileLocator = new DefaultConfigFileLocator(); + var log = new NullLog(); + configFileLocator = new DefaultConfigFileLocator(fileSystem, log); repoPath = DefaultRepoPath; ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); @@ -52,7 +53,7 @@ public void CanReadOldDocument() tag: rc "; SetupConfigFileContent(text); - var error = Should.Throw(() => ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator)); + var error = Should.Throw(() => ConfigurationProvider.Provide(repoPath, configFileLocator)); 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 @@ -65,7 +66,7 @@ assemblyVersioningScheme has been replaced by assembly-versioning-scheme [Test] public void OverwritesDefaultsWithProvidedConfig() { - var defaultConfig = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var defaultConfig = ConfigurationProvider.Provide(repoPath, configFileLocator); const string text = @" next-version: 2.0.0 branches: @@ -73,7 +74,7 @@ public void OverwritesDefaultsWithProvidedConfig() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.NextVersion.ShouldBe("2.0.0"); config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment); @@ -86,7 +87,7 @@ public void AllBranchesModeWhenUsingMainline() { const string text = @"mode: Mainline"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); var branches = config.Branches.Select(x => x.Value); branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true); } @@ -100,7 +101,7 @@ public void CanRemoveTag() release: tag: """""; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.NextVersion.ShouldBe("2.0.0"); config.Branches["release"].Tag.ShouldBe(string.Empty); @@ -115,7 +116,7 @@ public void RegexIsRequired() bug: tag: bugfix"; SetupConfigFileContent(text); - var ex = Should.Throw(() => ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator)); + var ex = Should.Throw(() => ConfigurationProvider.Provide(repoPath, configFileLocator)); ex.Message.ShouldBe("Branch configuration 'bug' is missing required configuration 'regex'\n\n" + "See http://gitversion.readthedocs.io/en/latest/configuration/ for more info"); } @@ -130,7 +131,7 @@ public void SourceBranchIsRequired() regex: 'bug[/-]' tag: bugfix"; SetupConfigFileContent(text); - var ex = Should.Throw(() => ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator)); + var ex = Should.Throw(() => ConfigurationProvider.Provide(repoPath, configFileLocator)); 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"); } @@ -146,7 +147,7 @@ public void CanProvideConfigForNewBranch() tag: bugfix source-branches: []"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.Branches["bug"].Regex.ShouldBe("bug[/-]"); config.Branches["bug"].Tag.ShouldBe("bugfix"); @@ -157,7 +158,7 @@ public void NextVersionCanBeInteger() { const string text = "next-version: 2"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.NextVersion.ShouldBe("2.0"); } @@ -167,7 +168,7 @@ public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.NextVersion.ShouldBe("2.118998723"); } @@ -177,7 +178,7 @@ public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.NextVersion.ShouldBe("2.12.654651698"); } @@ -188,7 +189,7 @@ 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, fileSystem, configFileLocator); + var config = ConfigurationProvider.GetEffectiveConfigAsString(repoPath, configFileLocator); config.ShouldMatchApproved(); } @@ -203,7 +204,7 @@ public void CanUpdateAssemblyInformationalVersioningScheme() SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}"); @@ -219,7 +220,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables( SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}"); @@ -238,7 +239,7 @@ public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}"); @@ -249,7 +250,7 @@ public void CanReadDefaultDocument() { const string text = ""; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe(null); @@ -276,13 +277,17 @@ public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty); - var s = string.Empty; - Action action = info => { s = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) - { - ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); - } - s.Length.ShouldBe(0); + var stringLogger = string.Empty; + void Action(string info) => stringLogger = info; + + var logAppender = new TestLogAppender(Action); + var log = new Log(logAppender); + + var defaultConfigFileLocator = new DefaultConfigFileLocator(fileSystem, log); + + ConfigurationProvider.Provide(repoPath, defaultConfigFileLocator); + + stringLogger.Length.ShouldBe(0); } string SetupConfigFileContent(string text, string fileName = DefaultConfigFileLocator.DefaultFileName) @@ -309,7 +314,7 @@ public void ShouldUseSpecifiedSourceBranchesForDevelop() source-branches: ['develop'] tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.Branches["develop"].SourceBranches.ShouldBe(new List { "develop" }); } @@ -324,7 +329,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.Branches["develop"].SourceBranches.ShouldBe(new List()); } @@ -340,7 +345,7 @@ public void ShouldUseSpecifiedSourceBranchesForFeature() source-branches: ['develop', 'release'] tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.Branches["feature"].SourceBranches.ShouldBe(new List { "develop", "release" }); } @@ -355,7 +360,7 @@ public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature() mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); - var config = ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); + var config = ConfigurationProvider.Provide(repoPath, configFileLocator); config.Branches["feature"].SourceBranches.ShouldBe( new List { "develop", "master", "release", "feature", "support", "hotfix" }); diff --git a/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs b/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs index 26899529f3..02c85d92c6 100644 --- a/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs +++ b/src/GitVersionCore.Tests/DefaultConfigFileLocatorTests.cs @@ -4,8 +4,8 @@ using Shouldly; using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -18,13 +18,11 @@ public class DefaultConfigFileLocatorTests : TestBase string repoPath; string workingPath; IFileSystem fileSystem; - DefaultConfigFileLocator configFileLocator; [SetUp] public void Setup() { fileSystem = new TestFileSystem(); - configFileLocator = new DefaultConfigFileLocator(); repoPath = DefaultRepoPath; workingPath = DefaultWorkingPath; @@ -37,14 +35,13 @@ public void WarnOnExistingGitVersionConfigYamlFile(string path) { SetupConfigFileContent(string.Empty, DefaultConfigFileLocator.ObsoleteFileName, path); - var logOutput = string.Empty; - Action action = info => { logOutput = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) + var output = WithDefaultConfigFileLocator(configFileLocator => { - configFileLocator.Verify(workingPath, repoPath, fileSystem); - } + configFileLocator.Verify(workingPath, repoPath); + }); + var configFileDeprecatedWarning = $"{DefaultConfigFileLocator.ObsoleteFileName}' is deprecated, use '{DefaultConfigFileLocator.DefaultFileName}' instead"; - logOutput.Contains(configFileDeprecatedWarning).ShouldBe(true); + output.Contains(configFileDeprecatedWarning).ShouldBe(true); } [TestCase(DefaultRepoPath)] @@ -54,15 +51,13 @@ public void WarnOnAmbiguousConfigFilesAtTheSameProjectRootDirectory(string path) SetupConfigFileContent(string.Empty, DefaultConfigFileLocator.ObsoleteFileName, path); SetupConfigFileContent(string.Empty, DefaultConfigFileLocator.DefaultFileName, path); - var logOutput = string.Empty; - Action action = info => { logOutput = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) + var output = WithDefaultConfigFileLocator(configFileLocator => { - configFileLocator.Verify(workingPath, repoPath, fileSystem); - } + configFileLocator.Verify(workingPath, repoPath); + }); var configFileDeprecatedWarning = $"Ambiguous config files at '{path}'"; - logOutput.Contains(configFileDeprecatedWarning).ShouldBe(true); + output.Contains(configFileDeprecatedWarning).ShouldBe(true); } [TestCase(DefaultConfigFileLocator.DefaultFileName, DefaultConfigFileLocator.DefaultFileName)] @@ -74,7 +69,13 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation(string repoConfigFile, var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, repoConfigFile, repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, workingConfigFile, workingPath); - WarningException exception = Should.Throw(() => { configFileLocator.Verify(workingPath, repoPath, fileSystem); }); + WarningException exception = Should.Throw(() => + { + WithDefaultConfigFileLocator(configFileLocator => + { + configFileLocator.Verify(workingPath, repoPath); + }); + }); var expecedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expecedMessage); @@ -85,13 +86,12 @@ public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty); - var s = string.Empty; - Action action = info => { s = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) + var output = WithDefaultConfigFileLocator(configFileLocator => { - ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); - } - s.Length.ShouldBe(0); + ConfigurationProvider.Provide(repoPath, configFileLocator); + }); + + output.Length.ShouldBe(0); } string SetupConfigFileContent(string text, string fileName = DefaultConfigFileLocator.DefaultFileName) @@ -125,5 +125,19 @@ public void WarnOnObsoleteIsDevelopBranchConfigurationSetting() const string expectedMessage = @"'is-develop' is deprecated, use 'tracks-release-branches' instead."; exception.Message.ShouldContain(expectedMessage); } + + private string WithDefaultConfigFileLocator(Action action) + { + var stringLogger = string.Empty; + void Action(string info) => stringLogger = info; + + var logAppender = new TestLogAppender(Action); + var log = new Log(logAppender); + + var configFileLocator = new DefaultConfigFileLocator(fileSystem, log); + action(configFileLocator); + + return stringLogger; + } } } diff --git a/src/GitVersionCore.Tests/DynamicRepositoryTests.cs b/src/GitVersionCore.Tests/DynamicRepositoryTests.cs index 9473e5def5..16ef36da41 100644 --- a/src/GitVersionCore.Tests/DynamicRepositoryTests.cs +++ b/src/GitVersionCore.Tests/DynamicRepositoryTests.cs @@ -1,8 +1,7 @@ -using System.Diagnostics; using System.IO; using GitVersion; using NUnit.Framework; -using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -11,6 +10,19 @@ public class DynamicRepositoryTests : TestBase { string workDirectory; + private void ClearReadOnly(DirectoryInfo parentDirectory) + { + if (parentDirectory == null) return; + parentDirectory.Attributes = FileAttributes.Normal; + foreach (var fi in parentDirectory.GetFiles()) + { + fi.Attributes = FileAttributes.Normal; + } + foreach (var di in parentDirectory.GetDirectories()) + { + ClearReadOnly(di); + } + } [OneTimeSetUp] public void CreateTemporaryRepository() @@ -21,6 +33,9 @@ public void CreateTemporaryRepository() // Clean directory upfront, some build agents are having troubles if (Directory.Exists(workDirectory)) { + var di = new DirectoryInfo(workDirectory); + ClearReadOnly(di); + Directory.Delete(workDirectory, true); } @@ -35,15 +50,12 @@ public void Cleanup() } // Note: use same name twice to see if changing commits works on same (cached) repository - [Ignore("These tests are slow and fail on the second run in Test Explorer and need to be re-written")] [NonParallelizable] [TestCase("GV_master", "https://github.com/GitTools/GitVersion", "master", "4783d325521463cd6cf1b61074352da84451f25d", "4.0.0+1086")] [TestCase("GV_master", "https://github.com/GitTools/GitVersion", "master", "3bdcd899530b4e9b37d13639f317da04a749e728", "4.0.0+1092")] [TestCase("Ctl_develop", "https://github.com/Catel/Catel", "develop", "0e2b6c125a730d2fa5e24394ef64abe62c98e9e9", "5.12.0-alpha.188")] [TestCase("Ctl_develop", "https://github.com/Catel/Catel", "develop", "71e71359f37581784e18c94e7a45eee72cbeeb30", "5.12.0-alpha.192")] [TestCase("Ctl_master", "https://github.com/Catel/Catel", "master", "f5de8964c35180a5f8607f5954007d5828aa849f", "5.10.0")] - [TestCase("CtlA_develop", "https://github.com/Catel/Catel.Analyzers", "develop", "be0aa94642d6ff1df6209e2180a7fe0de9aab384", "0.1.0-alpha.21")] - [TestCase("CtlA_develop", "https://github.com/Catel/Catel.Analyzers", "develop", "0e2b6c125a730d2fa5e24394ef64abe62c98e9e9", "0.1.0-alpha.23")] public void FindsVersionInDynamicRepo(string name, string url, string targetBranch, string commitId, string expectedFullSemVer) { var root = Path.Combine(workDirectory, name); @@ -53,13 +65,7 @@ public void FindsVersionInDynamicRepo(string name, string url, string targetBran Directory.CreateDirectory(dynamicDirectory); Directory.CreateDirectory(workingDirectory); - Logger.AddLoggersTemporarily( - x => Debug.WriteLine($"[DEBUG] {x}"), - x => Debug.WriteLine($"[INFO] {x}"), - x => Debug.WriteLine($"[WARNING] {x}"), - x => Debug.WriteLine($"[ERROR] {x}")); - - var executeCore = new ExecuteCore(new TestFileSystem(), new TestEnvironment()); + var executeCore = new ExecuteCore(new TestFileSystem(), new TestEnvironment(), new NullLog()); var versionVariables = executeCore.ExecuteGitVersion(url, dynamicDirectory, null, targetBranch, false, workingDirectory, commitId); diff --git a/src/GitVersionCore.Tests/ExecuteCoreTests.cs b/src/GitVersionCore.Tests/ExecuteCoreTests.cs index 26f040e607..8881918626 100644 --- a/src/GitVersionCore.Tests/ExecuteCoreTests.cs +++ b/src/GitVersionCore.Tests/ExecuteCoreTests.cs @@ -7,12 +7,12 @@ using Shouldly; using GitVersion.BuildServers; using GitVersion.Configuration; -using GitVersion.Helpers; 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 @@ -21,30 +21,33 @@ namespace GitVersionCore.Tests [Parallelizable(ParallelScope.None)] public class ExecuteCoreTests : TestBase { - IFileSystem fileSystem; + 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); + 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(targetUrl, null, new Authentication(), false, fixture.RepositoryPath); - var configFileLocator = new DefaultConfigFileLocator(); + 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, gitPreparer, null, configFileLocator); + var cacheKey1 = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, null, configFileLocator); gitPreparer.Initialise(true, targetBranch); - var cacheKey2 = GitVersionCacheKeyFactory.Create(fileSystem, gitPreparer, null, configFileLocator); + var cacheKey2 = GitVersionCacheKeyFactory.Create(fileSystem, log, gitPreparer, null, configFileLocator); cacheKey2.Value.ShouldBe(cacheKey1.Value); }); @@ -55,7 +58,7 @@ public void CacheKeySameAfterReNormalizing() [Description("LibGit2Sharp fails here when running under Mono")] public void CacheKeyForWorktree() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -67,9 +70,9 @@ public void CacheKeyForWorktree() repo.Worktrees.Add("worktree", worktreePath, false); var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(targetUrl, null, new Authentication(), false, worktreePath); - var configFileLocator = new DefaultConfigFileLocator(); - var cacheKey = GitVersionCacheKeyFactory.Create(fileSystem, gitPreparer, null, configFileLocator); + 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 @@ -115,16 +118,24 @@ public void CacheFileExistsOnDisk() CommitDate: 2015-11-10 "; - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + 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); - var logs = RepositoryScope(versionAndBranchFinder, (fixture, vv) => + 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"); }); - logs.Info.ShouldContain("Deserializing version variables from cache file", () => logs.Info); + var logsMessages = stringBuilder.ToString(); + + logsMessages.ShouldContain("Deserializing version variables from cache file", () => logsMessages); } @@ -162,13 +173,13 @@ public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDyn CommitDate: 2015-11-10 "; - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { fileSystem.WriteAllText(vv.FileName, versionCacheFileContent); - var gitPreparer = new GitPreparer(null, null, null, false, fixture.RepositoryPath); + var gitPreparer = new GitPreparer(log, null, null, null, false, fixture.RepositoryPath); var cacheDirectory = GitVersionCache.GetCacheDirectory(gitPreparer); var cacheDirectoryTimestamp = fileSystem.GetLastDirectoryWrite(cacheDirectory); @@ -187,8 +198,17 @@ public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDyn [Test] public void CacheFileIsMissing() { - var logsMessages = RepositoryScope(); - logsMessages.Info.ShouldContain("yml not found", () => logsMessages.Info); + 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); } @@ -228,7 +248,7 @@ public void ConfigChangeInvalidatesCache() CommitDate: 2015-11-10 "; - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -280,7 +300,7 @@ public void NoCacheBypassesCache() CommitDate: 2015-11-10 "; - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -297,7 +317,7 @@ public void NoCacheBypassesCache() [Test] public void WorkingDirectoryWithoutGit() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -311,7 +331,7 @@ public void WorkingDirectoryWithoutGit() [Description("LibGit2Sharp fails when running under Mono")] public void GetProjectRootDirectory_WorkingDirectoryWithWorktree() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -323,7 +343,7 @@ public void GetProjectRootDirectory_WorkingDirectoryWithWorktree() repo.Worktrees.Add("worktree", worktreePath, false); var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(targetUrl, null, new Authentication(), false, worktreePath); + var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, worktreePath); gitPreparer.GetProjectRootDirectory().TrimEnd('/', '\\').ShouldBe(worktreePath); } finally @@ -336,12 +356,12 @@ public void GetProjectRootDirectory_WorkingDirectoryWithWorktree() [Test] public void GetProjectRootDirectory_NoWorktree() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(targetUrl, null, new Authentication(), false, fixture.RepositoryPath); + var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, fixture.RepositoryPath); var expectedPath = fixture.RepositoryPath.TrimEnd('/', '\\'); gitPreparer.GetProjectRootDirectory().TrimEnd('/', '\\').ShouldBe(expectedPath); }); @@ -350,7 +370,7 @@ public void GetProjectRootDirectory_NoWorktree() [Test] public void DynamicRepositoriesShouldNotErrorWithFailedToFindGitDirectory() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -361,12 +381,12 @@ public void DynamicRepositoriesShouldNotErrorWithFailedToFindGitDirectory() [Test] public void GetDotGitDirectory_NoWorktree() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(targetUrl, null, new Authentication(), false, fixture.RepositoryPath); + var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, fixture.RepositoryPath); var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); gitPreparer.GetDotGitDirectory().ShouldBe(expectedPath); }); @@ -377,7 +397,7 @@ public void GetDotGitDirectory_NoWorktree() [Description("LibGit2Sharp fails when running under Mono")] public void GetDotGitDirectory_Worktree() { - var versionAndBranchFinder = new ExecuteCore(fileSystem, environment); + var versionAndBranchFinder = new ExecuteCore(fileSystem, environment, log); RepositoryScope(versionAndBranchFinder, (fixture, vv) => { @@ -390,7 +410,7 @@ public void GetDotGitDirectory_Worktree() repo.Worktrees.Add("worktree", worktreePath, false); var targetUrl = "https://github.com/GitTools/GitVersion.git"; - var gitPreparer = new GitPreparer(targetUrl, null, new Authentication(), false, worktreePath); + var gitPreparer = new GitPreparer(log, targetUrl, null, new Authentication(), false, worktreePath); var expectedPath = Path.Combine(fixture.RepositoryPath, ".git"); gitPreparer.GetDotGitDirectory().ShouldBe(expectedPath); } @@ -401,31 +421,13 @@ public void GetDotGitDirectory_Worktree() }); } - private LogMessages RepositoryScope(ExecuteCore executeCore = null, Action fixtureAction = null) + 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(VsoAgent.EnvironmentVariableName, null); - var debugBuilder = new StringBuilder(); - - void DebugLogger(string s) => debugBuilder.AppendLine(s); + environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, null); - var infoBuilder = new StringBuilder(); - - void InfoLogger(string s) => infoBuilder.AppendLine(s); - - var warnBuilder = new StringBuilder(); - - void WarnLogger(string s) => warnBuilder.AppendLine(s); - - var errorBuilder = new StringBuilder(); - - void ErrorLogger(string s) => errorBuilder.AppendLine(s); - - executeCore = executeCore ?? new ExecuteCore(fileSystem, environment); - - using (Logger.AddLoggersTemporarily(DebugLogger, InfoLogger, WarnLogger, ErrorLogger)) using (var fixture = new EmptyRepositoryFixture()) { fixture.Repository.MakeACommit(); @@ -436,14 +438,6 @@ private LogMessages RepositoryScope(ExecuteCore executeCore = null, Action @@ -76,7 +80,7 @@ static SemanticVersion ExecuteGitVersion(GitVersionContext context) /// public static void InitialiseRepo(this RemoteRepositoryFixture fixture) { - new GitPreparer(null, null, new Authentication(), false, fixture.LocalRepositoryFixture.RepositoryPath).Initialise(true, null); + new GitPreparer(new NullLog(), null, null, new Authentication(), false, fixture.LocalRepositoryFixture.RepositoryPath).Initialise(true, null); } } } diff --git a/src/GitVersionCore.Tests/GitVersionContextBuilder.cs b/src/GitVersionCore.Tests/GitVersionContextBuilder.cs index 4485a7e59b..bb5f2cb429 100644 --- a/src/GitVersionCore.Tests/GitVersionContextBuilder.cs +++ b/src/GitVersionCore.Tests/GitVersionContextBuilder.cs @@ -1,6 +1,7 @@ -using GitTools.Testing; +using GitTools.Testing; using GitVersion; using GitVersion.Configuration; +using GitVersion.Logging; using GitVersionCore.Tests.Mocks; using LibGit2Sharp; @@ -64,7 +65,7 @@ public GitVersionContext Build() var configuration = config ?? new Config(); ConfigurationProvider.ApplyDefaultsTo(configuration); var repo = repository ?? CreateRepository(); - return new GitVersionContext(repo, repo.Head, configuration); + return new GitVersionContext(repo, new NullLog(), repo.Head, configuration); } IRepository CreateRepository() @@ -83,4 +84,4 @@ IRepository CreateRepository() return mockRepository; } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/GitVersionContextTests.cs b/src/GitVersionCore.Tests/GitVersionContextTests.cs index 05a85660fe..608044e8cf 100644 --- a/src/GitVersionCore.Tests/GitVersionContextTests.cs +++ b/src/GitVersionCore.Tests/GitVersionContextTests.cs @@ -1,10 +1,11 @@ -using GitTools.Testing; +using GitTools.Testing; using GitVersion; using LibGit2Sharp; using NUnit.Framework; using Shouldly; using System.Collections.Generic; using GitVersion.Configuration; +using GitVersion.Logging; using GitVersion.VersioningModes; using GitVersionCore.Tests.Mocks; @@ -31,7 +32,7 @@ public void CanInheritVersioningMode(VersioningMode mode) } }; - var context = new GitVersionContext(mockRepository, mockBranch, config); + var context = new GitVersionContext(mockRepository, new NullLog(), mockBranch, config); context.Configuration.VersioningMode.ShouldBe(mode); } @@ -57,7 +58,7 @@ public void CanInheritIncrement(IncrementStrategy increment, IncrementStrategy? fixture.BranchTo(dummyBranchName); fixture.MakeACommit(); - var context = new GitVersionContext(fixture.Repository, fixture.Repository.Branches[dummyBranchName], config); + var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Branches[dummyBranchName], config); context.Configuration.Increment.ShouldBe(alternateExpected ?? increment); } @@ -90,7 +91,7 @@ public void UsesBranchSpecificConfigOverTopLevelDefaults() develop } }; - var context = new GitVersionContext(mockRepository, develop, config); + var context = new GitVersionContext(mockRepository, new NullLog(), develop, config); context.Configuration.Tag.ShouldBe("alpha"); } @@ -119,10 +120,10 @@ public void UsesFirstBranchConfigWhenMultipleMatch() } }; - var latestContext = new GitVersionContext(mockRepository, releaseLatestBranch, config); + var latestContext = new GitVersionContext(mockRepository, new NullLog(), releaseLatestBranch, config); latestContext.Configuration.Increment.ShouldBe(IncrementStrategy.None); - var versionContext = new GitVersionContext(mockRepository, releaseVersionBranch, config); + var versionContext = new GitVersionContext(mockRepository, new NullLog(), releaseVersionBranch, config); versionContext.Configuration.Increment.ShouldBe(IncrementStrategy.Patch); } @@ -147,9 +148,9 @@ public void CanFindParentBranchForInheritingIncrementStrategy() Commands.Checkout(repo.Repository, featureBranch); repo.Repository.MakeACommit(); - var context = new GitVersionContext(repo.Repository, repo.Repository.Head, config); + var context = new GitVersionContext(repo.Repository, new NullLog(), repo.Repository.Head, config); context.Configuration.Increment.ShouldBe(IncrementStrategy.Major); } } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs b/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs index 98641bdbde..16122b630f 100644 --- a/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs +++ b/src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs @@ -5,6 +5,7 @@ using Shouldly; using GitVersion.OutputVariables; using GitVersion.Extensions.GitVersionInformationResources; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -40,7 +41,8 @@ public void ShouldCreateFile(string fileExtension) "feature1", "commitSha", "commitShortSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; - var variables = VariableProvider.GetVariablesFor(semanticVersion, new TestEffectiveConfiguration(), false); + var variableProvider = new VariableProvider(new NullLog()); + var variables = variableProvider.GetVariablesFor(semanticVersion, new TestEffectiveConfiguration(), false); var generator = new GitVersionInformationGenerator(fileName, directory, variables, fileSystem); generator.Generate(); diff --git a/src/GitVersionCore.Tests/Init/InitScenarios.cs b/src/GitVersionCore.Tests/Init/InitScenarios.cs index e4fa31f784..572b499d61 100644 --- a/src/GitVersionCore.Tests/Init/InitScenarios.cs +++ b/src/GitVersionCore.Tests/Init/InitScenarios.cs @@ -1,6 +1,7 @@ using System.IO; using System.Runtime.InteropServices; using GitVersion.Configuration; +using GitVersion.Logging; using NUnit.Framework; using Shouldly; @@ -20,13 +21,14 @@ public void Setup() [Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void CanSetNextVersion() { - var testFileSystem = new TestFileSystem(); + var log = new NullLog(); + var fileSystem = new TestFileSystem(); var testConsole = new TestConsole("3", "2.0.0", "0"); - var configFileLocator = new DefaultConfigFileLocator(); + var configFileLocator = new DefaultConfigFileLocator(fileSystem, log); var workingDirectory = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "c:\\proj" : "/proj"; - ConfigurationProvider.Init(workingDirectory, testFileSystem, testConsole, configFileLocator); + ConfigurationProvider.Init(workingDirectory, fileSystem, testConsole, log, configFileLocator); - testFileSystem.ReadAllText(Path.Combine(workingDirectory, "GitVersion.yml")).ShouldMatchApproved(); + 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 9f1fb8cfbe..79b62a9994 100644 --- a/src/GitVersionCore.Tests/Init/TestConsole.cs +++ b/src/GitVersionCore.Tests/Init/TestConsole.cs @@ -1,32 +1,34 @@ -using System; +using System; using System.Collections.Generic; using GitVersion.Configuration; -using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests.Init { public class TestConsole : IConsole { readonly Queue responses; + private ILog log; public TestConsole(params string[] responses) { + log = new NullLog(); this.responses = new Queue(responses); } public void WriteLine(string msg) { - Logger.WriteInfo(msg + Environment.NewLine); + log.Info(msg + Environment.NewLine); } public void WriteLine() { - Logger.WriteInfo(Environment.NewLine); + log.Info(Environment.NewLine); } public void Write(string msg) { - Logger.WriteInfo(msg); + log.Info(msg); } public string ReadLine() @@ -44,4 +46,4 @@ class NoOpDisposable : IDisposable public void Dispose() { } } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs index 3f91a5efde..daec36f92b 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/ReleaseBranchScenarios.cs @@ -441,7 +441,7 @@ public void CommitBeetweenMergeReleaseToDevelop_ShouldNotResetCount() // Make some commits on release var commit1 = fixture.Repository.MakeACommit(); - var commit2 = fixture.Repository.MakeACommit(); + fixture.Repository.MakeACommit(); fixture.AssertFullSemver(config, "2.0.0-beta.2"); // Merge release to develop - emulate commit beetween other person release commit push and this commit merge to develop diff --git a/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs b/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs index 20e181a39a..2252a47b85 100644 --- a/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs +++ b/src/GitVersionCore.Tests/IntegrationTests/RemoteRepositoryScenarios.cs @@ -6,6 +6,7 @@ using Shouldly; using GitVersion.Exceptions; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests.IntegrationTests { @@ -43,7 +44,7 @@ public void GivenARemoteGitRepositoryWithCommitsAndBranches_ThenClonedLocalShoul return repo; })) { - GitRepositoryHelper.NormalizeGitDirectory(fixture.LocalRepositoryFixture.RepositoryPath, new AuthenticationInfo(), noFetch: false, currentBranch: string.Empty, true); + GitRepositoryHelper.NormalizeGitDirectory(new NullLog(), fixture.LocalRepositoryFixture.RepositoryPath, new AuthenticationInfo(), noFetch: false, currentBranch: string.Empty, isDynamicRepository: true); fixture.AssertFullSemver("1.0.0-beta.1+5"); fixture.AssertFullSemver("1.0.0-beta.1+5", fixture.LocalRepositoryFixture.Repository); diff --git a/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs b/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs index 6dc4f1362c..ff8d8d1d72 100644 --- a/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs +++ b/src/GitVersionCore.Tests/JsonVersionBuilderTests.cs @@ -1,5 +1,6 @@ using System; using GitVersion; +using GitVersion.Logging; using NUnit.Framework; using Shouldly; using GitVersion.OutputFormatters; @@ -32,7 +33,8 @@ public void Json() var config = new TestEffectiveConfiguration(); - var variables = VariableProvider.GetVariablesFor(semanticVersion, config, false); + var variableProvider = new VariableProvider(new NullLog()); + var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); var json = JsonOutputFormatter.ToJson(variables); json.ShouldMatchApproved(c => c.SubFolder("Approved")); } diff --git a/src/GitVersionCore.Tests/LogMessages.cs b/src/GitVersionCore.Tests/LogMessages.cs index 7adc3a4689..3c36b41f40 100644 --- a/src/GitVersionCore.Tests/LogMessages.cs +++ b/src/GitVersionCore.Tests/LogMessages.cs @@ -1,10 +1,7 @@ -namespace GitVersionCore.Tests +namespace GitVersionCore.Tests { internal class LogMessages { - public string Debug { get; internal set; } - public object Error { get; internal set; } public string Info { get; internal set; } - public string Warn { get; internal set; } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/LoggerTest.cs b/src/GitVersionCore.Tests/LoggerTest.cs index 7aaf868d7c..a94bf2d07f 100644 --- a/src/GitVersionCore.Tests/LoggerTest.cs +++ b/src/GitVersionCore.Tests/LoggerTest.cs @@ -1,7 +1,6 @@ -using NUnit.Framework; -using System; +using NUnit.Framework; using Shouldly; -using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -16,9 +15,13 @@ public void LoggerObscuresPassword(string protocol) const string username = "username%40domain.com"; const string password = "password"; var s = string.Empty; - Action action = info => { s = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) - Logger.WriteInfo($"{protocol}://{username}:{password}@workspace.visualstudio.com/DefaultCollection/_git/CAS"); + + void Action(string info) => s = info; + + var logAppender = new TestLogAppender(Action); + var log = new Log(logAppender); + + log.Info($"{protocol}://{username}:{password}@workspace.visualstudio.com/DefaultCollection/_git/CAS"); s.Contains(password).ShouldBe(false); } @@ -27,10 +30,15 @@ public void LoggerObscuresPassword(string protocol) public void UsernameWithoutPassword() { var s = string.Empty; - Action action = info => { s = info; }; + + void Action(string info) => s = info; + + var logAppender = new TestLogAppender(Action); + var log = new Log(logAppender); + const string repoUrl = "http://username@workspace.visualstudio.com/DefaultCollection/_git/CAS"; - using (Logger.AddLoggersTemporarily(action, action, action, action)) - Logger.WriteInfo(repoUrl); + + log.Info(repoUrl); s.Contains(repoUrl).ShouldBe(true); } diff --git a/src/GitVersionCore.Tests/Mocks/MockBranch.cs b/src/GitVersionCore.Tests/Mocks/MockBranch.cs index f6b7d167d2..93fad23498 100644 --- a/src/GitVersionCore.Tests/Mocks/MockBranch.cs +++ b/src/GitVersionCore.Tests/Mocks/MockBranch.cs @@ -10,12 +10,12 @@ public class MockBranch : Branch, ICollection public MockBranch(string friendlyName) { this.friendlyName = friendlyName; - canonicalName = friendlyName; + CanonicalName = friendlyName; } public MockBranch(string friendlyName, string canonicalName) { this.friendlyName = friendlyName; - this.canonicalName = canonicalName; + this.CanonicalName = canonicalName; } public MockBranch() @@ -24,13 +24,12 @@ public MockBranch() } MockCommitLog commits = new MockCommitLog(); string friendlyName; - string canonicalName; public override string FriendlyName => friendlyName; public override ICommitLog Commits => commits; public override Commit Tip => commits.First(); public override bool IsTracking => true; - public override string CanonicalName => canonicalName; + public override string CanonicalName { get; } public override int GetHashCode() { diff --git a/src/GitVersionCore.Tests/Mocks/MockRepository.cs b/src/GitVersionCore.Tests/Mocks/MockRepository.cs index 965cdb93bd..c564f470f0 100644 --- a/src/GitVersionCore.Tests/Mocks/MockRepository.cs +++ b/src/GitVersionCore.Tests/Mocks/MockRepository.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using LibGit2Sharp; +using Index = LibGit2Sharp.Index; namespace GitVersionCore.Tests.Mocks { public class MockRepository : IRepository @@ -34,21 +35,6 @@ public Branch Checkout(Commit commit, CheckoutOptions options, Signature signatu throw new NotImplementedException(); } - public Branch Checkout(Branch branch, CheckoutOptions options) - { - throw new NotImplementedException(); - } - - public Branch Checkout(string committishOrBranchSpec, CheckoutOptions options) - { - throw new NotImplementedException(); - } - - public Branch Checkout(Commit commit, CheckoutOptions options) - { - throw new NotImplementedException(); - } - public void CheckoutPaths(string committishOrBranchSpec, IEnumerable paths, CheckoutOptions checkoutOptions = null) { throw new NotImplementedException(); @@ -211,7 +197,7 @@ public void RevParse(string revision, out Reference reference, out GitObject obj public Branch Head { get; set; } public LibGit2Sharp.Configuration Config { get; set; } - public LibGit2Sharp.Index Index { get; set; } + public Index Index { get; set; } public ReferenceCollection Refs { get; set; } public IQueryableCommitLog Commits diff --git a/src/GitVersionCore.Tests/ModuleInitializer.cs b/src/GitVersionCore.Tests/ModuleInitializer.cs deleted file mode 100644 index 22f2e84f40..0000000000 --- a/src/GitVersionCore.Tests/ModuleInitializer.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using GitVersion.Helpers; - -namespace GitVersionCore.Tests -{ - /// - /// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded. - /// - public static class ModuleInitializer - { - /// - /// Initializes the module. - /// - public static void Initialize() - { - Logger.SetLoggers( - s => Console.WriteLine(s), - s => Console.WriteLine(s), - s => Console.WriteLine(s), - s => Console.WriteLine(s)); - } - } -} diff --git a/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs b/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs index b5ccd3f1d4..47b5237b2a 100644 --- a/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs +++ b/src/GitVersionCore.Tests/NamedConfigFileLocatorTests.cs @@ -1,11 +1,10 @@ -using System; using System.IO; using NUnit.Framework; using Shouldly; using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -19,12 +18,14 @@ public class NamedConfigFileLocatorTests : TestBase string workingPath; IFileSystem fileSystem; NamedConfigFileLocator configFileLocator; + private ILog log; [SetUp] public void Setup() { fileSystem = new TestFileSystem(); - configFileLocator = new NamedConfigFileLocator("my-config.yaml"); + log = new NullLog(); + configFileLocator = new NamedConfigFileLocator("my-config.yaml", fileSystem, log); repoPath = DefaultRepoPath; workingPath = DefaultWorkingPath; @@ -37,7 +38,7 @@ public void ThrowsExceptionOnAmbiguousConfigFileLocation() var repositoryConfigFilePath = SetupConfigFileContent(string.Empty, path: repoPath); var workingDirectoryConfigFilePath = SetupConfigFileContent(string.Empty, path: workingPath); - var exception = Should.Throw(() => { configFileLocator.Verify(workingPath, repoPath, fileSystem); }); + var exception = Should.Throw(() => { configFileLocator.Verify(workingPath, repoPath); }); var expectedMessage = $"Ambiguous config file selection from '{workingDirectoryConfigFilePath}' and '{repositoryConfigFilePath}'"; exception.Message.ShouldBe(expectedMessage); @@ -48,13 +49,16 @@ public void NoWarnOnCustomYmlFile() { SetupConfigFileContent(string.Empty); - var s = string.Empty; - Action action = info => { s = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) - { - ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); - } - s.Length.ShouldBe(0); + var stringLogger = string.Empty; + void Action(string info) => stringLogger = info; + + var logAppender = new TestLogAppender(Action); + log = new Log(logAppender); + + configFileLocator = new NamedConfigFileLocator("my-config.yaml", fileSystem, log); + + ConfigurationProvider.Provide(repoPath, configFileLocator); + stringLogger.Length.ShouldBe(0); } [Test] @@ -62,13 +66,16 @@ public void NoWarnOnCustomYmlFileOutsideRepoPath() { SetupConfigFileContent(string.Empty, path: @"c:\\Unrelated\\path"); - var s = string.Empty; - Action action = info => { s = info; }; - using (Logger.AddLoggersTemporarily(action, action, action, action)) - { - ConfigurationProvider.Provide(repoPath, fileSystem, configFileLocator); - } - s.Length.ShouldBe(0); + var stringLogger = string.Empty; + void Action(string info) => stringLogger = info; + + var logAppender = new TestLogAppender(Action); + log = new Log(logAppender); + + configFileLocator = new NamedConfigFileLocator("my-config.yaml", fileSystem, log); + + ConfigurationProvider.Provide(repoPath, configFileLocator); + stringLogger.Length.ShouldBe(0); } string SetupConfigFileContent(string text, string fileName = null, string path = null) diff --git a/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs b/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs index 03d57db16b..69523141dc 100644 --- a/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs +++ b/src/GitVersionCore.Tests/OperationWithExponentialBackoffTests.cs @@ -4,6 +4,7 @@ using NUnit.Framework; using Shouldly; using GitVersion.Helpers; +using GitVersion.Logging; using GitVersionCore.Tests.Mocks; namespace GitVersionCore.Tests @@ -14,26 +15,26 @@ public class OperationWithExponentialBackoffTests : TestBase [Test] public void RetryOperationThrowsWhenNegativeMaxRetries() { - Action action = () => new OperationWithExponentialBackoff(new MockThreadSleep(), () => { }, -1); + Action action = () => new OperationWithExponentialBackoff(new MockThreadSleep(), new NullLog(), () => { }, -1); action.ShouldThrow(); } [Test] public void RetryOperationThrowsWhenThreadSleepIsNull() { - Action action = () => new OperationWithExponentialBackoff(null, () => { }); + Action action = () => new OperationWithExponentialBackoff(null, new NullLog(), () => { }); action.ShouldThrow(); } [Test] public async Task OperationIsNotRetriedOnInvalidException() { - Action operation = () => + void Operation() { throw new Exception(); - }; + } - var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), operation); + var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), new NullLog(), Operation); Task action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); } @@ -43,16 +44,16 @@ public async Task OperationIsRetriedOnIOException() { var operationCount = 0; - Action operation = () => + void Operation() { operationCount++; if (operationCount < 2) { throw new IOException(); } - }; + } - var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), operation); + var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), new NullLog(), Operation); await retryOperation.ExecuteAsync(); operationCount.ShouldBe(2); @@ -64,13 +65,13 @@ public async Task OperationIsRetriedAMaximumNumberOfTimesAsync() const int numberOfRetries = 3; var operationCount = 0; - Action operation = () => + void Operation() { operationCount++; throw new IOException(); - }; + } - var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), operation, numberOfRetries); + var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(), new NullLog(), Operation, numberOfRetries); Task action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); @@ -84,9 +85,9 @@ public async Task OperationDelayDoublesBetweenRetries() var expectedSleepMSec = 500; var sleepCount = 0; - Action operation = () => throw new IOException(); + void Operation() => throw new IOException(); - Func validator = u => + Task Validator(int u) { return Task.Run(() => { @@ -94,10 +95,9 @@ public async Task OperationDelayDoublesBetweenRetries() u.ShouldBe(expectedSleepMSec); expectedSleepMSec *= 2; }); + } - }; - - var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(validator), operation, numberOfRetries); + var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(Validator), new NullLog(), Operation, numberOfRetries); Task action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); @@ -112,21 +112,17 @@ public async Task TotalSleepTimeForSixRetriesIsAboutThirtySecondsAsync() const int numberOfRetries = 6; int totalSleep = 0; - Action operation = () => + void Operation() { throw new IOException(); - }; + } - Func validator = u => + Task Validator(int u) { - return Task.Run(() => - { - totalSleep += u; - }); - - }; + return Task.Run(() => { totalSleep += u; }); + } - var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(validator), operation, numberOfRetries); + var retryOperation = new OperationWithExponentialBackoff(new MockThreadSleep(Validator), new NullLog(), Operation, numberOfRetries); Task action = retryOperation.ExecuteAsync(); await action.ShouldThrowAsync(); diff --git a/src/GitVersionCore.Tests/TestBase.cs b/src/GitVersionCore.Tests/TestBase.cs index 53381cf9cc..0ba0a3817b 100644 --- a/src/GitVersionCore.Tests/TestBase.cs +++ b/src/GitVersionCore.Tests/TestBase.cs @@ -1,11 +1,6 @@ -namespace GitVersionCore.Tests +namespace GitVersionCore.Tests { public class TestBase { - static TestBase() - { - ModuleInitializer.Initialize(); - } - } } diff --git a/src/GitVersionCore.Tests/TestLogAppender.cs b/src/GitVersionCore.Tests/TestLogAppender.cs new file mode 100644 index 0000000000..b6da6dab31 --- /dev/null +++ b/src/GitVersionCore.Tests/TestLogAppender.cs @@ -0,0 +1,19 @@ +using System; +using GitVersion.Logging; + +namespace GitVersionCore.Tests +{ + public class TestLogAppender : ILogAppender + { + private readonly Action logAction; + + public TestLogAppender(Action logAction) + { + this.logAction = logAction; + } + public void WriteTo(LogLevel level, string message) + { + logAction(message); + } + } +} diff --git a/src/GitVersionCore.Tests/TestStream.cs b/src/GitVersionCore.Tests/TestStream.cs index 428a66c68a..f8d6d0a054 100644 --- a/src/GitVersionCore.Tests/TestStream.cs +++ b/src/GitVersionCore.Tests/TestStream.cs @@ -1,7 +1,4 @@ -using System; using System.IO; -using System.Threading; -using System.Threading.Tasks; namespace GitVersionCore.Tests { @@ -50,21 +47,6 @@ public override void Write(byte[] buffer, int offset, int count) underlying.Write(buffer, offset, count); } - public override void WriteByte(byte value) - { - base.WriteByte(value); - } - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - return base.BeginWrite(buffer, offset, count, callback, state); - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return base.WriteAsync(buffer, offset, count, cancellationToken); - } - public override bool CanRead => underlying.CanRead; public override bool CanSeek => underlying.CanSeek; public override bool CanWrite => underlying.CanWrite; @@ -76,4 +58,4 @@ public override long Position set => underlying.Position = value; } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/VariableProviderTests.cs b/src/GitVersionCore.Tests/VariableProviderTests.cs index 6701ada38c..7451c15c42 100644 --- a/src/GitVersionCore.Tests/VariableProviderTests.cs +++ b/src/GitVersionCore.Tests/VariableProviderTests.cs @@ -1,5 +1,6 @@ -using System; +using System; using GitVersion; +using GitVersion.Logging; using NUnit.Framework; using Shouldly; using GitVersion.OutputFormatters; @@ -11,11 +12,14 @@ namespace GitVersionCore.Tests [TestFixture] public class VariableProviderTests : TestBase { + private IVariableProvider variableProvider; [SetUp] public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute(); + var log = new NullLog(); + variableProvider = new VariableProvider(log); } [Test] @@ -40,7 +44,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForPreRelease() var config = new TestEffectiveConfiguration(); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -67,7 +71,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForPreReleaseWithPadding() var config = new TestEffectiveConfiguration(buildMetaDataPadding: 2, legacySemVerPadding: 5); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -93,7 +97,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForPreRelease() var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -118,7 +122,7 @@ public void ProvidesVariablesInContinuousDeliveryModeForStable() var config = new TestEffectiveConfiguration(); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -143,7 +147,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForStable() var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -171,7 +175,7 @@ public void ProvidesVariablesInContinuousDeploymentModeForStableWhenCurrentCommi var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); - var vars = VariableProvider.GetVariablesFor(semVer, config, true); + var vars = variableProvider.GetVariablesFor(semVer, config, true); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); } @@ -194,7 +198,7 @@ public void ProvidesVariablesInContinuousDeploymentModeWithTagNamePattern() semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment, tagNumberPattern: @"[/-](?\d+)[-/]"); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); vars.FullSemVer.ShouldBe("1.2.3-PullRequest0002.5"); } @@ -216,7 +220,7 @@ public void ProvidesVariablesInContinuousDeploymentModeWithTagSetToUseBranchName semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment, tag: "useBranchName"); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); + var vars = variableProvider.GetVariablesFor(semVer, config, false); vars.FullSemVer.ShouldBe("1.2.3-feature.5"); } diff --git a/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs b/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs index 62d810f53e..ad9cb9fd25 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/BaseVersionCalculatorTests.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using GitTools.Testing; using GitVersion; @@ -11,18 +11,25 @@ using NUnit.Framework; using Shouldly; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests.VersionCalculation { [TestFixture] public class BaseVersionCalculatorTests : TestBase { + private ILog log; + + public BaseVersionCalculatorTests() + { + log = new NullLog(); + } [Test] public void ChoosesHighestVersionReturnedFromStrategies() { var context = new GitVersionContextBuilder().Build(); var dateTimeOffset = DateTimeOffset.Now; - var sut = new BaseVersionCalculator(new V1Strategy(DateTimeOffset.Now), new V2Strategy(dateTimeOffset)); + var sut = new BaseVersionCalculator(log, new V1Strategy(DateTimeOffset.Now), new V2Strategy(dateTimeOffset)); var baseVersion = sut.GetBaseVersion(context); @@ -36,7 +43,7 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhen() { var context = new GitVersionContextBuilder().Build(); var when = DateTimeOffset.Now; - var sut = new BaseVersionCalculator(new V1Strategy(when), new V2Strategy(null)); + var sut = new BaseVersionCalculator(log, new V1Strategy(when), new V2Strategy(null)); var baseVersion = sut.GetBaseVersion(context); @@ -50,7 +57,7 @@ public void UsesWhenFromNextBestMatchIfHighestDoesntHaveWhenReversedOrder() { var context = new GitVersionContextBuilder().Build(); var when = DateTimeOffset.Now; - var sut = new BaseVersionCalculator(new V1Strategy(null), new V2Strategy(when)); + var sut = new BaseVersionCalculator(log, new V1Strategy(null), new V2Strategy(when)); var baseVersion = sut.GetBaseVersion(context); @@ -95,7 +102,7 @@ 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(new TestVersionStrategy(version)); + var sut = new BaseVersionCalculator(log, new TestVersionStrategy(version)); var baseVersion = sut.GetBaseVersion(context); @@ -111,7 +118,7 @@ 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(new TestVersionStrategy(higherVersion, lowerVersion)); + var sut = new BaseVersionCalculator(log, new TestVersionStrategy(higherVersion, lowerVersion)); var baseVersion = sut.GetBaseVersion(context); @@ -121,7 +128,7 @@ public void ShouldFilterVersion() baseVersion.SemanticVersion.ShouldBe(lowerVersion.SemanticVersion); } - internal class TestIgnoreConfig : IgnoreConfig + private class TestIgnoreConfig : IgnoreConfig { private readonly IVersionFilter filter; @@ -136,7 +143,7 @@ public override IEnumerable ToFilters() } } - internal class ExcludeSourcesContainingExclude : IVersionFilter + private class ExcludeSourcesContainingExclude : IVersionFilter { public bool Exclude(BaseVersion version, out string reason) { @@ -166,4 +173,4 @@ public override IEnumerable GetVersions(GitVersionContext context) } } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs b/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs index 7d4e6aadc0..c10dc8ecd6 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/NextVersionCalculatorTests.cs @@ -10,17 +10,24 @@ using NUnit.Framework; using Shouldly; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests.VersionCalculation { public class NextVersionCalculatorTests : TestBase { + private ILog log; + + public NextVersionCalculatorTests() + { + log = new NullLog(); + } [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(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var sut = new NextVersionCalculator(log, baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); var config = new Config(); var context = new GitVersionContextBuilder().WithConfig(config).Build(); @@ -34,7 +41,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(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var sut = new NextVersionCalculator(log, baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); var config = new Config(); var context = new GitVersionContextBuilder().WithConfig(config).Build(); @@ -48,7 +55,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(baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); + var sut = new NextVersionCalculator(log, baseCalculator, new TestMetaDataCalculator(semanticVersionBuildMetaData)); var context = new GitVersionContextBuilder() .WithDevelopBranch() .Build(); diff --git a/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs b/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs index f1ef03c42d..8bb58091ac 100644 --- a/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs +++ b/src/GitVersionCore.Tests/VersionCalculation/Strategies/VersionInBranchNameBaseVersionStrategyTests.cs @@ -3,6 +3,7 @@ using GitTools.Testing; using GitVersion; using GitVersion.Configuration; +using GitVersion.Logging; using GitVersion.VersionCalculation.BaseVersionCalculators; using LibGit2Sharp; using NUnit.Framework; @@ -23,7 +24,7 @@ public void CanTakeVersionFromNameOfReleaseBranch(string branchName, string expe var branch = fixture.Repository.CreateBranch(branchName); var sut = new VersionInBranchNameBaseVersionStrategy(); - var gitVersionContext = new GitVersionContext(fixture.Repository, branch, new Config().ApplyDefaults()); + var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, new Config().ApplyDefaults()); var baseVersion = sut.GetVersions(gitVersionContext).Single(); baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion); @@ -42,7 +43,7 @@ public void ShouldNotTakeVersionFromNameOfNonReleaseBranch(string branchName) var branch = fixture.Repository.CreateBranch(branchName); var sut = new VersionInBranchNameBaseVersionStrategy(); - var gitVersionContext = new GitVersionContext(fixture.Repository, branch, new Config().ApplyDefaults()); + var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, new Config().ApplyDefaults()); var baseVersions = sut.GetVersions(gitVersionContext); baseVersions.ShouldBeEmpty(); @@ -61,7 +62,7 @@ public void CanTakeVersionFromNameOfConfiguredReleaseBranch(string branchName, s var branchConfigs = new Dictionary { { "support", new BranchConfig { IsReleaseBranch = true } } }; var config = new Config { Branches = branchConfigs }.ApplyDefaults(); - var gitVersionContext = new GitVersionContext(fixture.Repository, branch, config); + var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, config); var baseVersion = sut.GetVersions(gitVersionContext).Single(); baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion); @@ -82,7 +83,7 @@ public void CanTakeVersionFromNameOfRemoteReleaseBranch(string branchName, strin fixture.LocalRepositoryFixture.Checkout($"origin/{branchName}"); var sut = new VersionInBranchNameBaseVersionStrategy(); - var gitVersionContext = new GitVersionContext(fixture.Repository, branch, new Config().ApplyDefaults()); + var gitVersionContext = new GitVersionContext(fixture.Repository, new NullLog(), branch, new Config().ApplyDefaults()); var baseVersion = sut.GetVersions(gitVersionContext).Single(); baseVersion.SemanticVersion.ToString().ShouldBe(expectedBaseVersion); diff --git a/src/GitVersionCore.Tests/VersionSourceTests.cs b/src/GitVersionCore.Tests/VersionSourceTests.cs index 126a0a90cc..86b4e1e6fc 100644 --- a/src/GitVersionCore.Tests/VersionSourceTests.cs +++ b/src/GitVersionCore.Tests/VersionSourceTests.cs @@ -1,6 +1,7 @@ using GitTools.Testing; using GitVersion; using GitVersion.Configuration; +using GitVersion.Logging; using GitVersion.VersionCalculation; using LibGit2Sharp; using NUnit.Framework; @@ -11,6 +12,13 @@ namespace GitVersionCore.Tests [TestFixture] public class VersionSourceTests : TestBase { + private ILog log; + + public VersionSourceTests() + { + log = new NullLog(); + } + [Test] public void VersionSourceSha() { @@ -25,8 +33,8 @@ public void VersionSourceSha() Commands.Checkout(fixture.Repository, featureBranch); _ = fixture.Repository.MakeACommit(); - var context = new GitVersionContext(fixture.Repository, fixture.Repository.Head, config); - var nextVersionCalculator = new NextVersionCalculator(); + var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Head, config); + var nextVersionCalculator = new NextVersionCalculator(log); var version = nextVersionCalculator.FindVersion(context); version.BuildMetaData.VersionSourceSha.ShouldBe(initialCommit.Sha); @@ -43,8 +51,8 @@ public void VersionSourceShaOneCommit() { var initialCommit = fixture.Repository.MakeACommit(); - var context = new GitVersionContext(fixture.Repository, fixture.Repository.Head, config); - var nextVersionCalculator = new NextVersionCalculator(); + var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Head, config); + var nextVersionCalculator = new NextVersionCalculator(log); var version = nextVersionCalculator.FindVersion(context); version.BuildMetaData.VersionSourceSha.ShouldBe(initialCommit.Sha); @@ -67,8 +75,8 @@ public void VersionSourceShaUsingTag() Commands.Checkout(fixture.Repository, featureBranch); _ = fixture.Repository.MakeACommit(); - var context = new GitVersionContext(fixture.Repository, fixture.Repository.Head, config); - var nextVersionCalculator = new NextVersionCalculator(); + var context = new GitVersionContext(fixture.Repository, new NullLog(), fixture.Repository.Head, config); + var nextVersionCalculator = new NextVersionCalculator(log); 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 12be2d6bb0..c41d2e3b2d 100644 --- a/src/GitVersionCore.Tests/WixFileTests.cs +++ b/src/GitVersionCore.Tests/WixFileTests.cs @@ -6,7 +6,7 @@ using NUnit.Framework; using Shouldly; using GitVersion.Extensions; -using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersionCore.Tests { @@ -41,12 +41,17 @@ public void UpdateWixVersionFile() semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2019-02-20 23:59:59Z"); var config = new TestEffectiveConfiguration(buildMetaDataPadding: 2, legacySemVerPadding: 5); - var vars = VariableProvider.GetVariablesFor(semVer, config, false); - StringBuilder log = new StringBuilder(); - Action action = s => log.AppendLine(s); - Logger.SetLoggers(action, action, action, action); - using (var wixVersionFileUpdater = new WixVersionFileUpdater(workingDir, vars, fileSystem)) + 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); + + using (var wixVersionFileUpdater = new WixVersionFileUpdater(workingDir, vars, fileSystem, log)) { wixVersionFileUpdater.Update(); fileSystem.ReadAllText(wixVersionFileUpdater.WixVersionFile). diff --git a/src/GitVersionExe/Arguments.cs b/src/GitVersionCore/Arguments.cs similarity index 84% rename from src/GitVersionExe/Arguments.cs rename to src/GitVersionCore/Arguments.cs index 972e697fc4..b69dd0f273 100644 --- a/src/GitVersionExe/Arguments.cs +++ b/src/GitVersionCore/Arguments.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; using GitVersion.Configuration; -using GitVersion.Helpers; +using GitVersion.Logging; using GitVersion.OutputFormatters; namespace GitVersion @@ -13,16 +13,16 @@ public Arguments() OverrideConfig = new Config(); Output = OutputType.Json; UpdateAssemblyInfoFileName = new HashSet(); - Verbosity = VerbosityLevel.Info; + Verbosity = Verbosity.Normal; } public Authentication Authentication; public Config OverrideConfig; - public bool HasOverrideConfig { get; set; } - public ConfigFileLocator ConfigFileLocator { get; set; } = ConfigFileLocator.GetLocator(); + public bool HasOverrideConfig; public string TargetPath; + public string ConfigFile; public string TargetUrl; public string TargetBranch; @@ -54,7 +54,7 @@ public Arguments() public bool NoCache; public bool NoNormalize; - public VerbosityLevel Verbosity; + public Verbosity Verbosity; public void AddAssemblyInfoFileName(string fileName) { diff --git a/src/GitVersionCore/BuildServers/AppVeyor.cs b/src/GitVersionCore/BuildServers/AppVeyor.cs index 3481689c63..68876cd452 100644 --- a/src/GitVersionCore/BuildServers/AppVeyor.cs +++ b/src/GitVersionCore/BuildServers/AppVeyor.cs @@ -2,12 +2,13 @@ using System.Text; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class AppVeyor : BuildServerBase { - public AppVeyor(IEnvironment environment) : base(environment) + public AppVeyor(IEnvironment environment, ILog log) : base(environment, log) { } @@ -65,6 +66,17 @@ public override string[] GenerateSetParameterMessage(string name, string value) $"Adding Environment Variable. name='GitVersion_{name}' value='{value}']" }; } + + public override string GetCurrentBranch(bool usingDynamicRepos) + { + var pullRequestBranchName = Environment.GetEnvironmentVariable("APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH"); + if (!string.IsNullOrWhiteSpace(pullRequestBranchName)) + { + return pullRequestBranchName; + } + return Environment.GetEnvironmentVariable("APPVEYOR_REPO_BRANCH"); + } + public override bool PreventFetch() => false; } } diff --git a/src/GitVersionCore/BuildServers/VsoAgent.cs b/src/GitVersionCore/BuildServers/AzurePipelines.cs similarity index 80% rename from src/GitVersionCore/BuildServers/VsoAgent.cs rename to src/GitVersionCore/BuildServers/AzurePipelines.cs index d86b492e05..9ddd816feb 100644 --- a/src/GitVersionCore/BuildServers/VsoAgent.cs +++ b/src/GitVersionCore/BuildServers/AzurePipelines.cs @@ -4,12 +4,13 @@ using GitVersion.OutputVariables; using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { - public class VsoAgent : BuildServerBase + public class AzurePipelines : BuildServerBase { - public VsoAgent(IEnvironment environment) : base(environment) + public AzurePipelines(IEnvironment environment, ILog log) : base(environment, log) { } @@ -27,6 +28,11 @@ public override string[] GenerateSetParameterMessage(string name, string value) public override string GetCurrentBranch(bool usingDynamicRepos) { + var pullRequestBranchName = Environment.GetEnvironmentVariable("SYSTEM_PULLREQUEST_SOURCEBRANCH"); + if (!string.IsNullOrWhiteSpace(pullRequestBranchName)) + { + return pullRequestBranchName; + } return Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); } @@ -34,7 +40,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) public override string GenerateSetVersionMessage(VersionVariables variables) { - // For VSO, we'll get the Build Number and insert GitVersion variables where + // For AzurePipelines, we'll get the Build Number and insert GitVersion variables where // specified var buildNumberEnv = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER"); if (string.IsNullOrWhiteSpace(buildNumberEnv)) diff --git a/src/GitVersionCore/BuildServers/BuildServerList.cs b/src/GitVersionCore/BuildServers/BuildServerList.cs index ca8907fcc7..552e3e5f26 100644 --- a/src/GitVersionCore/BuildServers/BuildServerList.cs +++ b/src/GitVersionCore/BuildServers/BuildServerList.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { @@ -9,7 +9,7 @@ public static class BuildServerList { private static List supportedBuildServers; - public static IEnumerable GetApplicableBuildServers() + public static IEnumerable GetApplicableBuildServers(ILog log) { var buildServices = new List(); @@ -19,34 +19,34 @@ public static IEnumerable GetApplicableBuildServers() { if (buildServer.CanApplyToCurrentContext()) { - Logger.WriteInfo($"Applicable build agent found: '{buildServer.GetType().Name}'."); + log.Info($"Applicable build agent found: '{buildServer.GetType().Name}'."); buildServices.Add(buildServer); } } catch (Exception ex) { - Logger.WriteWarning($"Failed to check build server '{buildServer.GetType().Name}': {ex.Message}"); + log.Warning($"Failed to check build server '{buildServer.GetType().Name}': {ex.Message}"); } } return buildServices; } - public static void Init(IEnvironment environment) + public static void Init(IEnvironment environment, ILog log) { supportedBuildServers = new List { - new ContinuaCi(environment), - new TeamCity(environment), - new AppVeyor(environment), - new MyGet(environment), - new Jenkins(environment), - new GitLabCi(environment), - new VsoAgent(environment), - new TravisCI(environment), - new EnvRun(environment), - new Drone(environment), - new CodeBuild(environment) + 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 722b227a91..88fd422e19 100644 --- a/src/GitVersionCore/BuildServers/CodeBuild.cs +++ b/src/GitVersionCore/BuildServers/CodeBuild.cs @@ -3,6 +3,7 @@ using GitVersion.Common; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; +using GitVersion.Logging; namespace GitVersion.BuildServers { @@ -11,7 +12,7 @@ public sealed class CodeBuild : BuildServerBase public const string HeadRefEnvironmentName = "CODEBUILD_WEBHOOK_HEAD_REF"; private readonly string propertiesFileName; - public CodeBuild(IEnvironment environment, string propertiesFileName = "gitversion.properties") : base(environment) + public CodeBuild(IEnvironment environment, ILog log, string propertiesFileName = "gitversion.properties") : base(environment, log) { this.propertiesFileName = propertiesFileName; } diff --git a/src/GitVersionCore/BuildServers/ContinuaCi.cs b/src/GitVersionCore/BuildServers/ContinuaCi.cs index 67f226ecc3..2fe99be160 100644 --- a/src/GitVersionCore/BuildServers/ContinuaCi.cs +++ b/src/GitVersionCore/BuildServers/ContinuaCi.cs @@ -1,11 +1,12 @@ using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class ContinuaCi : BuildServerBase { - public ContinuaCi(IEnvironment environment) : base(environment) + public ContinuaCi(IEnvironment environment, ILog log) : base(environment, log) { } diff --git a/src/GitVersionCore/BuildServers/Drone.cs b/src/GitVersionCore/BuildServers/Drone.cs index 16f397a0a9..82f9f1c733 100644 --- a/src/GitVersionCore/BuildServers/Drone.cs +++ b/src/GitVersionCore/BuildServers/Drone.cs @@ -1,12 +1,13 @@ using System; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class Drone : BuildServerBase { - public Drone(IEnvironment environment) : base(environment) + public Drone(IEnvironment environment, ILog log) : base(environment, log) { } diff --git a/src/GitVersionCore/BuildServers/EnvRun.cs b/src/GitVersionCore/BuildServers/EnvRun.cs index 00423b40da..740d62bb81 100644 --- a/src/GitVersionCore/BuildServers/EnvRun.cs +++ b/src/GitVersionCore/BuildServers/EnvRun.cs @@ -1,13 +1,13 @@ using System.IO; using GitVersion.OutputVariables; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class EnvRun : BuildServerBase { - public EnvRun(IEnvironment environment) : base(environment) + public EnvRun(IEnvironment environment, ILog log) : base(environment, log) { } @@ -20,7 +20,7 @@ public override bool CanApplyToCurrentContext() { if (!File.Exists(envRunDatabasePath)) { - Logger.WriteError($"The database file of EnvRun.exe was not found at {envRunDatabasePath}."); + Log.Error($"The database file of EnvRun.exe was not found at {envRunDatabasePath}."); return false; } diff --git a/src/GitVersionCore/BuildServers/GitLabCi.cs b/src/GitVersionCore/BuildServers/GitLabCi.cs index e7079c3dbe..d5e97ff469 100755 --- a/src/GitVersionCore/BuildServers/GitLabCi.cs +++ b/src/GitVersionCore/BuildServers/GitLabCi.cs @@ -3,6 +3,7 @@ using GitVersion.OutputFormatters; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { @@ -11,7 +12,7 @@ public class GitLabCi : BuildServerBase public const string EnvironmentVariableName = "GITLAB_CI"; string _file; - public GitLabCi(IEnvironment environment, string propertiesFileName = "gitversion.properties") : base(environment) + public GitLabCi(IEnvironment environment, ILog log, string propertiesFileName = "gitversion.properties") : base(environment, log) { _file = propertiesFileName; } diff --git a/src/GitVersionCore/BuildServers/Jenkins.cs b/src/GitVersionCore/BuildServers/Jenkins.cs index 5f28352062..3657db8e59 100644 --- a/src/GitVersionCore/BuildServers/Jenkins.cs +++ b/src/GitVersionCore/BuildServers/Jenkins.cs @@ -3,6 +3,7 @@ using GitVersion.OutputFormatters; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { @@ -12,7 +13,7 @@ public class Jenkins : BuildServerBase string _file; protected override string EnvironmentVariable { get; } = EnvironmentVariableName; - public Jenkins(IEnvironment environment, string propertiesFileName = "gitversion.properties") : base(environment) + public Jenkins(IEnvironment environment, ILog log, string propertiesFileName = "gitversion.properties") : base(environment, log) { _file = propertiesFileName; } @@ -34,7 +35,7 @@ public override string GetCurrentBranch(bool usingDynamicRepos) { return IsPipelineAsCode() ? Environment.GetEnvironmentVariable("BRANCH_NAME") - : (Environment.GetEnvironmentVariable("GIT_LOCAL_BRANCH") ?? Environment.GetEnvironmentVariable("GIT_BRANCH")); + : Environment.GetEnvironmentVariable("GIT_LOCAL_BRANCH") ?? Environment.GetEnvironmentVariable("GIT_BRANCH"); } private bool IsPipelineAsCode() diff --git a/src/GitVersionCore/BuildServers/MyGet.cs b/src/GitVersionCore/BuildServers/MyGet.cs index e95c7c5354..4400fb2191 100644 --- a/src/GitVersionCore/BuildServers/MyGet.cs +++ b/src/GitVersionCore/BuildServers/MyGet.cs @@ -3,12 +3,13 @@ using GitVersion.Helpers; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class MyGet : BuildServerBase { - public MyGet(IEnvironment environment) : base(environment) + public MyGet(IEnvironment environment, ILog log) : base(environment, log) { } diff --git a/src/GitVersionCore/BuildServers/TeamCity.cs b/src/GitVersionCore/BuildServers/TeamCity.cs index acf35457b3..a67fae1987 100644 --- a/src/GitVersionCore/BuildServers/TeamCity.cs +++ b/src/GitVersionCore/BuildServers/TeamCity.cs @@ -1,12 +1,13 @@ using GitVersion.Helpers; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class TeamCity : BuildServerBase { - public TeamCity(IEnvironment environment) : base(environment) + public TeamCity(IEnvironment environment, ILog log) : base(environment, log) { } @@ -31,9 +32,9 @@ public override string GetCurrentBranch(bool usingDynamicRepos) return branchName; } - static void WriteBranchEnvVariableWarning() + private void WriteBranchEnvVariableWarning() { - Logger.WriteWarning(@"TeamCity doesn't make the current branch available through environmental variables. + Log.Warning(@"TeamCity doesn't make the current branch available through environmental variables. Depending on your authentication and transport setup of your git VCS root things may work. In that case, ignore this warning. diff --git a/src/GitVersionCore/BuildServers/TravisCI.cs b/src/GitVersionCore/BuildServers/TravisCI.cs index a1fb985849..c2b6a7f4db 100644 --- a/src/GitVersionCore/BuildServers/TravisCI.cs +++ b/src/GitVersionCore/BuildServers/TravisCI.cs @@ -1,11 +1,12 @@ using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.BuildServers { public class TravisCI : BuildServerBase { - public TravisCI(IEnvironment environment) : base(environment) + public TravisCI(IEnvironment environment, ILog log) : base(environment, log) { } diff --git a/src/GitVersionCore/Cache/GitVersionCache.cs b/src/GitVersionCore/Cache/GitVersionCache.cs index e74f60a17c..76b15f94eb 100644 --- a/src/GitVersionCore/Cache/GitVersionCache.cs +++ b/src/GitVersionCore/Cache/GitVersionCache.cs @@ -6,16 +6,19 @@ using GitVersion.OutputVariables; using YamlDotNet.Serialization; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Cache { public class GitVersionCache { - readonly IFileSystem fileSystem; + private readonly IFileSystem fileSystem; + private readonly ILog log; - public GitVersionCache(IFileSystem fileSystem) + public GitVersionCache(IFileSystem fileSystem, ILog log) { this.fileSystem = fileSystem; + this.log = log; } public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKey cacheKey, VersionVariables variablesFromCache) @@ -26,7 +29,7 @@ public void WriteVariablesToDiskCache(GitPreparer gitPreparer, GitVersionCacheKe variablesFromCache.FileName = cacheFileName; Dictionary dictionary; - using (Logger.IndentLog("Creating dictionary")) + using (log.IndentLog("Creating dictionary")) { dictionary = variablesFromCache.ToDictionary(x => x.Key, x => x.Value); } @@ -37,7 +40,7 @@ void WriteCacheOperation() { using (var sw = new StreamWriter(stream)) { - using (Logger.IndentLog("Storing version variables to cache file " + cacheFileName)) + using (log.IndentLog("Storing version variables to cache file " + cacheFileName)) { var serializer = new Serializer(); serializer.Serialize(sw, dictionary); @@ -46,7 +49,7 @@ void WriteCacheOperation() } } - var retryOperation = new OperationWithExponentialBackoff(new ThreadSleep(), WriteCacheOperation, maxRetries: 6); + var retryOperation = new OperationWithExponentialBackoff(new ThreadSleep(), log, WriteCacheOperation, maxRetries: 6); retryOperation.ExecuteAsync().Wait(); } @@ -69,18 +72,18 @@ private string PrepareCacheDirectory(GitPreparer gitPreparer) public VersionVariables LoadVersionVariablesFromDiskCache(GitPreparer gitPreparer, GitVersionCacheKey key) { - using (Logger.IndentLog("Loading version variables from disk cache")) + using (log.IndentLog("Loading version variables from disk cache")) { var cacheDir = PrepareCacheDirectory(gitPreparer); var cacheFileName = GetCacheFileName(key, cacheDir); if (!fileSystem.Exists(cacheFileName)) { - Logger.WriteInfo("Cache file " + cacheFileName + " not found."); + log.Info("Cache file " + cacheFileName + " not found."); return null; } - using (Logger.IndentLog("Deserializing version variables from cache file " + cacheFileName)) + using (log.IndentLog("Deserializing version variables from cache file " + cacheFileName)) { try { @@ -89,15 +92,15 @@ public VersionVariables LoadVersionVariablesFromDiskCache(GitPreparer gitPrepare } catch (Exception ex) { - Logger.WriteWarning("Unable to read cache file " + cacheFileName + ", deleting it."); - Logger.WriteInfo(ex.ToString()); + log.Warning("Unable to read cache file " + cacheFileName + ", deleting it."); + log.Info(ex.ToString()); try { fileSystem.Delete(cacheFileName); } catch (Exception deleteEx) { - Logger.WriteWarning($"Unable to delete corrupted version cache file {cacheFileName}. Got {deleteEx.GetType().FullName} exception."); + log.Warning($"Unable to delete corrupted version cache file {cacheFileName}. Got {deleteEx.GetType().FullName} exception."); } return null; diff --git a/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs b/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs index f56610daaf..24039e6cb3 100644 --- a/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs +++ b/src/GitVersionCore/Cache/GitVersionCacheKeyFactory.cs @@ -5,16 +5,16 @@ using System.Security.Cryptography; using System.Text; using GitVersion.Configuration; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Cache { class GitVersionCacheKeyFactory { - public static GitVersionCacheKey Create(IFileSystem fileSystem, GitPreparer gitPreparer, Config overrideConfig, ConfigFileLocator configFileLocator) + public static GitVersionCacheKey Create(IFileSystem fileSystem, ILog log, GitPreparer gitPreparer, Config overrideConfig, IConfigFileLocator configFileLocator) { - var gitSystemHash = GetGitSystemHash(gitPreparer); + var gitSystemHash = GetGitSystemHash(gitPreparer, log); var configFileHash = GetConfigFileHash(fileSystem, gitPreparer, configFileLocator); var repositorySnapshotHash = GetRepositorySnapshotHash(gitPreparer); var overrideConfigHash = GetOverrideConfigHash(overrideConfig); @@ -23,18 +23,18 @@ public static GitVersionCacheKey Create(IFileSystem fileSystem, GitPreparer gitP return new GitVersionCacheKey(compositeHash); } - static string GetGitSystemHash(GitPreparer gitPreparer) + static string GetGitSystemHash(GitPreparer gitPreparer, ILog log) { var dotGitDirectory = gitPreparer.GetDotGitDirectory(); // traverse the directory and get a list of files, use that for GetHash - var contents = CalculateDirectoryContents(Path.Combine(dotGitDirectory, "refs")); + var contents = CalculateDirectoryContents(log, Path.Combine(dotGitDirectory, "refs")); return GetHash(contents.ToArray()); } // based on https://msdn.microsoft.com/en-us/library/bb513869.aspx - static List CalculateDirectoryContents(string root) + static List CalculateDirectoryContents(ILog log, string root) { var result = new List(); @@ -72,12 +72,12 @@ static List CalculateDirectoryContents(string root) // about the systems on which this code will run. catch (UnauthorizedAccessException e) { - Logger.WriteError(e.Message); + log.Error(e.Message); continue; } catch (DirectoryNotFoundException e) { - Logger.WriteError(e.Message); + log.Error(e.Message); continue; } @@ -88,12 +88,12 @@ static List CalculateDirectoryContents(string root) } catch (UnauthorizedAccessException e) { - Logger.WriteError(e.Message); + log.Error(e.Message); continue; } catch (DirectoryNotFoundException e) { - Logger.WriteError(e.Message); + log.Error(e.Message); continue; } @@ -107,7 +107,7 @@ static List CalculateDirectoryContents(string root) } catch (IOException e) { - Logger.WriteError(e.Message); + log.Error(e.Message); } } @@ -157,11 +157,11 @@ private static string GetOverrideConfigHash(Config overrideConfig) return GetHash(configContent); } - private static string GetConfigFileHash(IFileSystem fileSystem, GitPreparer gitPreparer, ConfigFileLocator configFileLocator) + private static string GetConfigFileHash(IFileSystem fileSystem, GitPreparer 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. - var configFilePath = configFileLocator.SelectConfigFilePath(gitPreparer, fileSystem); + var configFilePath = configFileLocator.SelectConfigFilePath(gitPreparer); if (!fileSystem.Exists(configFilePath)) { return string.Empty; diff --git a/src/GitVersionCore/Common/BuildServerBase.cs b/src/GitVersionCore/Common/BuildServerBase.cs index 7dfea6a671..e0d42bcc1c 100644 --- a/src/GitVersionCore/Common/BuildServerBase.cs +++ b/src/GitVersionCore/Common/BuildServerBase.cs @@ -1,4 +1,5 @@ using System; +using GitVersion.Logging; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; @@ -6,11 +7,13 @@ namespace GitVersion.Common { public abstract class BuildServerBase : IBuildServer { + protected readonly ILog Log; protected IEnvironment Environment { get; } - protected BuildServerBase(IEnvironment environment) + protected BuildServerBase(IEnvironment environment, ILog log) { - this.Environment = environment; + Log = log; + Environment = environment; } protected abstract string EnvironmentVariable { get; } diff --git a/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs b/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs index 9d7c5de330..60b95319e5 100644 --- a/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs +++ b/src/GitVersionCore/Configuration/BranchConfigurationCalculator.cs @@ -3,24 +3,33 @@ using System.Linq; using System.Text.RegularExpressions; using GitVersion.Helpers; +using GitVersion.Logging; using LibGit2Sharp; namespace GitVersion.Configuration { - public class BranchConfigurationCalculator + public class BranchConfigurationCalculator : IBranchConfigurationCalculator { public static string FallbackConfigName = "Fallback"; + private GitVersionContext context; + private ILog log; + + public BranchConfigurationCalculator(ILog log, GitVersionContext context) + { + this.log = log; + this.context = context; + } /// /// Gets the for the current commit. /// - public static BranchConfig GetBranchConfiguration(GitVersionContext context, Branch targetBranch, IList excludedInheritBranches = null) + public BranchConfig GetBranchConfiguration(Branch targetBranch, IList excludedInheritBranches = null) { var matchingBranches = context.FullConfiguration.GetConfigForBranch(targetBranch.NameWithoutRemote()); if (matchingBranches == null) { - Logger.WriteInfo($"No branch configuration found for branch {targetBranch.FriendlyName}, falling back to default configuration"); + 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()); @@ -28,7 +37,7 @@ public static BranchConfig GetBranchConfiguration(GitVersionContext context, Bra if (matchingBranches.Increment == IncrementStrategy.Inherit) { - matchingBranches = InheritBranchConfiguration(context, targetBranch, matchingBranches, excludedInheritBranches); + matchingBranches = InheritBranchConfiguration(targetBranch, matchingBranches, excludedInheritBranches); if (matchingBranches.Name == FallbackConfigName && matchingBranches.Increment == IncrementStrategy.Inherit) { // We tried, and failed to inherit, just fall back to patch @@ -40,11 +49,11 @@ public static BranchConfig GetBranchConfiguration(GitVersionContext context, Bra } // TODO I think we need to take a fresh approach to this.. it's getting really complex with heaps of edge cases - static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch targetBranch, BranchConfig branchConfiguration, IList excludedInheritBranches) + private BranchConfig InheritBranchConfiguration(Branch targetBranch, BranchConfig branchConfiguration, IList excludedInheritBranches) { var repository = context.Repository; var config = context.FullConfiguration; - using (Logger.IndentLog("Attempting to inherit branch configuration from parent branch")) + using (log.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request @@ -97,11 +106,11 @@ static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch } } - Logger.WriteInfo("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName))); + log.Info("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName))); if (possibleParents.Count == 1) { - var branchConfig = GetBranchConfiguration(context, possibleParents[0], excludedInheritBranches); + var branchConfig = GetBranchConfiguration(possibleParents[0], excludedInheritBranches); // If we have resolved a fallback config we should not return that we have got config if (branchConfig.Name != FallbackConfigName) { @@ -136,7 +145,7 @@ static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch } var branchName = chosenBranch.FriendlyName; - Logger.WriteWarning(errorMessage + Environment.NewLine + Environment.NewLine + "Falling back to " + branchName + " branch config"); + log.Warning(errorMessage + Environment.NewLine + Environment.NewLine + "Falling back to " + branchName + " branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.IsSameBranch(chosenBranch)) @@ -150,7 +159,7 @@ static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch } else { - Logger.WriteWarning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); + log.Warning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); return new BranchConfig(branchConfiguration) { Increment = IncrementStrategy.Patch @@ -158,11 +167,11 @@ static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch } } - var inheritingBranchConfig = GetBranchConfiguration(context, chosenBranch, excludedInheritBranches); + var inheritingBranchConfig = GetBranchConfiguration(chosenBranch, excludedInheritBranches); var configIncrement = inheritingBranchConfig.Increment; if (inheritingBranchConfig.Name == FallbackConfigName && configIncrement == IncrementStrategy.Inherit) { - Logger.WriteWarning("Fallback config inherits by default, dropping to patch increment"); + log.Warning("Fallback config inherits by default, dropping to patch increment"); configIncrement = IncrementStrategy.Patch; } return new BranchConfig(branchConfiguration) @@ -175,7 +184,7 @@ static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch } } - static Branch[] CalculateWhenMultipleParents(IRepository repository, Commit currentCommit, ref Branch currentBranch, Branch[] excludedBranches) + private Branch[] CalculateWhenMultipleParents(IRepository repository, Commit currentCommit, ref Branch currentBranch, Branch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); var branches = repository.Branches.Where(b => !b.IsRemote && b.Tip == parents[1]).ToList(); @@ -206,14 +215,12 @@ static Branch[] CalculateWhenMultipleParents(IRepository repository, Commit curr } } - Logger.WriteInfo("HEAD is merge commit, this is likely a pull request using " + currentBranch.FriendlyName + " as base"); + log.Info("HEAD is merge commit, this is likely a pull request using " + currentBranch.FriendlyName + " as base"); 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; diff --git a/src/GitVersionCore/Configuration/Config.cs b/src/GitVersionCore/Configuration/Config.cs index 93f212af3b..a04bfecc89 100644 --- a/src/GitVersionCore/Configuration/Config.cs +++ b/src/GitVersionCore/Configuration/Config.cs @@ -6,7 +6,6 @@ using GitVersion.VersioningModes; using YamlDotNet.Serialization; using GitVersion.Extensions; -using GitVersion.Helpers; namespace GitVersion.Configuration { @@ -114,7 +113,8 @@ public BranchConfig GetConfigForBranch(string branchName) .Select(kvp => kvp.Value) .First(); - Logger.WriteWarning( + // 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}'"); @@ -122,7 +122,7 @@ public BranchConfig GetConfigForBranch(string branchName) } } - T MergeObjects(T target, T source) + private static T MergeObjects(T target, T source) { typeof(T).GetProperties() .Where(prop => prop.CanRead && prop.CanWrite) diff --git a/src/GitVersionCore/Configuration/ConfigFileLocator.cs b/src/GitVersionCore/Configuration/ConfigFileLocator.cs index 18ca3c7fd0..af00ea9764 100644 --- a/src/GitVersionCore/Configuration/ConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/ConfigFileLocator.cs @@ -1,41 +1,46 @@ using System.IO; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration { - public abstract class ConfigFileLocator + public abstract class ConfigFileLocator : IConfigFileLocator { - public static readonly ConfigFileLocator Default = new DefaultConfigFileLocator(); + protected readonly IFileSystem FileSystem; + protected readonly ILog Log; - public static ConfigFileLocator GetLocator(string filePath = null) => - !string.IsNullOrEmpty(filePath) ? new NamedConfigFileLocator(filePath) : Default; + protected ConfigFileLocator(IFileSystem fileSystem, ILog log) + { + FileSystem = fileSystem; + Log = log; + } - public abstract bool HasConfigFileAt(string workingDirectory, IFileSystem fileSystem); + public abstract bool HasConfigFileAt(string workingDirectory); - public abstract string GetConfigFilePath(string workingDirectory, IFileSystem fileSystem); + public abstract string GetConfigFilePath(string workingDirectory); - public abstract void Verify(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem); + public abstract void Verify(string workingDirectory, string projectRootDirectory); - public string SelectConfigFilePath(GitPreparer gitPreparer, IFileSystem fileSystem) + public string SelectConfigFilePath(GitPreparer gitPreparer) { var workingDirectory = gitPreparer.WorkingDirectory; var projectRootDirectory = gitPreparer.GetProjectRootDirectory(); - if (HasConfigFileAt(workingDirectory, fileSystem)) + if (HasConfigFileAt(workingDirectory)) { - return GetConfigFilePath(workingDirectory, fileSystem); + return GetConfigFilePath(workingDirectory); } - return GetConfigFilePath(projectRootDirectory, fileSystem); + return GetConfigFilePath(projectRootDirectory); } - public Config ReadConfig(string workingDirectory, IFileSystem fileSystem) + public Config ReadConfig(string workingDirectory) { - var configFilePath = GetConfigFilePath(workingDirectory, fileSystem); + var configFilePath = GetConfigFilePath(workingDirectory); - if (fileSystem.Exists(configFilePath)) + if (FileSystem.Exists(configFilePath)) { - var readAllText = fileSystem.ReadAllText(configFilePath); + var readAllText = FileSystem.ReadAllText(configFilePath); LegacyConfigNotifier.Notify(new StringReader(readAllText)); return ConfigSerialiser.Read(new StringReader(readAllText)); } @@ -43,7 +48,7 @@ public Config ReadConfig(string workingDirectory, IFileSystem fileSystem) return new Config(); } - public void Verify(GitPreparer gitPreparer, IFileSystem fileSystem) + public void Verify(GitPreparer gitPreparer) { if (!string.IsNullOrWhiteSpace(gitPreparer.TargetUrl)) { @@ -55,7 +60,7 @@ public void Verify(GitPreparer gitPreparer, IFileSystem fileSystem) var workingDirectory = gitPreparer.WorkingDirectory; var projectRootDirectory = gitPreparer.GetProjectRootDirectory(); - Verify(workingDirectory, projectRootDirectory, fileSystem); + Verify(workingDirectory, projectRootDirectory); } } } diff --git a/src/GitVersionCore/Configuration/ConfigurationProvider.cs b/src/GitVersionCore/Configuration/ConfigurationProvider.cs index 4bf574f7e8..5b17396ac7 100644 --- a/src/GitVersionCore/Configuration/ConfigurationProvider.cs +++ b/src/GitVersionCore/Configuration/ConfigurationProvider.cs @@ -3,10 +3,10 @@ using System.Linq; using System.Text; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Helpers; using GitVersion.VersioningModes; using GitVersion.Extensions; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration { @@ -28,7 +28,8 @@ public class ConfigurationProvider public const string HotfixBranchKey = "hotfix"; public const string SupportBranchKey = "support"; public const string DevelopBranchKey = "develop"; - public static Dictionary DefaultPreReleaseWeight = + + private static Dictionary DefaultPreReleaseWeight = new Dictionary { { DevelopBranchRegex, 0 }, @@ -42,22 +43,22 @@ public class ConfigurationProvider private const IncrementStrategy DefaultIncrementStrategy = IncrementStrategy.Inherit; - public static Config Provide(GitPreparer gitPreparer, IFileSystem fileSystem, ConfigFileLocator configFileLocator, bool applyDefaults = true, Config overrideConfig = null, string configFilePath = null) + 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, fileSystem)) + if (configFileLocator.HasConfigFileAt(workingDirectory)) { - return Provide(workingDirectory, fileSystem, configFileLocator, applyDefaults, overrideConfig); + return Provide(workingDirectory, configFileLocator, applyDefaults, overrideConfig); } - return Provide(projectRootDirectory, fileSystem, configFileLocator, applyDefaults, overrideConfig); + return Provide(projectRootDirectory, configFileLocator, applyDefaults, overrideConfig); } - public static Config Provide(string workingDirectory, IFileSystem fileSystem, ConfigFileLocator configFileLocator, bool applyDefaults = true, Config overrideConfig = null) + public static Config Provide(string workingDirectory, IConfigFileLocator configFileLocator, bool applyDefaults = true, Config overrideConfig = null) { - var readConfig = configFileLocator.ReadConfig(workingDirectory, fileSystem); + var readConfig = configFileLocator.ReadConfig(workingDirectory); VerifyConfiguration(readConfig); if (applyDefaults) @@ -233,9 +234,9 @@ public static void ApplyBranchDefaults(Config config, branchConfig.PreReleaseWeight = branchConfig.PreReleaseWeight ?? defaultPreReleaseNumber; } - public static string GetEffectiveConfigAsString(string workingDirectory, IFileSystem fileSystem, ConfigFileLocator configFileLocator) + public static string GetEffectiveConfigAsString(string workingDirectory, IConfigFileLocator configFileLocator) { - var config = Provide(workingDirectory, fileSystem, configFileLocator); + var config = Provide(workingDirectory, configFileLocator); var stringBuilder = new StringBuilder(); using (var stream = new StringWriter(stringBuilder)) { @@ -245,17 +246,17 @@ public static string GetEffectiveConfigAsString(string workingDirectory, IFileSy return stringBuilder.ToString(); } - public static void Init(string workingDirectory, IFileSystem fileSystem, IConsole console, ConfigFileLocator configFileLocator) + public static void Init(string workingDirectory, IFileSystem fileSystem, IConsole console, ILog log, IConfigFileLocator configFileLocator) { - var configFilePath = configFileLocator.GetConfigFilePath(workingDirectory, fileSystem); - var currentConfiguration = Provide(workingDirectory, fileSystem, applyDefaults: false, configFileLocator: configFileLocator); - var config = new ConfigInitWizard(console, fileSystem).Run(currentConfiguration, workingDirectory); + 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)) { - Logger.WriteInfo("Saving config file"); + 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 bf0c9d0e5e..694a4a81f3 100644 --- a/src/GitVersionCore/Configuration/DefaultConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/DefaultConfigFileLocator.cs @@ -1,27 +1,31 @@ using System.IO; using GitVersion.Exceptions; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration { public class DefaultConfigFileLocator : ConfigFileLocator { + public DefaultConfigFileLocator(IFileSystem fileSystem, ILog log) : base(fileSystem, log) + { + + } public const string DefaultFileName = "GitVersion.yml"; public const string ObsoleteFileName = "GitVersionConfig.yaml"; - public override bool HasConfigFileAt(string workingDirectory, IFileSystem fileSystem) + public override bool HasConfigFileAt(string workingDirectory) { var defaultConfigFilePath = Path.Combine(workingDirectory, DefaultFileName); - if (fileSystem.Exists(defaultConfigFilePath)) + if (FileSystem.Exists(defaultConfigFilePath)) { return true; } var deprecatedConfigFilePath = Path.Combine(workingDirectory, ObsoleteFileName); - if (fileSystem.Exists(deprecatedConfigFilePath)) + if (FileSystem.Exists(deprecatedConfigFilePath)) { return true; } @@ -29,16 +33,16 @@ public override bool HasConfigFileAt(string workingDirectory, IFileSystem fileSy return false; } - public override string GetConfigFilePath(string workingDirectory, IFileSystem fileSystem) + public override string GetConfigFilePath(string workingDirectory) { var ymlPath = Path.Combine(workingDirectory, DefaultFileName); - if (fileSystem.Exists(ymlPath)) + if (FileSystem.Exists(ymlPath)) { return ymlPath; } var deprecatedPath = Path.Combine(workingDirectory, ObsoleteFileName); - if (fileSystem.Exists(deprecatedPath)) + if (FileSystem.Exists(deprecatedPath)) { return deprecatedPath; } @@ -46,49 +50,49 @@ public override string GetConfigFilePath(string workingDirectory, IFileSystem fi return ymlPath; } - public override void Verify(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem) + public override void Verify(string workingDirectory, string projectRootDirectory) { - if (fileSystem.PathsEqual(workingDirectory, projectRootDirectory)) + if (FileSystem.PathsEqual(workingDirectory, projectRootDirectory)) { - WarnAboutObsoleteConfigFile(workingDirectory, fileSystem); + WarnAboutObsoleteConfigFile(workingDirectory); return; } - WarnAboutObsoleteConfigFile(workingDirectory, fileSystem); - WarnAboutObsoleteConfigFile(projectRootDirectory, fileSystem); + WarnAboutObsoleteConfigFile(workingDirectory); + WarnAboutObsoleteConfigFile(projectRootDirectory); - WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory, fileSystem); + WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory); } - private void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem) + private void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory) { - var workingConfigFile = GetConfigFilePath(workingDirectory, fileSystem); - var projectRootConfigFile = GetConfigFilePath(projectRootDirectory, fileSystem); + var workingConfigFile = GetConfigFilePath(workingDirectory); + var projectRootConfigFile = GetConfigFilePath(projectRootDirectory); - bool hasConfigInWorkingDirectory = fileSystem.Exists(workingConfigFile); - bool hasConfigInProjectRootDirectory = fileSystem.Exists(projectRootConfigFile); + bool hasConfigInWorkingDirectory = FileSystem.Exists(workingConfigFile); + bool hasConfigInProjectRootDirectory = FileSystem.Exists(projectRootConfigFile); if (hasConfigInProjectRootDirectory && hasConfigInWorkingDirectory) { throw new WarningException($"Ambiguous config file selection from '{workingConfigFile}' and '{projectRootConfigFile}'"); } } - private void WarnAboutObsoleteConfigFile(string workingDirectory, IFileSystem fileSystem) + private void WarnAboutObsoleteConfigFile(string workingDirectory) { var deprecatedConfigFilePath = Path.Combine(workingDirectory, ObsoleteFileName); - if (!fileSystem.Exists(deprecatedConfigFilePath)) + if (!FileSystem.Exists(deprecatedConfigFilePath)) { return; } var defaultConfigFilePath = Path.Combine(workingDirectory, DefaultFileName); - if (fileSystem.Exists(defaultConfigFilePath)) + if (FileSystem.Exists(defaultConfigFilePath)) { - Logger.WriteWarning(string.Format("Ambiguous config files at '{0}': '{1}' (deprecated) and '{2}'. Will be used '{2}'", workingDirectory, ObsoleteFileName, DefaultFileName)); + Log.Warning(string.Format("Ambiguous config files at '{0}': '{1}' (deprecated) and '{2}'. Will be used '{2}'", workingDirectory, ObsoleteFileName, DefaultFileName)); return; } - Logger.WriteWarning($"'{deprecatedConfigFilePath}' is deprecated, use '{DefaultFileName}' instead."); + Log.Warning($"'{deprecatedConfigFilePath}' is deprecated, use '{DefaultFileName}' instead."); } } diff --git a/src/GitVersionCore/Configuration/IBranchConfigurationCalculator.cs b/src/GitVersionCore/Configuration/IBranchConfigurationCalculator.cs new file mode 100644 index 0000000000..b775b0fa6f --- /dev/null +++ b/src/GitVersionCore/Configuration/IBranchConfigurationCalculator.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using LibGit2Sharp; + +namespace GitVersion.Configuration +{ + public interface IBranchConfigurationCalculator + { + /// + /// Gets the for the current commit. + /// + BranchConfig GetBranchConfiguration(Branch targetBranch, IList excludedInheritBranches = null); + } +} diff --git a/src/GitVersionCore/Configuration/IConfigFileLocator.cs b/src/GitVersionCore/Configuration/IConfigFileLocator.cs new file mode 100644 index 0000000000..333d1a617c --- /dev/null +++ b/src/GitVersionCore/Configuration/IConfigFileLocator.cs @@ -0,0 +1,12 @@ +namespace GitVersion.Configuration +{ + public interface IConfigFileLocator + { + bool HasConfigFileAt(string workingDirectory); + string GetConfigFilePath(string workingDirectory); + void Verify(string workingDirectory, string projectRootDirectory); + string SelectConfigFilePath(GitPreparer gitPreparer); + Config ReadConfig(string workingDirectory); + void Verify(GitPreparer gitPreparer); + } +} diff --git a/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs b/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs index d62f576673..b80274b64f 100644 --- a/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs +++ b/src/GitVersionCore/Configuration/Init/BuildServer/AppVeyorSetup.cs @@ -3,8 +3,8 @@ using System.IO; using System.Text; using GitVersion.Configuration.Init.Wizard; -using GitVersion.Helpers; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.BuildServer { @@ -16,10 +16,12 @@ enum ProjectVisibility class AppVeyorSetup : ConfigInitWizardStep { + private readonly ILog log; private ProjectVisibility _projectVisibility; - public AppVeyorSetup(IConsole console, IFileSystem fileSystem, ProjectVisibility visibility) : base(console, fileSystem) + public AppVeyorSetup(IConsole console, IFileSystem fileSystem, ILog log, ProjectVisibility visibility) : base(console, fileSystem, log) { + this.log = log; _projectVisibility = visibility; } @@ -28,21 +30,21 @@ protected override StepResult HandleResult(string result, Queue "0"; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs b/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs index bd38c3247a..26650c04bc 100644 --- a/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs +++ b/src/GitVersionCore/Configuration/Init/BuildServer/AppveyorPublicPrivate.cs @@ -1,12 +1,14 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.BuildServer { class AppveyorPublicPrivate : ConfigInitWizardStep { - public AppveyorPublicPrivate(IConsole console, IFileSystem fileSystem) : base(console, fileSystem) + + public AppveyorPublicPrivate(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -15,13 +17,13 @@ protected override StepResult HandleResult(string result, Queue null; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs b/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs index be30f26694..0b07ff62e4 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/AssemblyVersioningSchemeSetting.cs @@ -2,12 +2,13 @@ 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) : base(console, fileSystem) + public AssemblyVersioningSchemeSetting(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -16,27 +17,27 @@ protected override StepResult HandleResult(string result, Queue "0"; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs index f73e6e9347..ae918c143f 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranch.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { @@ -9,8 +10,8 @@ public class ConfigureBranch : ConfigInitWizardStep string name; readonly BranchConfig branchConfig; - public ConfigureBranch(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem) - : base(console, fileSystem) + public ConfigureBranch(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem, ILog log) + : base(console, fileSystem, log) { this.branchConfig = branchConfig; this.name = name; @@ -21,13 +22,13 @@ protected override StepResult HandleResult(string result, Queue "0"; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs index 04e5fa4565..a214a85d08 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/ConfigureBranches.cs @@ -3,12 +3,13 @@ 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) : base(console, fileSystem) + public ConfigureBranches(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -18,7 +19,7 @@ protected override StepResult HandleResult(string result, Queue> OrderedBranches(Co protected override string DefaultResult => "0"; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs b/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs index e5c65eaa40..0be6b62c5f 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/GlobalModeSetting.cs @@ -1,7 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.VersioningModes; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { @@ -10,8 +11,8 @@ public class GlobalModeSetting : ConfigInitWizardStep readonly ConfigInitWizardStep returnToStep; readonly bool isPartOfWizard; - public GlobalModeSetting(ConfigInitWizardStep returnToStep, bool isPartOfWizard, IConsole console, IFileSystem fileSystem) - : base(console, fileSystem) + public GlobalModeSetting(ConfigInitWizardStep returnToStep, bool isPartOfWizard, IConsole console, IFileSystem fileSystem, ILog log) + : base(console, fileSystem, log) { this.returnToStep = returnToStep; this.isPartOfWizard = isPartOfWizard; diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs index dc0f944102..aab1105b87 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchIncrementMode.cs @@ -2,6 +2,7 @@ using GitVersion.Configuration.Init.Wizard; using GitVersion.VersioningModes; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { @@ -10,8 +11,8 @@ public class SetBranchIncrementMode : ConfigInitWizardStep readonly string name; readonly BranchConfig branchConfig; - public SetBranchIncrementMode(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem) - : base(console, fileSystem) + public SetBranchIncrementMode(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem, ILog log) + : base(console, fileSystem, log) { this.name = name; this.branchConfig = branchConfig; @@ -22,15 +23,15 @@ protected override StepResult HandleResult(string result, Queue "0"; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs index c37055820a..33bab4719a 100644 --- a/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs +++ b/src/GitVersionCore/Configuration/Init/SetConfig/SetBranchTag.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using GitVersion.Configuration.Init.Wizard; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.SetConfig { @@ -9,8 +10,8 @@ public class SetBranchTag : ConfigInitWizardStep string name; readonly BranchConfig branchConfig; - public SetBranchTag(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem) - : base(console, fileSystem) + public SetBranchTag(string name, BranchConfig branchConfig, IConsole console, IFileSystem fileSystem, ILog log) + : base(console, fileSystem, log) { this.name = name; this.branchConfig = branchConfig; @@ -26,15 +27,15 @@ protected override StepResult HandleResult(string result, Queue "0"; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/SetNextVersion.cs b/src/GitVersionCore/Configuration/Init/SetNextVersion.cs index 72565260ce..d368a1db52 100644 --- a/src/GitVersionCore/Configuration/Init/SetNextVersion.cs +++ b/src/GitVersionCore/Configuration/Init/SetNextVersion.cs @@ -1,12 +1,13 @@ 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) : base(console, fileSystem) + public SetNextVersion(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -14,7 +15,7 @@ protected override StepResult HandleResult(string result, Queue null; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs index 5f212c8947..ed4eabe423 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizard.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { @@ -7,18 +8,20 @@ public class ConfigInitWizard { readonly IConsole console; readonly IFileSystem fileSystem; + private readonly ILog log; - public ConfigInitWizard(IConsole console, IFileSystem fileSystem) + public ConfigInitWizard(IConsole console, IFileSystem fileSystem, ILog log) { this.console = console; this.fileSystem = fileSystem; + this.log = log; } 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)); + steps.Enqueue(new EditConfigStep(console, fileSystem, log)); while (steps.Count > 0) { @@ -32,4 +35,4 @@ public Config Run(Config config, string workingDirectory) return config; } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs index 2e4e00d462..d818ea8bb7 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/ConfigInitWizardStep.cs @@ -1,20 +1,24 @@ using System; using System.Collections.Generic; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public abstract class ConfigInitWizardStep { - protected ConfigInitWizardStep(IConsole console, IFileSystem fileSystem) + + protected ConfigInitWizardStep(IConsole console, IFileSystem fileSystem, ILog log) { Console = console; FileSystem = fileSystem; + Log = log; } 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) { @@ -66,4 +70,4 @@ void InvalidResponse(Queue steps) protected abstract string GetPrompt(Config config, string workingDirectory); protected abstract string DefaultResult { get; } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs index d2fb00b36e..b8e2942361 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/FinishedSetupStep.cs @@ -1,10 +1,11 @@ using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Configuration.Init.Wizard { public class FinishedSetupStep : EditConfigStep { - public FinishedSetupStep(IConsole console, IFileSystem fileSystem) : base(console, fileSystem) + public FinishedSetupStep(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -13,4 +14,4 @@ protected override string GetPrompt(Config config, string workingDirectory) return "Questions are all done, you can now edit GitVersion's configuration further\r\n" + base.GetPrompt(config, workingDirectory); } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs index 6582037070..d275c18b86 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/GitFlowSetupStep.cs @@ -1,11 +1,12 @@ 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) : base(new FinishedSetupStep(console, fileSystem), true, console, fileSystem) + public GitFlowSetupStep(IConsole console, IFileSystem fileSystem, ILog log) : base(new FinishedSetupStep(console, fileSystem, log), true, console, fileSystem, log) { } @@ -15,4 +16,4 @@ protected override string GetPrompt(Config config, string workingDirectory) base.GetPrompt(config, workingDirectory); } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs index 272d2846fe..0ffa4490ba 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/GitHubFlowStep.cs @@ -1,11 +1,12 @@ 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) : base(new FinishedSetupStep(console, fileSystem), true, console, fileSystem) + public GitHubFlowStep(IConsole console, IFileSystem fileSystem, ILog log) : base(new FinishedSetupStep(console, fileSystem, log), true, console, fileSystem, log) { } @@ -14,4 +15,4 @@ protected override string GetPrompt(Config config, string workingDirectory) return "By default GitVersion will only increment the version when tagged\r\n\r\n" + base.GetPrompt(config, workingDirectory); } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs index 05a578939c..d21d3acd6f 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy1Step.cs @@ -1,11 +1,12 @@ 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) : base(console, fileSystem) + public PickBranchingStrategy1Step(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -17,10 +18,10 @@ protected override StepResult HandleResult(string result, Queue null; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs index 0bf335ea07..7576c46adc 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy2Step.cs @@ -1,11 +1,12 @@ 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) : base(console, fileSystem) + public PickBranchingStrategy2Step(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -20,10 +21,10 @@ protected override StepResult HandleResult(string result, Queue null; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs index b808fe8186..d695a552d4 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategy3Step.cs @@ -1,11 +1,12 @@ 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) : base(console, fileSystem) + public PickBranchingStrategy3Step(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -27,7 +28,7 @@ protected override StepResult HandleResult(string result, Queue null; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs index 3428ee073a..f0c99a1588 100644 --- a/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs +++ b/src/GitVersionCore/Configuration/Init/Wizard/PickBranchingStrategyStep.cs @@ -1,11 +1,12 @@ 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) : base(console, fileSystem) + public PickBranchingStrategyStep(IConsole console, IFileSystem fileSystem, ILog log) : base(console, fileSystem, log) { } @@ -14,13 +15,13 @@ protected override StepResult HandleResult(string result, Queue null; } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs b/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs index 963002c860..3b8ceaf329 100644 --- a/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs +++ b/src/GitVersionCore/Configuration/NamedConfigFileLocator.cs @@ -1,14 +1,14 @@ using System; using System.IO; -using GitVersion.Exceptions; using GitVersion.Common; +using GitVersion.Exceptions; +using GitVersion.Logging; namespace GitVersion.Configuration { public class NamedConfigFileLocator : ConfigFileLocator { - - public NamedConfigFileLocator(string filePath) + public NamedConfigFileLocator(string filePath, IFileSystem fileSystem, ILog log) : base(fileSystem, log) { if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException(nameof(filePath), "Empty file path provided!"); FilePath = filePath; @@ -16,27 +16,27 @@ public NamedConfigFileLocator(string filePath) public string FilePath { get; } - public override bool HasConfigFileAt(string workingDirectory, IFileSystem fileSystem) => - fileSystem.Exists(Path.Combine(workingDirectory, FilePath)); + public override bool HasConfigFileAt(string workingDirectory) => + FileSystem.Exists(Path.Combine(workingDirectory, FilePath)); - public override string GetConfigFilePath(string workingDirectory, IFileSystem fileSystem) => + public override string GetConfigFilePath(string workingDirectory) => Path.Combine(workingDirectory, FilePath); - public override void Verify(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem) + public override void Verify(string workingDirectory, string projectRootDirectory) { if (!Path.IsPathRooted(FilePath)) { - WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory, fileSystem); + WarnAboutAmbiguousConfigFileSelection(workingDirectory, projectRootDirectory); } } - private void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory, IFileSystem fileSystem) + private void WarnAboutAmbiguousConfigFileSelection(string workingDirectory, string projectRootDirectory) { - var workingConfigFile = GetConfigFilePath(workingDirectory, fileSystem); - var projectRootConfigFile = GetConfigFilePath(projectRootDirectory, fileSystem); + var workingConfigFile = GetConfigFilePath(workingDirectory); + var projectRootConfigFile = GetConfigFilePath(projectRootDirectory); - var hasConfigInWorkingDirectory = fileSystem.Exists(workingConfigFile); - var 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/ExecuteCore.cs b/src/GitVersionCore/ExecuteCore.cs index d8b5e4931e..81bfdbafcf 100644 --- a/src/GitVersionCore/ExecuteCore.cs +++ b/src/GitVersionCore/ExecuteCore.cs @@ -1,4 +1,3 @@ -using GitVersion.Helpers; using System; using System.Linq; using GitVersion.BuildServers; @@ -6,37 +5,41 @@ using GitVersion.OutputVariables; using GitVersion.Cache; using GitVersion.Common; +using GitVersion.Logging; using Environment = System.Environment; namespace GitVersion { public class ExecuteCore { - readonly IFileSystem fileSystem; + private readonly IFileSystem fileSystem; private readonly IEnvironment environment; - readonly ConfigFileLocator configFileLocator; - readonly GitVersionCache gitVersionCache; + private readonly ILog log; + private readonly IConfigFileLocator configFileLocator; + private readonly GitVersionCache gitVersionCache; - public ExecuteCore(IFileSystem fileSystem, IEnvironment environment, ConfigFileLocator configFileLocator = null) + public ExecuteCore(IFileSystem fileSystem, IEnvironment environment, ILog log, IConfigFileLocator configFileLocator = null) { this.fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); this.environment = environment; - this.configFileLocator = configFileLocator ?? ConfigFileLocator.Default; - gitVersionCache = new GitVersionCache(fileSystem); + 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); - // Normalise if we are running on build server - var applicableBuildServers = BuildServerList.GetApplicableBuildServers(); + BuildServerList.Init(environment, log); + + // Normalize if we are running on build server + var applicableBuildServers = BuildServerList.GetApplicableBuildServers(log); var buildServer = applicableBuildServers.FirstOrDefault(); - bool normaliseGitDirectory = !noNormalize && (buildServer != null); - var fetch = noFetch || (buildServer != null && buildServer.PreventFetch()); + var normalizeGitDirectory = !noNormalize && buildServer != null; + var fetch = noFetch || buildServer != null && buildServer.PreventFetch(); var shouldCleanUpRemotes = buildServer != null && buildServer.ShouldCleanUpRemotes(); - var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, fetch, workingDirectory); + var gitPreparer = new GitPreparer(log, targetUrl, dynamicRepositoryLocation, authentication, fetch, workingDirectory); - gitPreparer.Initialise(normaliseGitDirectory, ResolveCurrentBranch(buildServer, targetBranch, !string.IsNullOrWhiteSpace(dynamicRepositoryLocation)), shouldCleanUpRemotes); + gitPreparer.Initialise(normalizeGitDirectory, ResolveCurrentBranch(buildServer, targetBranch, !string.IsNullOrWhiteSpace(dynamicRepositoryLocation)), shouldCleanUpRemotes); var dotGitDirectory = gitPreparer.GetDotGitDirectory(); var projectRoot = gitPreparer.GetProjectRootDirectory(); @@ -52,19 +55,19 @@ public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicReposi // }, // Directory = workingDirectory //}); - Logger.WriteInfo($"Project root is: {projectRoot}"); - Logger.WriteInfo($"DotGit directory is: {dotGitDirectory}"); + 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, gitPreparer, overrideConfig, configFileLocator); + 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, buildServer, overrideConfig); + versionVariables = ExecuteInternal(targetBranch, commitId, gitPreparer, overrideConfig); if (!noCache) { @@ -74,7 +77,7 @@ public VersionVariables ExecuteGitVersion(string targetUrl, string dynamicReposi } catch (AggregateException e) { - Logger.WriteWarning($"One or more exceptions during cache write:{Environment.NewLine}{e}"); + log.Warning($"One or more exceptions during cache write:{Environment.NewLine}{e}"); } } } @@ -91,13 +94,13 @@ public bool TryGetVersion(string directory, out VersionVariables versionVariable } catch (Exception ex) { - Logger.WriteWarning("Could not determine assembly version: " + ex); + log.Warning("Could not determine assembly version: " + ex); versionVariables = null; return false; } } - static string ResolveCurrentBranch(IBuildServer buildServer, string targetBranch, bool isDynamicRepository) + string ResolveCurrentBranch(IBuildServer buildServer, string targetBranch, bool isDynamicRepository) { if (buildServer == null) { @@ -105,22 +108,23 @@ static string ResolveCurrentBranch(IBuildServer buildServer, string targetBranch } var currentBranch = buildServer.GetCurrentBranch(isDynamicRepository) ?? targetBranch; - Logger.WriteInfo("Branch from build environment: " + currentBranch); + log.Info("Branch from build environment: " + currentBranch); return currentBranch; } - VersionVariables ExecuteInternal(string targetBranch, string commitId, GitPreparer gitPreparer, IBuildServer buildServer, Config overrideConfig = null) + VersionVariables ExecuteInternal(string targetBranch, string commitId, GitPreparer gitPreparer, Config overrideConfig = null) { var versionFinder = new GitVersionFinder(); - var configuration = ConfigurationProvider.Provide(gitPreparer, fileSystem, overrideConfig: overrideConfig, configFileLocator: configFileLocator); + var configuration = ConfigurationProvider.Provide(gitPreparer, overrideConfig: overrideConfig, configFileLocator: configFileLocator); return gitPreparer.WithRepository(repo => { - var gitVersionContext = new GitVersionContext(repo, targetBranch, configuration, commitId: commitId); - var semanticVersion = versionFinder.FindVersion(gitVersionContext); + var gitVersionContext = new GitVersionContext(repo, log, targetBranch, configuration, commitId: commitId); + var semanticVersion = versionFinder.FindVersion(log, gitVersionContext); - return VariableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged); + var variableProvider = new VariableProvider(log); + return variableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged); }); } } diff --git a/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs b/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs index 2664a1ea74..8224a4dfcc 100644 --- a/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs +++ b/src/GitVersionCore/Extensions/VersionAssemblyInfoResources/AssemblyInfoFileUpdater.cs @@ -3,18 +3,18 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; -using GitVersion.Helpers; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Extensions.VersionAssemblyInfoResources { public class AssemblyInfoFileUpdater : IDisposable { - readonly List restoreBackupTasks = new List(); - readonly List cleanupBackupTasks = new List(); + private readonly List restoreBackupTasks = new List(); + private readonly List cleanupBackupTasks = new List(); - readonly IDictionary assemblyAttributeRegexes = new Dictionary + private readonly IDictionary assemblyAttributeRegexes = new Dictionary { {".cs", new Regex( @"(\s*\[\s*assembly:\s*(?:.*)\s*\]\s*$(\r?\n)?)", RegexOptions.Multiline) }, {".fs", new Regex( @"(\s*\[\s*\\s*\]\s*$(\r?\n)?)", RegexOptions.Multiline) }, @@ -23,23 +23,25 @@ public class AssemblyInfoFileUpdater : IDisposable private const string NewLine = "\r\n"; - ISet assemblyInfoFileNames; - string workingDirectory; - VersionVariables variables; - IFileSystem fileSystem; - bool ensureAssemblyInfo; - TemplateManager templateManager; + private readonly ISet assemblyInfoFileNames; + private readonly string workingDirectory; + private readonly VersionVariables variables; + private readonly IFileSystem fileSystem; + private readonly ILog log; + private readonly bool ensureAssemblyInfo; + private readonly TemplateManager templateManager; - public AssemblyInfoFileUpdater(string assemblyInfoFileName, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, bool ensureAssemblyInfo) : - this(new HashSet { assemblyInfoFileName }, workingDirectory, variables, fileSystem, ensureAssemblyInfo) + public AssemblyInfoFileUpdater(string assemblyInfoFileName, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, ILog log, bool ensureAssemblyInfo) : + this(new HashSet { assemblyInfoFileName }, workingDirectory, variables, fileSystem, log, ensureAssemblyInfo) { } - public AssemblyInfoFileUpdater(ISet assemblyInfoFileNames, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, bool ensureAssemblyInfo) + public AssemblyInfoFileUpdater(ISet assemblyInfoFileNames, string workingDirectory, VersionVariables variables, IFileSystem fileSystem, ILog log, bool ensureAssemblyInfo) { this.assemblyInfoFileNames = assemblyInfoFileNames; this.workingDirectory = workingDirectory; this.variables = variables; this.fileSystem = fileSystem; + this.log = log; this.ensureAssemblyInfo = ensureAssemblyInfo; templateManager = new TemplateManager(TemplateType.VersionAssemblyInfoResources); @@ -47,10 +49,10 @@ public AssemblyInfoFileUpdater(ISet assemblyInfoFileNames, string workin public void Update() { - Logger.WriteInfo("Updating assembly info files"); + log.Info("Updating assembly info files"); var assemblyInfoFiles = GetAssemblyInfoFiles(workingDirectory, assemblyInfoFileNames, fileSystem, ensureAssemblyInfo).ToList(); - Logger.WriteInfo($"Found {assemblyInfoFiles.Count} files"); + log.Info($"Found {assemblyInfoFiles.Count} files"); var assemblyVersion = variables.AssemblySemVer; var assemblyVersionRegex = new Regex(@"AssemblyVersion(Attribute)?\s*\(.*\)\s*"); @@ -111,7 +113,7 @@ public void Update() } } - string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, string inputString, string replaceString, string fileExtension, ref bool appendedAttributes) + private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, string inputString, string replaceString, string fileExtension, ref bool appendedAttributes) { var assemblyAddFormat = templateManager.GetAddFormatFor(fileExtension); @@ -139,7 +141,7 @@ string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, str return inputString; } - IEnumerable GetAssemblyInfoFiles(string workingDirectory, ISet assemblyInfoFileNames, IFileSystem fileSystem, bool ensureAssemblyInfo) + private IEnumerable GetAssemblyInfoFiles(string workingDirectory, ISet assemblyInfoFileNames, IFileSystem fileSystem, bool ensureAssemblyInfo) { if (assemblyInfoFileNames != null && assemblyInfoFileNames.Any(x => !string.IsNullOrWhiteSpace(x))) { @@ -167,7 +169,7 @@ IEnumerable GetAssemblyInfoFiles(string workingDirectory, ISet } } - bool EnsureVersionAssemblyInfoFile(bool ensureAssemblyInfo, IFileSystem fileSystem, string fullPath) + private bool EnsureVersionAssemblyInfoFile(bool ensureAssemblyInfo, IFileSystem fileSystem, string fullPath) { if (fileSystem.Exists(fullPath)) { @@ -194,7 +196,7 @@ bool EnsureVersionAssemblyInfoFile(bool ensureAssemblyInfo, IFileSystem fileSyst return true; } - Logger.WriteWarning($"No version assembly info template available to create source file '{fullPath}'"); + log.Warning($"No version assembly info template available to create source file '{fullPath}'"); return false; } diff --git a/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs b/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs index 4277de5451..e06be24d46 100644 --- a/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs +++ b/src/GitVersionCore/Extensions/WixVersionFileUpdater.cs @@ -2,9 +2,9 @@ using System.IO; using System.Text; using System.Xml; -using GitVersion.Helpers; using GitVersion.OutputVariables; using GitVersion.Common; +using GitVersion.Logging; namespace GitVersion.Extensions { @@ -12,19 +12,21 @@ public class WixVersionFileUpdater : IDisposable { VersionVariables variables; IFileSystem fileSystem; + private readonly ILog log; public string WixVersionFile { get; } public const string WIX_VERSION_FILE = "GitVersion_WixVersion.wxi"; - public WixVersionFileUpdater(string workingDirectory, VersionVariables variables, IFileSystem fileSystem) + 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); } public void Update() { - Logger.WriteInfo("Updating GitVersion_WixVersion.wxi"); + log.Info("Updating GitVersion_WixVersion.wxi"); XmlDocument doc = new XmlDocument(); doc.LoadXml(GetWixFormatFromVersionVariables()); @@ -55,7 +57,7 @@ private string GetWixFormatFromVersionVariables() public void Dispose() { - Logger.WriteInfo($"Done writing {WixVersionFile}"); + log.Info($"Done writing {WixVersionFile}"); } } } diff --git a/src/GitVersionCore/GitPreparer.cs b/src/GitVersionCore/GitPreparer.cs index 3f2d192a48..626dc0f844 100644 --- a/src/GitVersionCore/GitPreparer.cs +++ b/src/GitVersionCore/GitPreparer.cs @@ -2,24 +2,29 @@ using System.IO; using System.Linq; using GitVersion.Helpers; +using GitVersion.Logging; using LibGit2Sharp; namespace GitVersion { public class GitPreparer { - string targetUrl; - string dynamicRepositoryLocation; - AuthenticationInfo authentication; - bool noFetch; - string targetPath; + private readonly ILog log; + private string dynamicRepositoryLocation; + private AuthenticationInfo authentication; + private bool noFetch; - const string defaultRemoteName = "origin"; + private const string defaultRemoteName = "origin"; - public GitPreparer(string targetPath) : this(null, null, null, false, targetPath) { } - public GitPreparer(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, bool noFetch, string targetPath) + public GitPreparer(ILog log, Arguments arguments) + : this(log, arguments.TargetUrl, arguments.DynamicRepositoryLocation, arguments.Authentication, arguments.NoFetch, arguments.TargetPath) { - this.targetUrl = targetUrl; + } + + 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 @@ -28,38 +33,38 @@ public GitPreparer(string targetUrl, string dynamicRepositoryLocation, Authentic Password = authentication?.Password }; this.noFetch = noFetch; - this.targetPath = targetPath.TrimEnd('/', '\\'); + WorkingDirectory = targetPath.TrimEnd('/', '\\'); } - public string TargetUrl => targetUrl; + public string TargetUrl { get; } - public string WorkingDirectory => targetPath; + public string WorkingDirectory { get; } - public bool IsDynamicGitRepository => !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath); + private bool IsDynamicGitRepository => !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath); - public string DynamicGitRepositoryPath { get; private set; } + private string DynamicGitRepositoryPath { get; set; } - public void Initialise(bool normaliseGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false) + public void Initialise(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false) { - if (string.IsNullOrWhiteSpace(targetUrl)) + if (string.IsNullOrWhiteSpace(TargetUrl)) { - if (normaliseGitDirectory) + if (normalizeGitDirectory) { - using (Logger.IndentLog($"Normalizing git directory for branch '{currentBranch}'")) + using (log.IndentLog($"Normalizing git directory for branch '{currentBranch}'")) { if (shouldCleanUpRemotes) { CleanupDuplicateOrigin(); } - GitRepositoryHelper.NormalizeGitDirectory(GetDotGitDirectory(), authentication, noFetch, currentBranch, IsDynamicGitRepository); + GitRepositoryHelper.NormalizeGitDirectory(log, GetDotGitDirectory(), authentication, noFetch, currentBranch, IsDynamicGitRepository); } } return; } - var tempRepositoryPath = CalculateTemporaryRepositoryPath(targetUrl, dynamicRepositoryLocation); + var tempRepositoryPath = CalculateTemporaryRepositoryPath(TargetUrl, dynamicRepositoryLocation); - DynamicGitRepositoryPath = CreateDynamicRepository(tempRepositoryPath, authentication, targetUrl, currentBranch, noFetch); + DynamicGitRepositoryPath = CreateDynamicRepository(tempRepositoryPath, authentication, TargetUrl, currentBranch, noFetch); } private void CleanupDuplicateOrigin() @@ -94,7 +99,7 @@ public TResult WithRepository(Func action) } } - static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation) + private static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation) { var userTemp = dynamicRepositoryLocation ?? Path.GetTempPath(); var repositoryName = targetUrl.Split('/', '\\').Last().Replace(".git", string.Empty); @@ -119,7 +124,7 @@ static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicR return possiblePath; } - static bool GitRepoHasMatchingRemote(string possiblePath, string targetUrl) + private static bool GitRepoHasMatchingRemote(string possiblePath, string targetUrl) { try { @@ -136,11 +141,11 @@ static bool GitRepoHasMatchingRemote(string possiblePath, string targetUrl) public string GetDotGitDirectory() { - var dotGitDirectory = IsDynamicGitRepository ? DynamicGitRepositoryPath : Repository.Discover(targetPath); + var dotGitDirectory = IsDynamicGitRepository ? DynamicGitRepositoryPath : Repository.Discover(WorkingDirectory); dotGitDirectory = dotGitDirectory?.TrimEnd('/', '\\'); if (string.IsNullOrEmpty(dotGitDirectory)) - throw new DirectoryNotFoundException("Can't find the .git directory in " + targetPath); + 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; @@ -150,81 +155,80 @@ public string GetDotGitDirectory() public string GetProjectRootDirectory() { - Logger.WriteInfo($"IsDynamicGitRepository: {IsDynamicGitRepository}"); + log.Info($"IsDynamicGitRepository: {IsDynamicGitRepository}"); if (IsDynamicGitRepository) { - Logger.WriteInfo($"Returning Project Root as {targetPath}"); - return targetPath; + log.Info($"Returning Project Root as {WorkingDirectory}"); + return WorkingDirectory; } - var dotGitDirectory = Repository.Discover(targetPath); + var dotGitDirectory = Repository.Discover(WorkingDirectory); if (string.IsNullOrEmpty(dotGitDirectory)) - throw new DirectoryNotFoundException($"Can't find the .git directory in {targetPath}"); + throw new DirectoryNotFoundException($"Can't find the .git directory in {WorkingDirectory}"); using (var repo = new Repository(dotGitDirectory)) { var result = repo.Info.WorkingDirectory; - Logger.WriteInfo($"Returning Project Root from DotGitDirectory: {dotGitDirectory} - {result}"); + log.Info($"Returning Project Root from DotGitDirectory: {dotGitDirectory} - {result}"); return result; } } - static string CreateDynamicRepository(string targetPath, AuthenticationInfo authentication, string repositoryUrl, string targetBranch, bool noFetch) + private string CreateDynamicRepository(string targetPath, AuthenticationInfo auth, string repositoryUrl, string targetBranch, bool noFetch) { if (string.IsNullOrWhiteSpace(targetBranch)) { throw new Exception("Dynamic Git repositories must have a target branch (/b)"); } - using (Logger.IndentLog($"Creating dynamic repository at '{targetPath}'")) + using (log.IndentLog($"Creating dynamic repository at '{targetPath}'")) { var gitDirectory = Path.Combine(targetPath, ".git"); if (Directory.Exists(targetPath)) { - Logger.WriteInfo("Git repository already exists"); - using (Logger.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) + log.Info("Git repository already exists"); + using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) { - GitRepositoryHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch, targetBranch, true); + GitRepositoryHelper.NormalizeGitDirectory(log, gitDirectory, auth, noFetch, targetBranch, true); } return gitDirectory; } - CloneRepository(repositoryUrl, gitDirectory, authentication); + CloneRepository(repositoryUrl, gitDirectory, auth); - using (Logger.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) + using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) { // Normalize (download branches) before using the branch - GitRepositoryHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch, targetBranch, true); + GitRepositoryHelper.NormalizeGitDirectory(log, gitDirectory, auth, noFetch, targetBranch, true); } return gitDirectory; } } - static void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo authentication) + private void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo auth) { Credentials credentials = null; - if (authentication != null) + if (auth != null) { - if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password)) + if (!string.IsNullOrWhiteSpace(auth.Username) && !string.IsNullOrWhiteSpace(auth.Password)) { - Logger.WriteInfo($"Setting up credentials using name '{authentication.Username}'"); + log.Info($"Setting up credentials using name '{auth.Username}'"); credentials = new UsernamePasswordCredentials { - Username = authentication.Username, - Password = authentication.Password + Username = auth.Username, + Password = auth.Password }; } } - try { - using (Logger.IndentLog($"Cloning repository from url '{repositoryUrl}'")) + using (log.IndentLog($"Cloning repository from url '{repositoryUrl}'")) { var cloneOptions = new CloneOptions { @@ -233,7 +237,7 @@ static void CloneRepository(string repositoryUrl, string gitDirectory, Authentic }; var returnedPath = Repository.Clone(repositoryUrl, gitDirectory, cloneOptions); - Logger.WriteInfo($"Returned path after repository clone: {returnedPath}"); + log.Info($"Returned path after repository clone: {returnedPath}"); } } catch (LibGit2SharpException ex) @@ -241,11 +245,11 @@ static void CloneRepository(string repositoryUrl, string gitDirectory, Authentic var message = ex.Message; if (message.Contains("401")) { - throw new Exception("Unauthorised: Incorrect username/password"); + throw new Exception("Unauthorized: Incorrect username/password"); } if (message.Contains("403")) { - throw new Exception("Forbidden: Possbily Incorrect username/password"); + throw new Exception("Forbidden: Possibly Incorrect username/password"); } if (message.Contains("404")) { diff --git a/src/GitVersionCore/GitRepoMetadataProvider.cs b/src/GitVersionCore/GitRepoMetadataProvider.cs index aad7decc84..e54a886617 100644 --- a/src/GitVersionCore/GitRepoMetadataProvider.cs +++ b/src/GitVersionCore/GitRepoMetadataProvider.cs @@ -5,6 +5,7 @@ using System.Text.RegularExpressions; using GitVersion.Configuration; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion { @@ -15,14 +16,16 @@ public class GitRepoMetadataProvider private Dictionary> semanticVersionTagsOnBranchCache; private IRepository Repository { get; set; } 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; - public GitRepoMetadataProvider(IRepository repository, Config configuration) + public GitRepoMetadataProvider(IRepository repository, ILog log, Config configuration) { mergeBaseCache = new Dictionary, MergeBaseData>(); mergeBaseCommitsCache = new Dictionary>(); semanticVersionTagsOnBranchCache = new Dictionary>(); Repository = repository; + this.log = log; this.configuration = configuration; } @@ -48,11 +51,11 @@ public IEnumerable GetVersionTagsOnBranch(Branch branch, string { if (semanticVersionTagsOnBranchCache.ContainsKey(branch)) { - Logger.WriteDebug($"Cache hit for version tags on branch '{branch.CanonicalName}"); + log.Debug($"Cache hit for version tags on branch '{branch.CanonicalName}"); return semanticVersionTagsOnBranchCache[branch]; } - using (Logger.IndentLog($"Getting version tags from branch '{branch.CanonicalName}'.")) + using (log.IndentLog($"Getting version tags from branch '{branch.CanonicalName}'.")) { var tags = GetValidVersionTags(Repository, tagPrefixRegex); @@ -71,10 +74,10 @@ public IEnumerable GetBranchesContainingCommit(Commit commit, IList GetBranchesContainingCommit(Commit commit, IList GetBranchesContainingCommit(Commit commit, IList onlyTrackedBranches && !b.IsTracking)) { - Logger.WriteInfo($"Searching for commits reachable from '{branch.FriendlyName}'."); + log.Info($"Searching for commits reachable from '{branch.FriendlyName}'."); var commits = Repository.Commits.QueryBy(new CommitFilter { @@ -105,11 +108,11 @@ public IEnumerable GetBranchesContainingCommit(Commit commit, IList 1) { var first = possibleBranches.First(); - Logger.WriteInfo($"Multiple source branches have been found, picking the first one ({first.Branch.FriendlyName}).\n" + + log.Info($"Multiple source branches have been found, picking the first one ({first.Branch.FriendlyName}).\n" + "This may result in incorrect commit counting.\nOptions were:\n " + string.Join(", ", possibleBranches.Select(b => b.Branch.FriendlyName))); return first; @@ -229,7 +232,7 @@ List GetMergeCommitsForBranch(Branch branch, Branch[] excludedBran { if (mergeBaseCommitsCache.ContainsKey(branch)) { - Logger.WriteDebug($"Cache hit for getting merge commits for branch {branch.CanonicalName}."); + log.Debug($"Cache hit for getting merge commits for branch {branch.CanonicalName}."); return mergeBaseCommitsCache[branch]; } @@ -250,7 +253,7 @@ List GetMergeCommitsForBranch(Branch branch, Branch[] excludedBran { if (otherBranch.Tip == null) { - Logger.WriteWarning(string.Format(missingTipFormat, otherBranch.FriendlyName)); + log.Warning(string.Format(missingTipFormat, otherBranch.FriendlyName)); return BranchCommit.Empty; } diff --git a/src/GitVersionCore/GitVersionContext.cs b/src/GitVersionCore/GitVersionContext.cs index e68f0afdab..bc30367527 100644 --- a/src/GitVersionCore/GitVersionContext.cs +++ b/src/GitVersionCore/GitVersionContext.cs @@ -3,6 +3,7 @@ using System.Linq; using GitVersion.Configuration; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion { @@ -11,15 +12,18 @@ namespace GitVersion /// public class GitVersionContext { - public GitVersionContext(IRepository repository, string targetBranch, Config configuration, bool onlyEvaluateTrackedBranches = true, string commitId = null) - : this(repository, GetTargetBranch(repository, targetBranch), configuration, onlyEvaluateTrackedBranches, commitId) + public ILog Log { get; set; } + + 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) { } - public GitVersionContext(IRepository repository, Branch currentBranch, Config configuration, bool onlyEvaluateTrackedBranches = true, string commitId = null) + public GitVersionContext(IRepository repository, ILog log, Branch currentBranch, Config configuration, bool onlyEvaluateTrackedBranches = true, string commitId = null) { + Log = log; Repository = repository; - RepositoryMetadataProvider = new GitRepoMetadataProvider(repository, configuration); + RepositoryMetadataProvider = new GitRepoMetadataProvider(repository, log, configuration); FullConfiguration = configuration; OnlyEvaluateTrackedBranches = onlyEvaluateTrackedBranches; @@ -28,7 +32,7 @@ public GitVersionContext(IRepository repository, Branch currentBranch, Config co if (!string.IsNullOrWhiteSpace(commitId)) { - Logger.WriteInfo($"Searching for specific commit '{commitId}'"); + log.Info($"Searching for specific commit '{commitId}'"); var commit = repository.Commits.FirstOrDefault(c => string.Equals(c.Sha, commitId, StringComparison.OrdinalIgnoreCase)); if (commit != null) @@ -37,13 +41,13 @@ public GitVersionContext(IRepository repository, Branch currentBranch, Config co } else { - Logger.WriteWarning($"Commit '{commitId}' specified but not found"); + log.Warning($"Commit '{commitId}' specified but not found"); } } if (CurrentCommit == null) { - Logger.WriteInfo("Using latest commit on specified branch"); + log.Info("Using latest commit on specified branch"); CurrentCommit = currentBranch.Tip; } @@ -72,19 +76,20 @@ public GitVersionContext(IRepository repository, Branch currentBranch, Config co /// /// Contains the raw configuration, use Configuration for specific config based on the current GitVersion context. /// - public Config FullConfiguration { get; private set; } - public SemanticVersion CurrentCommitTaggedVersion { get; private set; } - public bool OnlyEvaluateTrackedBranches { get; private set; } + public Config FullConfiguration { get; } + public SemanticVersion CurrentCommitTaggedVersion { get; } + public bool OnlyEvaluateTrackedBranches { get; } public EffectiveConfiguration Configuration { get; private set; } - public IRepository Repository { get; private set; } - public Branch CurrentBranch { get; private set; } - public Commit CurrentCommit { get; private set; } - public bool IsCurrentCommitTagged { get; private set; } - public GitRepoMetadataProvider RepositoryMetadataProvider { get; private set; } + public IRepository Repository { get; } + public Branch CurrentBranch { get; } + public Commit CurrentCommit { get; } + public bool IsCurrentCommitTagged { get; } + public GitRepoMetadataProvider RepositoryMetadataProvider { get; } - void CalculateEffectiveConfiguration() + private void CalculateEffectiveConfiguration() { - var currentBranchConfig = BranchConfigurationCalculator.GetBranchConfiguration(this, CurrentBranch); + IBranchConfigurationCalculator calculator = new BranchConfigurationCalculator(Log, this); + var currentBranchConfig = calculator.GetBranchConfiguration(CurrentBranch); if (!currentBranchConfig.VersioningMode.HasValue) throw new Exception($"Configuration value for 'Versioning mode' for branch {currentBranchConfig.Name} has no value. (this should not happen, please report an issue)"); diff --git a/src/GitVersionCore/GitVersionFinder.cs b/src/GitVersionCore/GitVersionFinder.cs index 9f1fc3e61a..af68cdf63e 100644 --- a/src/GitVersionCore/GitVersionFinder.cs +++ b/src/GitVersionCore/GitVersionFinder.cs @@ -2,17 +2,18 @@ using GitVersion.Exceptions; using GitVersion.VersionCalculation; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion { public class GitVersionFinder { - public SemanticVersion FindVersion(GitVersionContext context) + public SemanticVersion FindVersion(ILog log, GitVersionContext context) { - Logger.WriteInfo($"Running against branch: {context.CurrentBranch.FriendlyName} ({(context.CurrentCommit == null ? "-" : context.CurrentCommit.Sha)})"); + log.Info($"Running against branch: {context.CurrentBranch.FriendlyName} ({(context.CurrentCommit == null ? "-" : context.CurrentCommit.Sha)})"); if (context.IsCurrentCommitTagged) { - Logger.WriteInfo($"Current commit is tagged with version {context.CurrentCommitTaggedVersion}, " + + log.Info($"Current commit is tagged with version {context.CurrentCommitTaggedVersion}, " + "version calculation is for metadata only."); } EnsureMainTopologyConstraints(context); @@ -23,7 +24,7 @@ public SemanticVersion FindVersion(GitVersionContext context) throw new WarningException("NextVersion.txt has been deprecated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement"); } - return new NextVersionCalculator().FindVersion(context); + return new NextVersionCalculator(log).FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) diff --git a/src/GitVersionCore/Helpers/GitRepositoryHelper.cs b/src/GitVersionCore/Helpers/GitRepositoryHelper.cs index c0b4b98864..d34debfb6a 100644 --- a/src/GitVersionCore/Helpers/GitRepositoryHelper.cs +++ b/src/GitVersionCore/Helpers/GitRepositoryHelper.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using GitVersion.Exceptions; +using GitVersion.Logging; using LibGit2Sharp; namespace GitVersion.Helpers @@ -12,7 +13,7 @@ public static class GitRepositoryHelper /// Normalisation of a git directory turns all remote branches into local branches, turns pull request refs into a real branch and a few other things. This is designed to be run *only on the build server* which checks out repositories in different ways. /// It is not recommended to run normalisation against a local repository /// - public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo authentication, + public static void NormalizeGitDirectory(ILog log, string gitDirectory, AuthenticationInfo authentication, bool noFetch, string currentBranch, bool isDynamicRepository) { using (var repo = new Repository(gitDirectory)) @@ -23,22 +24,22 @@ public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo try { - var remote = EnsureOnlyOneRemoteIsDefined(repo); + var remote = EnsureOnlyOneRemoteIsDefined(log, repo); - AddMissingRefSpecs(repo, remote); + AddMissingRefSpecs(log, repo, remote); //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) { - Logger.WriteInfo("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories"); + 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(authentication, remote, repo); + Fetch(log, authentication, remote, repo); } - EnsureLocalBranchExistsForCurrentBranch(repo, remote, currentBranch); - CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(repo, remote.Name); + 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) @@ -48,22 +49,21 @@ public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo var newExpectedSha = repo.Head.Tip.Sha; var newExpectedBranchName = repo.Head.CanonicalName; - Logger.WriteInfo($"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; - expectedBranchName = newExpectedBranchName; } var headSha = repo.Refs.Head.TargetIdentifier; if (!repo.Info.IsHeadDetached) { - Logger.WriteInfo($"HEAD points at branch '{headSha}'."); + log.Info($"HEAD points at branch '{headSha}'."); return; } - Logger.WriteInfo($"HEAD is detached and points at commit '{headSha}'."); - Logger.WriteInfo(string.Format("Local Refs:\r\n" + string.Join(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 @@ -75,7 +75,7 @@ public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo : null; if (matchingCurrentBranch != null) { - Logger.WriteInfo($"Checking out local branch '{currentBranch}'."); + log.Info($"Checking out local branch '{currentBranch}'."); Commands.Checkout(repo, matchingCurrentBranch); } else if (localBranchesWhereCommitShaIsHead.Count > 1) @@ -84,11 +84,11 @@ public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo var csvNames = string.Join(", ", branchNames); const string moveBranchMsg = "Move one of the branches along a commit to remove warning"; - Logger.WriteWarning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames})."); + 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) { - Logger.WriteWarning("Because one of the branches is 'master', will build master." + moveBranchMsg); + log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg); Commands.Checkout(repo, master); } else @@ -97,7 +97,7 @@ public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo if (branchesWithoutSeparators.Count == 1) { var branchWithoutSeparator = branchesWithoutSeparators[0]; - Logger.WriteWarning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg); + log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg); Commands.Checkout(repo, branchWithoutSeparator); } else @@ -108,12 +108,12 @@ public static void NormalizeGitDirectory(string gitDirectory, AuthenticationInfo } else if (localBranchesWhereCommitShaIsHead.Count == 0) { - Logger.WriteInfo($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); - CreateFakeBranchPointingAtThePullRequestTip(repo, authentication); + log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); + CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication); } else { - Logger.WriteInfo($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'."); + log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'."); Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]); } } @@ -140,13 +140,13 @@ public static string CreateGitLogArgs(int? maxCommits) return @"log --graph --format=""%h %cr %d"" --decorate --date=relative --all --remotes=*" + (maxCommits != null ? $" -n {maxCommits}" : null); } - public static void Fetch(AuthenticationInfo authentication, Remote remote, Repository repo) + private static void Fetch(ILog log, AuthenticationInfo authentication, Remote remote, Repository repo) { - Logger.WriteInfo($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}."); + log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}."); Commands.Fetch(repo, remote.Name, new string[0], authentication.ToFetchOptions(), null); } - static void EnsureLocalBranchExistsForCurrentBranch(Repository repo, Remote remote, string currentBranch) + static void EnsureLocalBranchExistsForCurrentBranch(ILog log, Repository repo, Remote remote, string currentBranch) { if (string.IsNullOrEmpty(currentBranch)) return; @@ -168,13 +168,13 @@ static void EnsureLocalBranchExistsForCurrentBranch(Repository repo, Remote remo if (repo.Branches.All(b => b.CanonicalName != localCanonicalName)) { - Logger.WriteInfo(isBranch ? $"Creating local branch {localCanonicalName}" + log.Info(isBranch ? $"Creating local branch {localCanonicalName}" : $"Creating local branch {localCanonicalName} pointing at {repoTipId}"); repo.Refs.Add(localCanonicalName, repoTipId); } else { - Logger.WriteInfo(isBranch ? $"Updating local branch {localCanonicalName} to point at {repoTip.Sha}" + log.Info(isBranch ? $"Updating local branch {localCanonicalName} to point at {repoTip.Sha}" : $"Updating local branch {localCanonicalName} to match ref {currentBranch}"); repo.Refs.UpdateTarget(repo.Refs[localCanonicalName], repoTipId); } @@ -182,30 +182,30 @@ static void EnsureLocalBranchExistsForCurrentBranch(Repository repo, Remote remo Commands.Checkout(repo, localCanonicalName); } - static void AddMissingRefSpecs(Repository repo, Remote remote) + static void AddMissingRefSpecs(ILog log, Repository repo, Remote remote) { if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*")) return; var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*"; - Logger.WriteInfo($"Adding refspec: {allBranchesFetchRefSpec}"); + log.Info($"Adding refspec: {allBranchesFetchRefSpec}"); repo.Network.Remotes.Update(remote.Name, r => r.FetchRefSpecs.Add(allBranchesFetchRefSpec)); } - static void CreateFakeBranchPointingAtThePullRequestTip(Repository repo, AuthenticationInfo authentication) + static void CreateFakeBranchPointingAtThePullRequestTip(ILog log, Repository repo, AuthenticationInfo authentication) { var remote = repo.Network.Remotes.Single(); - Logger.WriteInfo("Fetching remote refs to see if there is a pull request ref"); + log.Info("Fetching remote refs to see if there is a pull request ref"); var remoteTips = (string.IsNullOrEmpty(authentication.Username) ? GetRemoteTipsForAnonymousUser(repo, remote) : GetRemoteTipsUsingUsernamePasswordCredentials(repo, remote, authentication.Username, authentication.Password)) .ToList(); - Logger.WriteInfo("Remote Refs:\r\n" + string.Join(Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); + log.Info("Remote Refs:\r\n" + string.Join(Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); var headTipSha = repo.Head.Tip.Sha; @@ -226,11 +226,11 @@ static void CreateFakeBranchPointingAtThePullRequestTip(Repository repo, Authent var reference = refs[0]; var canonicalName = reference.CanonicalName; - Logger.WriteInfo($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'."); + log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'."); if (canonicalName.StartsWith("refs/tags")) { - Logger.WriteInfo($"Checking out tag '{canonicalName}'"); + log.Info($"Checking out tag '{canonicalName}'"); Commands.Checkout(repo, reference.Target.Sha); return; } @@ -243,10 +243,10 @@ static void CreateFakeBranchPointingAtThePullRequestTip(Repository repo, Authent var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/"); - Logger.WriteInfo($"Creating fake local branch '{fakeBranchName}'."); + log.Info($"Creating fake local branch '{fakeBranchName}'."); repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha)); - Logger.WriteInfo($"Checking local branch '{fakeBranchName}' out."); + log.Info($"Checking local branch '{fakeBranchName}' out."); Commands.Checkout(repo, fakeBranchName); } @@ -264,7 +264,7 @@ static IEnumerable GetRemoteTipsForAnonymousUser(Repository rep return repo.Network.ListReferences(remote).Select(r => r.ResolveToDirectReference()); } - static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(Repository repo, string remoteName) + static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(ILog log, Repository repo, string remoteName) { var prefix = $"refs/remotes/{remoteName}/"; var remoteHeadCanonicalName = $"{prefix}{"HEAD"}"; @@ -284,16 +284,16 @@ static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(Repository repo, s var remotedirectReference = remoteTrackingReference.ResolveToDirectReference(); if (localRef.ResolveToDirectReference().TargetIdentifier == remotedirectReference.TargetIdentifier) { - Logger.WriteInfo($"Skipping update of '{remoteTrackingReference.CanonicalName}' as it already matches the remote ref."); + log.Info($"Skipping update of '{remoteTrackingReference.CanonicalName}' as it already matches the remote ref."); continue; } var remoteRefTipId = remotedirectReference.Target.Id; - Logger.WriteInfo($"Updating local ref '{localRef.CanonicalName}' to point at {remoteRefTipId}."); + log.Info($"Updating local ref '{localRef.CanonicalName}' to point at {remoteRefTipId}."); repo.Refs.UpdateTarget(localRef, remoteRefTipId); continue; } - Logger.WriteInfo($"Creating local branch from remote tracking '{remoteTrackingReference.CanonicalName}'."); + log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.CanonicalName}'."); repo.Refs.Add(localCanonicalName, new ObjectId(remoteTrackingReference.ResolveToDirectReference().TargetIdentifier), true); var branch = repo.Branches[branchName]; @@ -301,7 +301,7 @@ static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(Repository repo, s } } - public static Remote EnsureOnlyOneRemoteIsDefined(IRepository repo) + public static Remote EnsureOnlyOneRemoteIsDefined(ILog log, IRepository repo) { var remotes = repo.Network.Remotes; var howMany = remotes.Count(); @@ -309,7 +309,7 @@ public static Remote EnsureOnlyOneRemoteIsDefined(IRepository repo) if (howMany == 1) { var remote = remotes.Single(); - Logger.WriteInfo($"One remote found ({remote.Name} -> '{remote.Url}')."); + log.Info($"One remote found ({remote.Name} -> '{remote.Url}')."); return remote; } diff --git a/src/GitVersionCore/Helpers/LibGitExtensions.cs b/src/GitVersionCore/Helpers/LibGitExtensions.cs index 548d1a08f8..68a4e28f5f 100644 --- a/src/GitVersionCore/Helpers/LibGitExtensions.cs +++ b/src/GitVersionCore/Helpers/LibGitExtensions.cs @@ -93,46 +93,6 @@ public static string GetRepositoryDirectory(this IRepository repository, bool om return gitDirectory; } - public static void CheckoutFilesIfExist(this IRepository repository, params string[] fileNames) - { - if (fileNames == null || fileNames.Length == 0) - { - return; - } - - Logger.WriteInfo("Checking out files that might be needed later in dynamic repository"); - - foreach (var fileName in fileNames) - { - try - { - Logger.WriteInfo($" Trying to check out '{fileName}'"); - - var headBranch = repository.Head; - var tip = headBranch.Tip; - - var treeEntry = tip[fileName]; - if (treeEntry == null) - { - continue; - } - - var fullPath = Path.Combine(repository.GetRepositoryDirectory(), fileName); - using (var stream = ((Blob)treeEntry.Target).GetContentStream()) - { - using (var streamReader = new BinaryReader(stream)) - { - File.WriteAllBytes(fullPath, streamReader.ReadBytes((int)stream.Length)); - } - } - } - catch (Exception ex) - { - Logger.WriteWarning($" An error occurred while checking out '{fileName}': '{ex.Message}'"); - } - } - } - public static Branch FindBranch(this IRepository repository, string branchName) { return repository.Branches.FirstOrDefault(x => x.NameWithoutRemote() == branchName); diff --git a/src/GitVersionCore/Helpers/Logger.cs b/src/GitVersionCore/Helpers/Logger.cs deleted file mode 100644 index c6959f650c..0000000000 --- a/src/GitVersionCore/Helpers/Logger.cs +++ /dev/null @@ -1,120 +0,0 @@ -using System; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace GitVersion.Helpers -{ - public static class Logger - { - static readonly Regex ObscurePasswordRegex = new Regex("(https?://)(.+)(:.+@)", RegexOptions.Compiled); - static string indent = string.Empty; - - static Logger() - { - Reset(); - } - - public static Action WriteDebug { get; private set; } - public static Action WriteInfo { get; private set; } - public static Action WriteWarning { get; private set; } - public static Action WriteError { get; private set; } - - public static IDisposable IndentLog(string operationDescription) - { - var start = DateTime.Now; - WriteInfo("Begin: " + operationDescription); - indent = indent + " "; - return new ActionDisposable(() => - { - var length = indent.Length - 2; - indent = length > 0 ? indent.Substring(0, length) : indent; - WriteInfo(string.Format(CultureInfo.InvariantCulture, "End: {0} (Took: {1:N}ms)", operationDescription, DateTime.Now.Subtract(start).TotalMilliseconds)); - }); - } - - static Action ObscurePassword(Action info) - { - void LogAction(string s) - { - s = ObscurePasswordRegex.Replace(s, "$1$2:*******@"); - info(s); - } - - return LogAction; - } - - public static void SetLoggers(Action debug, Action info, Action warn, Action error) - { - if (debug == null) throw new ArgumentNullException(nameof(debug)); - if (info == null) throw new ArgumentNullException(nameof(info)); - if (warn == null) throw new ArgumentNullException(nameof(warn)); - if (error == null) throw new ArgumentNullException(nameof(error)); - - WriteDebug = LogMessage(ObscurePassword(debug), "DEBUG"); - WriteInfo = LogMessage(ObscurePassword(info), "INFO"); - WriteWarning = LogMessage(ObscurePassword(warn), "WARN"); - WriteError = LogMessage(ObscurePassword(error), "ERROR"); - } - - public static IDisposable AddLoggersTemporarily(Action debug, Action info, Action warn, Action error) - { - var currentDebug = WriteDebug; - var currentInfo = WriteInfo; - var currentWarn = WriteWarning; - var currentError = WriteError; - SetLoggers(s => - { - debug(s); - currentDebug(s); - }, s => - { - info(s); - currentInfo(s); - }, s => - { - warn(s); - currentWarn(s); - }, s => - { - error(s); - currentError(s); - }); - - return new ActionDisposable(() => - { - WriteDebug = currentDebug; - WriteInfo = currentInfo; - WriteWarning = currentWarn; - WriteError = currentError; - }); - } - - static Action LogMessage(Action logAction, string level) - { - return s => logAction(string.Format(CultureInfo.InvariantCulture, "{0}{1} [{2:MM/dd/yy H:mm:ss:ff}] {3}", indent, level, DateTime.Now, s)); - } - - public static void Reset() - { - WriteDebug = s => { throw new Exception("Debug logger not defined. Attempted to log: " + s); }; - WriteInfo = s => { throw new Exception("Info logger not defined. Attempted to log: " + s); }; - WriteWarning = s => { throw new Exception("Warning logger not defined. Attempted to log: " + s); }; - WriteError = s => { throw new Exception("Error logger not defined. Attempted to log: " + s); }; - } - - class ActionDisposable : IDisposable - { - readonly Action action; - - public ActionDisposable(Action action) - { - this.action = action; - } - - public void Dispose() - { - action(); - } - } - } -} diff --git a/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs b/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs index 5512332b38..f438b3e7a6 100644 --- a/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs +++ b/src/GitVersionCore/Helpers/OperationWithExponentialBackoff.cs @@ -2,21 +2,24 @@ 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 ILog log; private Action Operation; private int MaxRetries; - public OperationWithExponentialBackoff(IThreadSleep threadSleep, Action operation, int maxRetries = 5) + 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.log = log; Operation = operation; MaxRetries = maxRetries; } @@ -46,7 +49,7 @@ public async Task ExecuteAsync() } } - Logger.WriteInfo($"Operation failed, retrying in {sleepMSec} milliseconds."); + log.Info($"Operation failed, retrying in {sleepMSec} milliseconds."); await ThreadSleep.SleepAsync(sleepMSec); sleepMSec *= 2; diff --git a/src/GitVersionCore/Helpers/ProcessHelper.cs b/src/GitVersionCore/Helpers/ProcessHelper.cs index 432bd68897..389ca08bab 100644 --- a/src/GitVersionCore/Helpers/ProcessHelper.cs +++ b/src/GitVersionCore/Helpers/ProcessHelper.cs @@ -13,7 +13,7 @@ public static class ProcessHelper static volatile object lockObject = new object(); // http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/f6069441-4ab1-4299-ad6a-b8bb9ed36be3 - public static Process Start(ProcessStartInfo startInfo) + private static Process Start(ProcessStartInfo startInfo) { Process process; @@ -112,7 +112,9 @@ public static int Run(Action output, Action errorOutput, TextRea psi.EnvironmentVariables.Add(environmentalVariable.Key, environmentalVariable.Value); } if (psi.EnvironmentVariables.ContainsKey(environmentalVariable.Key) && environmentalVariable.Value == null) + { psi.EnvironmentVariables.Remove(environmentalVariable.Key); + } } using (var process = Start(psi)) @@ -174,7 +176,7 @@ public enum ErrorModes NoOpenFileErrorBox = 0x8000 } - public struct ChangeErrorMode : IDisposable + private struct ChangeErrorMode : IDisposable { readonly int oldMode; diff --git a/src/GitVersionCore/Log/ConsoleAppender.cs b/src/GitVersionCore/Log/ConsoleAppender.cs new file mode 100644 index 0000000000..40b58e0b49 --- /dev/null +++ b/src/GitVersionCore/Log/ConsoleAppender.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; + +namespace GitVersion.Logging +{ + public class ConsoleAppender : ILogAppender + { + private readonly object _lock; + private IDictionary _palettes; + public ConsoleAppender() + { + _lock = new object(); + _palettes = CreatePalette(); + } + public void WriteTo(LogLevel level, string message) + { + lock (_lock) + { + try + { + var (backgroundColor, foregroundColor) = _palettes[level]; + + Console.BackgroundColor = backgroundColor; + Console.ForegroundColor = foregroundColor; + + if (level == LogLevel.Error) + { + Console.Error.Write(message); + } + else if (level != LogLevel.None) + { + Console.Write(message); + } + } + finally + { + Console.ResetColor(); + if (level == LogLevel.Error) + { + Console.Error.WriteLine(); + } + else if (level != LogLevel.None) + { + Console.WriteLine(); + } + } + } + } + + private IDictionary CreatePalette() + { + var background = Console.BackgroundColor; + var palette = new Dictionary + { + { LogLevel.Error, (ConsoleColor.DarkRed, ConsoleColor.White) }, + { LogLevel.Warn, (background, ConsoleColor.Yellow) }, + { LogLevel.Info, (background, ConsoleColor.White) }, + { LogLevel.Debug, (background, ConsoleColor.DarkGray) } + }; + return palette; + } + } +} diff --git a/src/GitVersionCore/Log/Disposable.cs b/src/GitVersionCore/Log/Disposable.cs new file mode 100644 index 0000000000..00e7e25ed2 --- /dev/null +++ b/src/GitVersionCore/Log/Disposable.cs @@ -0,0 +1,32 @@ +using System; + +namespace GitVersion.Logging +{ + public static class Disposable + { + static Disposable() + { + Empty = Create(() => { }); + } + + public static IDisposable Create(Action disposer) => new AnonymousDisposable(disposer); + + public static readonly IDisposable Empty; + + private sealed class AnonymousDisposable : IDisposable + { + public AnonymousDisposable(Action disposer) + { + _disposer = disposer ?? throw new ArgumentNullException(nameof(disposer)); + } + + public void Dispose() + { + _disposer?.Invoke(); + _disposer = null; + } + + private Action _disposer; + } + } +} \ No newline at end of file diff --git a/src/GitVersionCore/Log/FileAppender.cs b/src/GitVersionCore/Log/FileAppender.cs new file mode 100644 index 0000000000..6218e51643 --- /dev/null +++ b/src/GitVersionCore/Log/FileAppender.cs @@ -0,0 +1,46 @@ +using System; +using System.IO; +using System.Threading; + +namespace GitVersion.Logging +{ + public class FileAppender : ILogAppender + { + private static readonly ReaderWriterLock locker = new ReaderWriterLock(); + private readonly string filePath; + + public FileAppender(string filePath) + { + this.filePath = filePath; + + var logFile = new FileInfo(Path.GetFullPath(filePath)); + + // NOTE: logFile.Directory will be null if the path is i.e. C:\logfile.log. @asbjornu + logFile.Directory?.Create(); + if (logFile.Exists) return; + + using (logFile.CreateText()) { } + } + + public void WriteTo(LogLevel level, string message) + { + try + { + if (level != LogLevel.None) + { + WriteLogEntry(filePath, message); + } + } + catch (Exception) + { + // + } + } + + private static void WriteLogEntry(string logFilePath, string str) + { + var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{str}\r\n"; + File.AppendAllText(logFilePath, contents); + } + } +} diff --git a/src/GitVersionCore/Log/ILog.cs b/src/GitVersionCore/Log/ILog.cs new file mode 100644 index 0000000000..8da5a8925f --- /dev/null +++ b/src/GitVersionCore/Log/ILog.cs @@ -0,0 +1,12 @@ +using System; + +namespace GitVersion.Logging +{ + public interface ILog + { + Verbosity Verbosity { get; set; } + void Write(Verbosity verbosity, LogLevel level, string format, params object[] args); + IDisposable IndentLog(string operationDescription); + void AddLogAppender(ILogAppender logAppender); + } +} diff --git a/src/GitVersionCore/Log/ILogAppender.cs b/src/GitVersionCore/Log/ILogAppender.cs new file mode 100644 index 0000000000..8d88810b1d --- /dev/null +++ b/src/GitVersionCore/Log/ILogAppender.cs @@ -0,0 +1,7 @@ +namespace GitVersion.Logging +{ + public interface ILogAppender + { + void WriteTo(LogLevel level, string message); + } +} diff --git a/src/GitVersionCore/Log/Log.cs b/src/GitVersionCore/Log/Log.cs new file mode 100644 index 0000000000..885393a9ba --- /dev/null +++ b/src/GitVersionCore/Log/Log.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace GitVersion.Logging +{ + public sealed class Log : ILog + { + private IEnumerable appenders; + private readonly Regex ObscurePasswordRegex = new Regex("(https?://)(.+)(:.+@)", RegexOptions.Compiled); + private readonly StringBuilder sb; + private string indent = string.Empty; + + public Log(params ILogAppender[] appenders) + { + this.appenders = appenders ?? Array.Empty(); + sb = new StringBuilder(); + Verbosity = Verbosity.Normal; + } + + public Verbosity Verbosity { get; set; } + + public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) + { + if (verbosity > Verbosity) + { + return; + } + + var formattedString = FormatMessage(string.Format(format, args), level.ToString().ToUpperInvariant()); + foreach (var appender in appenders) + { + appender.WriteTo(level, formattedString); + } + + sb.Append(formattedString); + } + + public IDisposable IndentLog(string operationDescription) + { + var start = DateTime.Now; + Write(Verbosity.Normal, LogLevel.Info, $"Begin: {operationDescription}"); + indent += " "; + + return Disposable.Create(() => + { + var length = indent.Length - 2; + indent = length > 0 ? indent.Substring(0, length) : indent; + Write(Verbosity.Normal, LogLevel.Info, string.Format(CultureInfo.InvariantCulture, "End: {0} (Took: {1:N}ms)", operationDescription, DateTime.Now.Subtract(start).TotalMilliseconds)); + }); + } + + public void AddLogAppender(ILogAppender logAppender) + { + appenders = appenders.Concat(new[] { logAppender }); + } + + public override string ToString() + { + return sb.ToString(); + } + + private string FormatMessage(string message, string level) + { + 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/Log/LogAction.cs b/src/GitVersionCore/Log/LogAction.cs new file mode 100644 index 0000000000..850274bde5 --- /dev/null +++ b/src/GitVersionCore/Log/LogAction.cs @@ -0,0 +1,6 @@ +namespace GitVersion.Logging +{ + public delegate void LogAction(LogActionEntry actionEntry); + + public delegate void LogActionEntry(string format, params object[] args); +} diff --git a/src/GitVersionCore/Log/LogExtensions.cs b/src/GitVersionCore/Log/LogExtensions.cs new file mode 100644 index 0000000000..75aa8f9826 --- /dev/null +++ b/src/GitVersionCore/Log/LogExtensions.cs @@ -0,0 +1,177 @@ +using System; +using System.Collections.Generic; + +namespace GitVersion.Logging +{ + public static class LogExtensions + { + public static void Debug(this ILog log, string format, params object[] args) + { + log?.Write(LogLevel.Debug, format, args); + } + + public static void Debug(this ILog log, Verbosity verbosity, string format, params object[] args) + { + log?.Write(verbosity, LogLevel.Debug, format, args); + } + + public static void Debug(this ILog log, LogAction logAction) + { + log?.Write(LogLevel.Debug, logAction); + } + + public static void Debug(this ILog log, Verbosity verbosity, LogAction logAction) + { + log?.Write(verbosity, LogLevel.Debug, logAction); + } + + public static void Warning(this ILog log, string format, params object[] args) + { + log?.Write(LogLevel.Warn, format, args); + } + + public static void Warning(this ILog log, Verbosity verbosity, string format, params object[] args) + { + log?.Write(verbosity, LogLevel.Warn, format, args); + } + + public static void Warning(this ILog log, LogAction logAction) + { + log?.Write(LogLevel.Warn, logAction); + } + + public static void Warning(this ILog log, Verbosity verbosity, LogAction logAction) + { + log?.Write(verbosity, LogLevel.Warn, logAction); + } + + public static void Info(this ILog log, string format, params object[] args) + { + log?.Write(LogLevel.Info, format, args); + } + + public static void Info(this ILog log, Verbosity verbosity, string format, params object[] args) + { + log?.Write(verbosity, LogLevel.Info, format, args); + } + + public static void Info(this ILog log, LogAction logAction) + { + log?.Write(LogLevel.Info, logAction); + } + + public static void Info(this ILog log, Verbosity verbosity, LogAction logAction) + { + log?.Write(verbosity, LogLevel.Info, logAction); + } + + public static void Error(this ILog log, string format, params object[] args) + { + log?.Write(LogLevel.Error, format, args); + } + + public static void Error(this ILog log, Verbosity verbosity, string format, params object[] args) + { + log?.Write(verbosity, LogLevel.Error, format, args); + } + + public static void Error(this ILog log, LogAction logAction) + { + log?.Write(LogLevel.Error, logAction); + } + + public static void Error(this ILog log, Verbosity verbosity, LogAction logAction) + { + log?.Write(verbosity, LogLevel.Error, logAction); + } + + public static void Write(this ILog log, LogLevel level, string format, params object[] args) + { + if (log == null) + return; + + var verbosity = GetVerbosityForLevel(level); + if (verbosity > log.Verbosity) + { + return; + } + + log.Write(verbosity, level, format, args); + } + + public static void Write(this ILog log, Verbosity verbosity, LogLevel level, LogAction logAction) + { + if (log == null || logAction == null) + return; + + if (verbosity > log.Verbosity) + { + return; + } + + void ActionEntry(string format, object[] args) => log.Write(verbosity, level, format, args); + logAction(ActionEntry); + } + + public static void Write(this ILog log, LogLevel level, LogAction logAction) + { + if (log == null || logAction == null) + return; + + var verbosity = GetVerbosityForLevel(level); + if (verbosity > log.Verbosity) + { + return; + } + + void ActionEntry(string format, object[] args) => log.Write(verbosity, level, format, args); + logAction(ActionEntry); + } + + public static IDisposable QuietVerbosity(this ILog log) + { + return log.WithVerbosity(Verbosity.Quiet); + } + + public static IDisposable MinimalVerbosity(this ILog log) + { + return log.WithVerbosity(Verbosity.Minimal); + } + + public static IDisposable NormalVerbosity(this ILog log) + { + return log.WithVerbosity(Verbosity.Normal); + } + + public static IDisposable VerboseVerbosity(this ILog log) + { + return log.WithVerbosity(Verbosity.Verbose); + } + + public static IDisposable DiagnosticVerbosity(this ILog log) + { + return log.WithVerbosity(Verbosity.Diagnostic); + } + + public static IDisposable WithVerbosity(this ILog log, Verbosity verbosity) + { + if (log == null) + { + throw new ArgumentNullException(nameof(log)); + } + var lastVerbosity = log.Verbosity; + log.Verbosity = verbosity; + return Disposable.Create(() => log.Verbosity = lastVerbosity); + } + + public static Verbosity GetVerbosityForLevel(LogLevel level) => verbosityMaps[level]; + + private static readonly IDictionary verbosityMaps = new Dictionary + { + { LogLevel.Debug, Verbosity.Diagnostic }, + { LogLevel.Info, Verbosity.Normal }, + { LogLevel.Warn, Verbosity.Minimal }, + { LogLevel.Error, Verbosity.Quiet }, + }; + } +} diff --git a/src/GitVersionCore/Helpers/VerbosityLevel.cs b/src/GitVersionCore/Log/LogLevel.cs similarity index 58% rename from src/GitVersionCore/Helpers/VerbosityLevel.cs rename to src/GitVersionCore/Log/LogLevel.cs index 8ee6b1f844..d46f71f472 100644 --- a/src/GitVersionCore/Helpers/VerbosityLevel.cs +++ b/src/GitVersionCore/Log/LogLevel.cs @@ -1,6 +1,6 @@ -namespace GitVersion.Helpers +namespace GitVersion.Logging { - public enum VerbosityLevel + public enum LogLevel { None, Error, diff --git a/src/GitVersionCore/Log/NullLog.cs b/src/GitVersionCore/Log/NullLog.cs new file mode 100644 index 0000000000..b2aa48365b --- /dev/null +++ b/src/GitVersionCore/Log/NullLog.cs @@ -0,0 +1,24 @@ +using System; + +namespace GitVersion.Logging +{ + public sealed class NullLog : ILog + { + public Verbosity Verbosity { get; set; } + + public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) + { + } + + public IDisposable IndentLog(string operationDescription) + { + return Disposable.Empty; + } + + public void AddLogAppender(ILogAppender logAppender) + { + } + + public string Indent { get; set; } + } +} diff --git a/src/GitVersionCore/Log/Verbosity.cs b/src/GitVersionCore/Log/Verbosity.cs new file mode 100644 index 0000000000..de90aa73c5 --- /dev/null +++ b/src/GitVersionCore/Log/Verbosity.cs @@ -0,0 +1,11 @@ +namespace GitVersion.Logging +{ + public enum Verbosity + { + Quiet = 0, + Minimal = 1, + Normal = 2, + Verbose = 3, + Diagnostic = 4 + } +} diff --git a/src/GitVersionCore/OutputVariables/IVariableProvider.cs b/src/GitVersionCore/OutputVariables/IVariableProvider.cs new file mode 100644 index 0000000000..91f1801d7f --- /dev/null +++ b/src/GitVersionCore/OutputVariables/IVariableProvider.cs @@ -0,0 +1,9 @@ +using GitVersion.Configuration; + +namespace GitVersion.OutputVariables +{ + public interface IVariableProvider + { + VersionVariables GetVariablesFor(SemanticVersion semanticVersion, EffectiveConfiguration config, bool isCurrentCommitTagged); + } +} diff --git a/src/GitVersionCore/OutputVariables/VariableProvider.cs b/src/GitVersionCore/OutputVariables/VariableProvider.cs index afadac8257..cdc168a896 100644 --- a/src/GitVersionCore/OutputVariables/VariableProvider.cs +++ b/src/GitVersionCore/OutputVariables/VariableProvider.cs @@ -5,12 +5,19 @@ using GitVersion.VersioningModes; using GitVersion.Configuration; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion.OutputVariables { - public static class VariableProvider + public class VariableProvider : IVariableProvider { - public static VersionVariables GetVariablesFor(SemanticVersion semanticVersion, EffectiveConfiguration config, bool isCurrentCommitTagged) + private readonly ILog log; + + public VariableProvider(ILog log) + { + this.log = log; + } + public VersionVariables GetVariablesFor(SemanticVersion semanticVersion, EffectiveConfiguration config, bool isCurrentCommitTagged) { var isContinuousDeploymentMode = config.VersioningMode == VersioningMode.ContinuousDeployment && !isCurrentCommitTagged; if (isContinuousDeploymentMode) @@ -19,7 +26,8 @@ public static VersionVariables GetVariablesFor(SemanticVersion semanticVersion, // Continuous Deployment always requires a pre-release tag unless the commit is tagged if (!semanticVersion.PreReleaseTag.HasTag()) { - semanticVersion.PreReleaseTag.Name = NextVersionCalculator.GetBranchSpecificTag(config, semanticVersion.BuildMetaData.Branch, null); + var nextVersionCalculator = new NextVersionCalculator(log); + semanticVersion.PreReleaseTag.Name = nextVersionCalculator.GetBranchSpecificTag(config, semanticVersion.BuildMetaData.Branch, null); if (string.IsNullOrEmpty(semanticVersion.PreReleaseTag.Name)) { semanticVersion.PreReleaseTag.Name = config.ContinuousDeploymentFallbackTag; diff --git a/src/GitVersionCore/SemanticVersionExtensions.cs b/src/GitVersionCore/SemanticVersionExtensions.cs index 3e9886ca09..02748ca557 100644 --- a/src/GitVersionCore/SemanticVersionExtensions.cs +++ b/src/GitVersionCore/SemanticVersionExtensions.cs @@ -1,11 +1,10 @@ -using LibGit2Sharp; using GitVersion.Configuration; namespace GitVersion { public static class SemanticVersionExtensions { - public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, IRepository repository, EffectiveConfiguration configuration) + public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, EffectiveConfiguration configuration) { if (!string.IsNullOrEmpty(configuration.NextVersion) && SemanticVersion.TryParse(configuration.NextVersion, configuration.GitTagPrefix, out var manualNextVersion)) { @@ -18,4 +17,4 @@ public static void OverrideVersionManuallyIfNeeded(this SemanticVersion version, } } } -} \ No newline at end of file +} diff --git a/src/GitVersionCore/SemanticVersionPreReleaseTag.cs b/src/GitVersionCore/SemanticVersionPreReleaseTag.cs index f43484408f..25c1f55385 100644 --- a/src/GitVersionCore/SemanticVersionPreReleaseTag.cs +++ b/src/GitVersionCore/SemanticVersionPreReleaseTag.cs @@ -95,7 +95,8 @@ public static SemanticVersionPreReleaseTag Parse(string preReleaseTag) var match = Regex.Match(preReleaseTag, @"(?.*?)\.?(?\d+)?$"); if (!match.Success) { - Logger.WriteWarning($"Unable to successfully parse semver tag {preReleaseTag}"); + // TODO check how to log this + Console.WriteLine($"Unable to successfully parse semver tag {preReleaseTag}"); return new SemanticVersionPreReleaseTag(); } diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs index 467d43c829..f3c96376ce 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculator.cs @@ -3,22 +3,24 @@ using System.Linq; using System.Text.RegularExpressions; using GitVersion.VersionCalculation.BaseVersionCalculators; -using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion.VersionCalculation { public class BaseVersionCalculator : IBaseVersionCalculator { + private readonly ILog log; readonly BaseVersionStrategy[] strategies; - public BaseVersionCalculator(params BaseVersionStrategy[] strategies) + public BaseVersionCalculator(ILog log, params BaseVersionStrategy[] strategies) { + this.log = log; this.strategies = strategies; } public BaseVersion GetBaseVersion(GitVersionContext context) { - using (Logger.IndentLog("Calculating base versions")) + using (log.IndentLog("Calculating base versions")) { var baseVersions = strategies .SelectMany(s => s.GetVersions(context)) @@ -26,13 +28,13 @@ public BaseVersion GetBaseVersion(GitVersionContext context) { if (v == null) return false; - Logger.WriteInfo(v.ToString()); + log.Info(v.ToString()); foreach (var filter in context.Configuration.VersionFilters) { if (filter.Exclude(v, out var reason)) { - Logger.WriteInfo(reason); + log.Info(reason); return false; } } @@ -58,7 +60,7 @@ public BaseVersion GetBaseVersion(GitVersionContext context) var oldest = matchingVersionsOnceIncremented.Aggregate((v1, v2) => v1.Version.BaseVersionSource.Committer.When < v2.Version.BaseVersionSource.Committer.When ? v1 : v2); baseVersionWithOldestSource = oldest.Version; maxVersion = oldest; - Logger.WriteInfo($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource.Source})"); + log.Info($"Found multiple base versions which will produce the same SemVer ({maxVersion.IncrementedVersion}), taking oldest source for commit counting ({baseVersionWithOldestSource.Source})"); } else { @@ -77,7 +79,7 @@ public BaseVersion GetBaseVersion(GitVersionContext context) context, maxVersion.Version.Source, maxVersion.Version.ShouldIncrement, maxVersion.Version.SemanticVersion, baseVersionWithOldestSource.BaseVersionSource, maxVersion.Version.BranchNameOverride); - Logger.WriteInfo($"Base version used: {calculatedBase}"); + log.Info($"Base version used: {calculatedBase}"); return calculatedBase; } diff --git a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs index 69d57997d5..066c18fb95 100644 --- a/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs +++ b/src/GitVersionCore/VersionCalculation/BaseVersionCalculators/MergeMessageBaseVersionStrategy.cs @@ -3,6 +3,7 @@ using System.Text.RegularExpressions; using LibGit2Sharp; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion.VersionCalculation.BaseVersionCalculators { @@ -24,7 +25,7 @@ public override IEnumerable GetVersions(GitVersionContext context) mergeMessage.Version != null && context.FullConfiguration.IsReleaseBranch(TrimRemote(mergeMessage.MergedBranch))) { - Logger.WriteInfo($"Found commit [{context.CurrentCommit.Sha}] matching merge message format: {mergeMessage.FormatName}"); + context.Log.Info($"Found commit [{context.CurrentCommit.Sha}] matching merge message format: {mergeMessage.FormatName}"); var shouldIncrement = !context.Configuration.PreventIncrementForMergedBranchVersion; return new[] { diff --git a/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs new file mode 100644 index 0000000000..92a66e235b --- /dev/null +++ b/src/GitVersionCore/VersionCalculation/IMainlineVersionCalculator.cs @@ -0,0 +1,9 @@ +using GitVersion.VersionCalculation.BaseVersionCalculators; + +namespace GitVersion.VersionCalculation +{ + internal interface IMainlineVersionCalculator + { + SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersionContext context); + } +} \ No newline at end of file diff --git a/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs index 95f8a262d7..e9e55b3bab 100644 --- a/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/MainlineVersionCalculator.cs @@ -6,16 +6,19 @@ using System.Text.RegularExpressions; using GitVersion.Configuration; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion.VersionCalculation { - class MainlineVersionCalculator + class MainlineVersionCalculator : IMainlineVersionCalculator { IMetaDataCalculator metaDataCalculator; + private readonly ILog log; - public MainlineVersionCalculator(IMetaDataCalculator metaDataCalculator) + public MainlineVersionCalculator(IMetaDataCalculator metaDataCalculator, ILog log) { this.metaDataCalculator = metaDataCalculator; + this.log = log; } public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersionContext context) @@ -25,7 +28,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersi throw new NotSupportedException("Mainline development mode doesn't yet support pre-release tags on master"); } - using (Logger.IndentLog("Using mainline development mode to calculate current version")) + using (log.IndentLog("Using mainline development mode to calculate current version")) { var mainlineVersion = baseVersion.SemanticVersion; @@ -43,7 +46,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersi if (!context.CurrentBranch.IsSameBranch(mainline)) { mergeBase = FindMergeBaseBeforeForwardMerge(context, baseVersion.BaseVersionSource, mainline, out mainlineTip); - Logger.WriteInfo($"Current branch ({context.CurrentBranch.FriendlyName}) was branch from {mergeBase}"); + log.Info($"Current branch ({context.CurrentBranch.FriendlyName}) was branch from {mergeBase}"); } var mainlineCommitLog = context.Repository.Commits.QueryBy(new CommitFilter @@ -74,7 +77,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersi if (context.CurrentBranch.FriendlyName != "master") { var branchIncrement = FindMessageIncrement(context, null, context.CurrentCommit, mergeBase, mainlineCommitLog); - Logger.WriteInfo($"Performing {branchIncrement} increment for current branch "); + log.Info($"Performing {branchIncrement} increment for current branch "); mainlineVersion = mainlineVersion.IncrementVersion(branchIncrement); } @@ -83,7 +86,7 @@ public SemanticVersion FindMainlineModeVersion(BaseVersion baseVersion, GitVersi } } - SemanticVersion AggregateMergeCommitIncrement(GitVersionContext context, Commit commit, List directCommits, SemanticVersion mainlineVersion, Branch mainline) + private SemanticVersion AggregateMergeCommitIncrement(GitVersionContext context, Commit commit, List directCommits, SemanticVersion mainlineVersion, Branch mainline) { // Merge commit, process all merged commits as a batch var mergeCommit = commit; @@ -98,11 +101,11 @@ SemanticVersion AggregateMergeCommitIncrement(GitVersionContext context, Commit // Finally increment for the branch mainlineVersion = mainlineVersion.IncrementVersion(findMessageIncrement); - Logger.WriteInfo($"Merge commit {mergeCommit.Sha} incremented base versions {findMessageIncrement}, now {mainlineVersion}"); + log.Info($"Merge commit {mergeCommit.Sha} incremented base versions {findMessageIncrement}, now {mainlineVersion}"); return mainlineVersion; } - static Branch GetMainline(GitVersionContext context, Commit baseVersionSource) + private Branch GetMainline(GitVersionContext context, Commit baseVersionSource) { var mainlineBranchConfigs = context.FullConfiguration.Branches.Where(b => b.Value.IsMainline == true).ToList(); var mainlineBranches = context.Repository.Branches @@ -120,7 +123,7 @@ static Branch GetMainline(GitVersionContext context, Commit baseVersionSource) .ToDictionary(b => b.Key, b => b.ToList()); var allMainlines = mainlineBranches.Values.SelectMany(branches => branches.Select(b => b.FriendlyName)); - Logger.WriteInfo("Found possible mainline branches: " + string.Join(", ", allMainlines)); + log.Info("Found possible mainline branches: " + string.Join(", ", allMainlines)); // Find closest mainline branch var firstMatchingCommit = context.CurrentBranch.Commits.First(c => mainlineBranches.ContainsKey(c.Sha)); @@ -129,14 +132,14 @@ static Branch GetMainline(GitVersionContext context, Commit baseVersionSource) if (possibleMainlineBranches.Count == 1) { var mainlineBranch = possibleMainlineBranches[0]; - Logger.WriteInfo("Mainline for current branch is " + mainlineBranch.FriendlyName); + log.Info("Mainline for current branch is " + mainlineBranch.FriendlyName); return mainlineBranch; } // prefer current branch, if it is a mainline branch if (possibleMainlineBranches.Any(context.CurrentBranch.IsSameBranch)) { - Logger.WriteInfo($"Choosing {context.CurrentBranch.FriendlyName} as mainline because it is the current branch"); + log.Info($"Choosing {context.CurrentBranch.FriendlyName} as mainline because it is the current branch"); return context.CurrentBranch; } @@ -160,13 +163,13 @@ static Branch GetMainline(GitVersionContext context, Commit baseVersionSource) "Choosing {0} as mainline because {1}'s merge base was a direct commit to {0}", firstMatchingCommitBranch.FriendlyName, context.CurrentBranch.FriendlyName); - Logger.WriteInfo(message); + log.Info(message); return firstMatchingCommitBranch; } var chosenMainline = possibleMainlineBranches[0]; - Logger.WriteInfo($"Multiple mainlines ({string.Join(", ", possibleMainlineBranches.Select(b => b.FriendlyName))}) have the same merge base for the current branch, choosing {chosenMainline.FriendlyName} because we found that branch first..."); + log.Info($"Multiple mainlines ({string.Join(", ", possibleMainlineBranches.Select(b => b.FriendlyName))}) have the same merge base for the current branch, choosing {chosenMainline.FriendlyName} because we found that branch first..."); return chosenMainline; } @@ -180,14 +183,14 @@ static Branch GetMainline(GitVersionContext context, Commit baseVersionSource) /// /// This method gets the most recent commit on mainline that should be considered for versioning the current branch. /// - private static Commit GetEffectiveMainlineTip(IEnumerable mainlineCommitLog, Commit mergeBase, Commit mainlineTip) + private Commit GetEffectiveMainlineTip(IEnumerable mainlineCommitLog, Commit mergeBase, Commit mainlineTip) { // find the commit that merged mergeBase into mainline foreach (var commit in mainlineCommitLog) { if (commit == mergeBase || commit.Parents.Contains(mergeBase)) { - Logger.WriteInfo($"Found branch merge point; choosing {commit} as effective mainline tip"); + log.Info($"Found branch merge point; choosing {commit} as effective mainline tip"); return commit; } } @@ -203,7 +206,7 @@ private static Commit GetEffectiveMainlineTip(IEnumerable mainlineCommit /// The mainline branch. /// The commit on mainline at which the returned merge base was fully integrated. /// The best possible merge base between the current commit and that is not the child of a forward merge. - private static Commit FindMergeBaseBeforeForwardMerge(GitVersionContext context, Commit baseVersionSource, Branch mainline, out Commit mainlineTip) + private Commit FindMergeBaseBeforeForwardMerge(GitVersionContext context, Commit baseVersionSource, Branch mainline, out Commit mainlineTip) { var mergeBase = context.Repository.ObjectDatabase.FindMergeBase(context.CurrentCommit, mainline.Tip); var mainlineCommitLog = context.Repository.Commits @@ -225,7 +228,7 @@ private static Commit FindMergeBaseBeforeForwardMerge(GitVersionContext context, var mainlineTipPrevious = mainlineTip.Parents.First(); var message = $"Detected forward merge at {mainlineTip}; rewinding mainline to previous commit {mainlineTipPrevious}"; - Logger.WriteInfo(message); + log.Info(message); // re-do mergeBase detection before the forward merge mergeBase = context.Repository.ObjectDatabase.FindMergeBase(context.CurrentCommit, mainlineTipPrevious); @@ -235,7 +238,7 @@ private static Commit FindMergeBaseBeforeForwardMerge(GitVersionContext context, return mergeBase; } - private static SemanticVersion IncrementForEachCommit(GitVersionContext context, List directCommits, SemanticVersion mainlineVersion, Branch mainline) + private SemanticVersion IncrementForEachCommit(GitVersionContext context, List directCommits, SemanticVersion mainlineVersion, Branch mainline) { foreach (var directCommit in directCommits) { @@ -244,7 +247,7 @@ private static SemanticVersion IncrementForEachCommit(GitVersionContext context, directCommit }) ?? IncrementStrategyFinder.FindDefaultIncrementForBranch(context, mainline.FriendlyName); mainlineVersion = mainlineVersion.IncrementVersion(directCommitIncrement); - Logger.WriteInfo($"Direct commit on master {directCommit.Sha} incremented base versions {directCommitIncrement}, now {mainlineVersion}"); + log.Info($"Direct commit on master {directCommit.Sha} incremented base versions {directCommitIncrement}, now {mainlineVersion}"); } return mainlineVersion; } @@ -273,7 +276,7 @@ private static VersionField TryFindIncrementFromMergeMessage(Commit mergeCommit, if (mergeMessage.MergedBranch != null) { var config = context.FullConfiguration.GetConfigForBranch(mergeMessage.MergedBranch); - if (config != null && config.Increment.HasValue && config.Increment != IncrementStrategy.Inherit) + if (config?.Increment != null && config.Increment != IncrementStrategy.Inherit) { return config.Increment.Value.ToVersionField(); } @@ -284,7 +287,7 @@ private static VersionField TryFindIncrementFromMergeMessage(Commit mergeCommit, return IncrementStrategyFinder.FindDefaultIncrementForBranch(context); } - private Commit GetMergedHead(Commit mergeCommit) + private static Commit GetMergedHead(Commit mergeCommit) { var parents = mergeCommit.Parents.Skip(1).ToList(); if (parents.Count > 1) diff --git a/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs b/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs index e9eace936e..e7e8d89053 100644 --- a/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/MetaDataCalculator.cs @@ -1,6 +1,7 @@ using System.Linq; using LibGit2Sharp; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion.VersionCalculation { @@ -17,7 +18,7 @@ public SemanticVersionBuildMetaData Create(Commit baseVersionSource, GitVersionC var commitLog = context.Repository.Commits.QueryBy(qf); var commitsSinceTag = commitLog.Count(); - Logger.WriteInfo($"{commitsSinceTag} commits found between {baseVersionSource.Sha} and {context.CurrentCommit.Sha}"); + context.Log.Info($"{commitsSinceTag} commits found between {baseVersionSource.Sha} and {context.CurrentCommit.Sha}"); var shortSha = context.Repository.ObjectDatabase.ShortenObjectId(context.CurrentCommit); return new SemanticVersionBuildMetaData( diff --git a/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs b/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs index ca8ddd974e..459024ba11 100644 --- a/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs +++ b/src/GitVersionCore/VersionCalculation/NextVersionCalculator.cs @@ -4,19 +4,22 @@ using GitVersion.VersioningModes; using GitVersion.Configuration; using GitVersion.Helpers; +using GitVersion.Logging; namespace GitVersion.VersionCalculation { public class NextVersionCalculator { + private readonly ILog log; IBaseVersionCalculator baseVersionFinder; IMetaDataCalculator metaDataCalculator; - public NextVersionCalculator(IBaseVersionCalculator baseVersionCalculator = null, IMetaDataCalculator metaDataCalculator = null) + public NextVersionCalculator(ILog log, IBaseVersionCalculator baseVersionCalculator = null, IMetaDataCalculator metaDataCalculator = null) { + this.log = log; this.metaDataCalculator = metaDataCalculator ?? new MetaDataCalculator(); baseVersionFinder = baseVersionCalculator ?? - new BaseVersionCalculator( + new BaseVersionCalculator(log, new FallbackBaseVersionStrategy(), new ConfigNextVersionBaseVersionStrategy(), new TaggedCommitVersionStrategy(), @@ -46,7 +49,7 @@ public SemanticVersion FindVersion(GitVersionContext context) SemanticVersion semver; if (context.Configuration.VersioningMode == VersioningMode.Mainline) { - var mainlineMode = new MainlineVersionCalculator(metaDataCalculator); + var mainlineMode = new MainlineVersionCalculator(metaDataCalculator, log); semver = mainlineMode.FindMainlineModeVersion(baseVersion, context); } else @@ -73,7 +76,7 @@ public SemanticVersion FindVersion(GitVersionContext context) return taggedSemanticVersion ?? semver; } - private static SemanticVersion PerformIncrement(GitVersionContext context, BaseVersion baseVersion) + private SemanticVersion PerformIncrement(GitVersionContext context, BaseVersion baseVersion) { var semver = baseVersion.SemanticVersion; var increment = IncrementStrategyFinder.DetermineIncrementedField(context, baseVersion); @@ -81,7 +84,7 @@ private static SemanticVersion PerformIncrement(GitVersionContext context, BaseV { semver = semver.IncrementVersion(increment.Value); } - else Logger.WriteInfo("Skipping version increment"); + else log.Info("Skipping version increment"); return semver; } @@ -110,7 +113,7 @@ void UpdatePreReleaseTag(GitVersionContext context, SemanticVersion semanticVers semanticVersion.PreReleaseTag = new SemanticVersionPreReleaseTag(tagToUse, number); } - public static string GetBranchSpecificTag(EffectiveConfiguration configuration, string branchFriendlyName, string branchNameOverride) + public string GetBranchSpecificTag(EffectiveConfiguration configuration, string branchFriendlyName, string branchNameOverride) { var tagToUse = configuration.Tag; if (tagToUse == "useBranchName") @@ -119,7 +122,7 @@ public static string GetBranchSpecificTag(EffectiveConfiguration configuration, } if (tagToUse.Contains("{BranchName}")) { - Logger.WriteInfo("Using branch name to calculate version tag"); + log.Info("Using branch name to calculate version tag"); var branchName = branchNameOverride ?? branchFriendlyName; if (!string.IsNullOrWhiteSpace(configuration.BranchPrefixToTrim)) diff --git a/src/GitVersionExe.Tests/ArgumentParserTests.cs b/src/GitVersionExe.Tests/ArgumentParserTests.cs index d2b98e454b..65eb830a50 100644 --- a/src/GitVersionExe.Tests/ArgumentParserTests.cs +++ b/src/GitVersionExe.Tests/ArgumentParserTests.cs @@ -1,10 +1,9 @@ using System; -using System.Collections.Generic; using GitVersion; using NUnit.Framework; using Shouldly; using GitVersion.Exceptions; -using GitVersion.Helpers; +using GitVersion.Logging; using GitVersion.OutputFormatters; namespace GitVersionExe.Tests @@ -12,10 +11,18 @@ namespace GitVersionExe.Tests [TestFixture] public class ArgumentParserTests { + private IArgumentParser argumentParser; + + [SetUp] + public void SetUp() + { + argumentParser = new ArgumentParser(); + } + [Test] public void Empty_means_use_current_directory() { - var arguments = ArgumentParser.ParseArguments(""); + var arguments = argumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); @@ -24,7 +31,7 @@ public void Empty_means_use_current_directory() [Test] public void Single_means_use_as_target_directory() { - var arguments = ArgumentParser.ParseArguments("path"); + var arguments = argumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); @@ -33,7 +40,7 @@ public void Single_means_use_as_target_directory() [Test] public void No_path_and_logfile_should_use_current_directory_TargetDirectory() { - var arguments = ArgumentParser.ParseArguments("-l logFilePath"); + var arguments = argumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); @@ -42,7 +49,7 @@ public void No_path_and_logfile_should_use_current_directory_TargetDirectory() [Test] public void H_means_IsHelp() { - var arguments = ArgumentParser.ParseArguments("-h"); + var arguments = argumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); @@ -51,14 +58,14 @@ public void H_means_IsHelp() [Test] public void Exec() { - var arguments = ArgumentParser.ParseArguments("-exec rake"); + var arguments = argumentParser.ParseArguments("-exec rake"); arguments.Exec.ShouldBe("rake"); } [Test] public void Exec_with_args() { - var arguments = ArgumentParser.ParseArguments(new List + var arguments = argumentParser.ParseArguments(new [] { "-exec", "rake", @@ -72,14 +79,14 @@ public void Exec_with_args() [Test] public void Msbuild() { - var arguments = ArgumentParser.ParseArguments("-proj msbuild.proj"); + var arguments = argumentParser.ParseArguments("-proj msbuild.proj"); arguments.Proj.ShouldBe("msbuild.proj"); } [Test] public void Msbuild_with_args() { - var arguments = ArgumentParser.ParseArguments(new List + var arguments = argumentParser.ParseArguments(new [] { "-proj", "msbuild.proj", @@ -93,7 +100,7 @@ public void Msbuild_with_args() [Test] public void Execwith_targetdirectory() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -exec rake"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -exec rake"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Exec.ShouldBe("rake"); } @@ -101,7 +108,7 @@ public void Execwith_targetdirectory() [Test] public void TargetDirectory_and_LogFilePath_can_be_parsed() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); @@ -110,7 +117,7 @@ public void TargetDirectory_and_LogFilePath_can_be_parsed() [Test] public void Username_and_Password_can_be_parsed() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); @@ -120,42 +127,42 @@ public void Username_and_Password_can_be_parsed() [Test] public void Unknown_output_should_throw() { - var exception = Assert.Throws(() => ArgumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); + 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() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_json_can_be_parsed() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output json"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_buildserver_can_be_parsed() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void MultipleArgsAndFlag() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void Url_and_BranchName_can_be_parsed() { - var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); + var arguments = argumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); @@ -165,7 +172,7 @@ public void Url_and_BranchName_can_be_parsed() [Test] public void Wrong_number_of_arguments_should_throw() { - var exception = Assert.Throws(() => ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); + var exception = Assert.Throws(() => argumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } @@ -173,7 +180,7 @@ public void Wrong_number_of_arguments_should_throw() [TestCase("/invalid-argument")] public void Unknown_arguments_should_throw(string arguments) { - var exception = Assert.Throws(() => ArgumentParser.ParseArguments(arguments)); + var exception = Assert.Throws(() => argumentParser.ParseArguments(arguments)); exception.Message.ShouldStartWith("Could not parse command line parameter"); } @@ -187,7 +194,7 @@ public void Unknown_arguments_should_throw(string arguments) [TestCase("-updateAssemblyInfo Assembly.cs Assembly.cs -ensureassemblyinfo")] public void Update_assembly_info_true(string command) { - var arguments = ArgumentParser.ParseArguments(command); + var arguments = argumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } @@ -195,21 +202,21 @@ public void Update_assembly_info_true(string command) [TestCase("-updateAssemblyInfo 0")] public void Update_assembly_info_false(string command) { - var arguments = ArgumentParser.ParseArguments(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) { - var exception = Assert.Throws(() => ArgumentParser.ParseArguments(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() { - var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs"); + var arguments = argumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldContain("CommonAssemblyInfo.cs"); } @@ -217,7 +224,7 @@ public void Update_assembly_info_with_filename() [Test] public void Update_assembly_info_with_multiple_filenames() { - var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); + var arguments = argumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs VersionAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.Count.ShouldBe(2); arguments.UpdateAssemblyInfoFileName.ShouldContain("CommonAssemblyInfo.cs"); @@ -227,7 +234,7 @@ public void Update_assembly_info_with_multiple_filenames() [Test] public void Overrideconfig_with_no_options() { - var arguments = ArgumentParser.ParseArguments("/overrideconfig"); + var arguments = argumentParser.ParseArguments("/overrideconfig"); arguments.HasOverrideConfig.ShouldBe(false); arguments.OverrideConfig.ShouldNotBeNull(); } @@ -235,7 +242,7 @@ public void Overrideconfig_with_no_options() [Test] public void Overrideconfig_with_single_tagprefix_option() { - var arguments = ArgumentParser.ParseArguments("/overrideconfig tag-prefix=sample"); + var arguments = argumentParser.ParseArguments("/overrideconfig tag-prefix=sample"); arguments.HasOverrideConfig.ShouldBe(true); arguments.OverrideConfig.TagPrefix.ShouldBe("sample"); } @@ -244,21 +251,21 @@ public void Overrideconfig_with_single_tagprefix_option() [TestCase("tag-prefix=sample;param2=other")] public void Overrideconfig_with_several_options(string options) { - var exception = Assert.Throws(() => ArgumentParser.ParseArguments($"/overrideconfig {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) { - var exception = Assert.Throws(() => ArgumentParser.ParseArguments($"/overrideconfig {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() { - var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); + var arguments = argumentParser.ParseArguments("-updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldContain("..\\..\\CommonAssemblyInfo.cs"); } @@ -266,56 +273,56 @@ public void Update_assembly_info_with_relative_filename() [Test] public void Ensure_assembly_info_true_when_found() { - var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo"); + var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void Ensure_assembly_info_true() { - var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo true"); + var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo true"); arguments.EnsureAssemblyInfo.ShouldBe(true); } [Test] public void Ensure_assembly_info_false() { - var arguments = ArgumentParser.ParseArguments("-ensureAssemblyInfo false"); + var arguments = argumentParser.ParseArguments("-ensureAssemblyInfo false"); arguments.EnsureAssemblyInfo.ShouldBe(false); } [Test] public void DynamicRepoLocation() { - var arguments = ArgumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); + var arguments = argumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); arguments.DynamicRepositoryLocation.ShouldBe("c:\\foo\\"); } [Test] public void Can_log_to_console() { - var arguments = ArgumentParser.ParseArguments("-l console -proj foo.sln"); + var arguments = argumentParser.ParseArguments("-l console -proj foo.sln"); arguments.LogFilePath.ShouldBe("console"); } [Test] public void Nofetch_true_when_defined() { - var arguments = ArgumentParser.ParseArguments("-nofetch"); + var arguments = argumentParser.ParseArguments("-nofetch"); arguments.NoFetch.ShouldBe(true); } [Test] public void Nonormilize_true_when_defined() { - var arguments = ArgumentParser.ParseArguments("-nonormalize"); + var arguments = argumentParser.ParseArguments("-nonormalize"); arguments.NoNormalize.ShouldBe(true); } [Test] public void Other_arguments_can_be_parsed_before_nofetch() { - var arguments = ArgumentParser.ParseArguments("targetpath -nofetch "); + var arguments = argumentParser.ParseArguments("targetpath -nofetch "); arguments.TargetPath.ShouldBe("targetpath"); arguments.NoFetch.ShouldBe(true); } @@ -323,7 +330,7 @@ public void Other_arguments_can_be_parsed_before_nofetch() [Test] public void Other_arguments_can_be_parsed_after_nofetch() { - var arguments = ArgumentParser.ParseArguments("-nofetch -proj foo.sln"); + var arguments = argumentParser.ParseArguments("-nofetch -proj foo.sln"); arguments.NoFetch.ShouldBe(true); arguments.Proj.ShouldBe("foo.sln"); } @@ -331,14 +338,14 @@ public void Other_arguments_can_be_parsed_after_nofetch() [Test] public void Log_path_can_contain_forward_slash() { - var arguments = ArgumentParser.ParseArguments("-l /some/path"); + var arguments = argumentParser.ParseArguments("-l /some/path"); arguments.LogFilePath.ShouldBe("/some/path"); } [Test] public void Boolean_argument_handling() { - var arguments = ArgumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); + var arguments = argumentParser.ParseArguments("/nofetch /updateassemblyinfo true"); arguments.NoFetch.ShouldBe(true); arguments.UpdateAssemblyInfo.ShouldBe(true); } @@ -346,26 +353,25 @@ public void Boolean_argument_handling() [Test] public void Nocache_true_when_defined() { - var arguments = ArgumentParser.ParseArguments("-nocache"); + var arguments = argumentParser.ParseArguments("-nocache"); arguments.NoCache.ShouldBe(true); } - [TestCase("-verbosity x", true, VerbosityLevel.None)] - [TestCase("-verbosity none", false, VerbosityLevel.None)] - [TestCase("-verbosity info", false, VerbosityLevel.Info)] - [TestCase("-verbosity debug", false, VerbosityLevel.Debug)] - [TestCase("-verbosity INFO", false, VerbosityLevel.Info)] - [TestCase("-verbosity warn", false, VerbosityLevel.Warn)] - [TestCase("-verbosity error", false, VerbosityLevel.Error)] - public void Check_verbosity_parsing(string command, bool shouldThrow, VerbosityLevel expectedVerbosity) + [TestCase("-verbosity x", true, Verbosity.Normal)] + [TestCase("-verbosity diagnostic", false, Verbosity.Diagnostic)] + [TestCase("-verbosity Minimal", false, Verbosity.Minimal)] + [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) { if (shouldThrow) { - Assert.Throws(() => ArgumentParser.ParseArguments(command)); + Assert.Throws(() => argumentParser.ParseArguments(command)); } else { - var arguments = ArgumentParser.ParseArguments(command); + var arguments = argumentParser.ParseArguments(command); arguments.Verbosity.ShouldBe(expectedVerbosity); } } diff --git a/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs b/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs index 61b2a3fd05..1ba112fe4f 100644 --- a/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs +++ b/src/GitVersionExe.Tests/ExecCmdLineArgumentTest.cs @@ -31,7 +31,7 @@ public void RunExecViaCommandLine() "; File.WriteAllText(buildFile, buildFileContent); - var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, SpecifiedArgumentRunner.BuildTool, "RunExecViaCommandLine.csproj /target:OutputResults"); + var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, ExecCommand.BuildTool, "RunExecViaCommandLine.csproj /target:OutputResults"); result.ExitCode.ShouldBe(0, result.Log); result.Log.ShouldContain("GitVersion_FullSemVer: 1.2.4+1"); @@ -59,7 +59,7 @@ public void LogPathContainsForwardSlash() fixture.MakeATaggedCommit("1.2.3"); fixture.MakeACommit(); - var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: @" /l ""/some/path""", logToFile: false); + var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: @" /l ""/tmp/path""", logToFile: false); result.ExitCode.ShouldBe(0); result.Output.ShouldContain(@"""MajorMinorPatch"":""1.2.4"""); @@ -68,8 +68,8 @@ public void LogPathContainsForwardSlash() [Theory] [TestCase("", "INFO [")] - [TestCase("-verbosity Info", "INFO [")] - [TestCase("-verbosity Error", "")] + [TestCase("-verbosity NORMAL", "INFO [")] + [TestCase("-verbosity quiet", "")] public void CheckBuildServerVerbosityConsole(string verbosityArg, string expectedOutput) { using (var fixture = new EmptyRepositoryFixture()) @@ -77,7 +77,7 @@ public void CheckBuildServerVerbosityConsole(string verbosityArg, string expecte fixture.MakeATaggedCommit("1.2.3"); fixture.MakeACommit(); - var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: $@" {verbosityArg} -output buildserver /l ""/some/path""", logToFile: false); + var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: $@" {verbosityArg} -output buildserver /l ""/tmp/path""", logToFile: false); result.ExitCode.ShouldBe(0); result.Output.ShouldContain(expectedOutput); diff --git a/src/GitVersionExe.Tests/GitVersionHelper.cs b/src/GitVersionExe.Tests/GitVersionHelper.cs index 9f7564e508..1b4a46f930 100644 --- a/src/GitVersionExe.Tests/GitVersionHelper.cs +++ b/src/GitVersionExe.Tests/GitVersionHelper.cs @@ -41,7 +41,7 @@ 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(VsoAgent.EnvironmentVariableName, null), + new KeyValuePair(AzurePipelines.EnvironmentVariableName, null), }; var exitCode = -1; diff --git a/src/GitVersionExe.Tests/HelpWriterTests.cs b/src/GitVersionExe.Tests/HelpWriterTests.cs index ba2d65bb59..4ca74e3424 100644 --- a/src/GitVersionExe.Tests/HelpWriterTests.cs +++ b/src/GitVersionExe.Tests/HelpWriterTests.cs @@ -8,6 +8,14 @@ namespace GitVersionExe.Tests { public class HelpWriterTests { + private IHelpWriter helpWriter; + + public HelpWriterTests() + { + var versionWriter = new VersionWriter(); + helpWriter = new HelpWriter(versionWriter); + } + [Test] public void AllArgsAreInHelp() { @@ -20,16 +28,17 @@ public void AllArgsAreInHelp() { "DynamicRepositoryLocation" , "/dynamicRepoLocation" }, { "IsHelp", "/?" }, { "IsVersion", "/version" }, - { "UpdateWixVersionFile", "/updatewixversionfile" } + { "UpdateWixVersionFile", "/updatewixversionfile" }, + { "ConfigFile", "/config" }, }; string helpText = null; - HelpWriter.WriteTo(s => helpText = s); + helpWriter.WriteTo(s => helpText = s); typeof(Arguments).GetFields() .Select(p => p.Name) .Where(p => IsNotInHelp(lookup, p, helpText)) - .Except(new[] { "Authentication", "CommitId" }) + .Except(new[] { "Authentication", "CommitId", "HasOverrideConfig" }) .ShouldBeEmpty(); } @@ -41,4 +50,4 @@ static bool IsNotInHelp(Dictionary lookup, string propertyName, return !helpText.Contains("/" + propertyName.ToLower()); } } -} \ No newline at end of file +} diff --git a/src/GitVersionExe.Tests/Helpers/TestStream.cs b/src/GitVersionExe.Tests/Helpers/TestStream.cs index 27f565016e..c3a6441d68 100644 --- a/src/GitVersionExe.Tests/Helpers/TestStream.cs +++ b/src/GitVersionExe.Tests/Helpers/TestStream.cs @@ -1,7 +1,4 @@ -using System; using System.IO; -using System.Threading; -using System.Threading.Tasks; namespace GitVersionExe.Tests.Helpers { @@ -50,21 +47,6 @@ public override void Write(byte[] buffer, int offset, int count) underlying.Write(buffer, offset, count); } - public override void WriteByte(byte value) - { - base.WriteByte(value); - } - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - return base.BeginWrite(buffer, offset, count, callback, state); - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return base.WriteAsync(buffer, offset, count, cancellationToken); - } - public override bool CanRead => underlying.CanRead; public override bool CanSeek => underlying.CanSeek; public override bool CanWrite => underlying.CanWrite; @@ -76,4 +58,4 @@ public override long Position set => underlying.Position = value; } } -} \ No newline at end of file +} diff --git a/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs b/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs index 617bfa75b2..4d29103111 100644 --- a/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs +++ b/src/GitVersionExe.Tests/MsBuildProjectArgTest.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using GitTools.Testing; using NUnit.Framework; using Shouldly; @@ -32,4 +32,4 @@ public void RunsMsBuildProvideViaCommandLineArg() } } } -} \ No newline at end of file +} diff --git a/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs b/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs index 18dc270e3d..ae6e89de6f 100644 --- a/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs +++ b/src/GitVersionExe.Tests/UpdateWixVersionFileTests.cs @@ -43,8 +43,7 @@ public void WixVersionFileVarCountTest() fixture.MakeATaggedCommit("1.2.3"); fixture.MakeACommit(); - var gitVersionExecutionResults = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: null); - var vars = gitVersionExecutionResults.OutputVariables; + GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: null); GitVersionHelper.ExecuteIn(fixture.RepositoryPath, arguments: " /updatewixversionfile"); diff --git a/src/GitVersionExe.Tests/VersionWriterTests.cs b/src/GitVersionExe.Tests/VersionWriterTests.cs index 010e7b7707..5bd56da6fc 100644 --- a/src/GitVersionExe.Tests/VersionWriterTests.cs +++ b/src/GitVersionExe.Tests/VersionWriterTests.cs @@ -10,13 +10,19 @@ namespace GitVersionExe.Tests [TestFixture] public class VersionWriterTests { + private IVersionWriter versionWriter; + + public VersionWriterTests() + { + this.versionWriter = new VersionWriter(); + } [Test] public void WriteVersion_ShouldWriteFileVersion_WithNoPrereleaseTag() { var asm = GenerateAssembly(new Version(1, 0, 0), ""); string version = null; - VersionWriter.WriteTo(asm, v => version = v); + versionWriter.WriteTo(asm, v => version = v); Assert.IsNotNull(asm); Assert.AreEqual("1.0.0", version); @@ -28,7 +34,7 @@ public void WriteVersion_ShouldWriteFileVersion_WithPrereleaseTag() var asm = GenerateAssembly(new Version(1, 0, 0), "-beta0004"); string version = null; - VersionWriter.WriteTo(asm, v => version = v); + versionWriter.WriteTo(asm, v => version = v); Assert.IsNotNull(asm); Assert.AreEqual("1.0.0-beta0004", version); diff --git a/src/GitVersionExe/ArgumentParser.cs b/src/GitVersionExe/ArgumentParser.cs index 0e29673d59..37dfe3da22 100644 --- a/src/GitVersionExe/ArgumentParser.cs +++ b/src/GitVersionExe/ArgumentParser.cs @@ -3,39 +3,32 @@ 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; namespace GitVersion { - public class ArgumentParser + public class ArgumentParser : IArgumentParser { - public static Arguments ParseArguments(string commandLineArguments) + public Arguments ParseArguments(string commandLineArguments) { var arguments = commandLineArguments .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) - .ToList(); + .ToArray(); return ParseArguments(arguments); } - static void EnsureArgumentValueCount(string[] values, int maxArguments = 1) + public Arguments ParseArguments(string[] commandLineArguments) { - if (values != null && values.Length > maxArguments) - { - throw new WarningException($"Could not parse command line parameter '{values[1]}'."); - } - } - - public static Arguments ParseArguments(List commandLineArguments) - { - if (commandLineArguments.Count == 0) + if (commandLineArguments.Length == 0) { return new Arguments { - TargetPath = Environment.CurrentDirectory + TargetPath = Environment.CurrentDirectory, }; } @@ -45,7 +38,7 @@ public static Arguments ParseArguments(List commandLineArguments) { return new Arguments { - IsHelp = true + IsHelp = true, }; } @@ -54,11 +47,12 @@ public static Arguments ParseArguments(List commandLineArguments) return new Arguments { TargetPath = Environment.CurrentDirectory, - Init = true + Init = true, }; } var arguments = new Arguments(); + var switchesAndValues = CollectSwitchesAndValuesFromArguments(commandLineArguments, out var firstArgumentIsSwitch); for (var i = 0; i < switchesAndValues.AllKeys.Length; i++) @@ -84,7 +78,7 @@ public static Arguments ParseArguments(List commandLineArguments) if (name.IsSwitch("config")) { EnsureArgumentValueCount(values); - arguments.ConfigFileLocator = new NamedConfigFileLocator(value); + arguments.ConfigFile = value; continue; } @@ -173,6 +167,7 @@ public static Arguments ParseArguments(List commandLineArguments) { arguments.Diag = true; } + continue; } @@ -251,6 +246,7 @@ public static Arguments ParseArguments(List commandLineArguments) { arguments.ShowConfig = true; } + continue; } @@ -296,6 +292,7 @@ public static Arguments ParseArguments(List commandLineArguments) { throw new WarningException("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"); } + continue; } @@ -345,10 +342,16 @@ public static Arguments ParseArguments(List commandLineArguments) if (name.IsSwitch("verbosity")) { - if (!Enum.TryParse(value, true, out arguments.Verbosity)) + // first try the old version + if (Enum.TryParse(value, true, out LogLevel logLevel)) + { + arguments.Verbosity = LogExtensions.GetVerbosityForLevel(logLevel); + } + else if (!Enum.TryParse(value, true, out arguments.Verbosity)) { throw new WarningException($"Could not parse Verbosity value '{value}'"); } + continue; } @@ -395,7 +398,15 @@ public static Arguments ParseArguments(List commandLineArguments) return arguments; } - static NameValueCollection CollectSwitchesAndValuesFromArguments(IList namedArguments, out bool firstArgumentIsSwitch) + private static void EnsureArgumentValueCount(string[] values, int maxArguments = 1) + { + if (values != null && values.Length > maxArguments) + { + throw new WarningException($"Could not parse command line parameter '{values[1]}'."); + } + } + + private static NameValueCollection CollectSwitchesAndValuesFromArguments(IList namedArguments, out bool firstArgumentIsSwitch) { firstArgumentIsSwitch = true; var switchesAndValues = new NameValueCollection(); diff --git a/src/GitVersionExe/SpecifiedArgumentRunner.cs b/src/GitVersionExe/ExecCommand.cs similarity index 83% rename from src/GitVersionExe/SpecifiedArgumentRunner.cs rename to src/GitVersionExe/ExecCommand.cs index fe1bb172b3..184a864f5d 100644 --- a/src/GitVersionExe/SpecifiedArgumentRunner.cs +++ b/src/GitVersionExe/ExecCommand.cs @@ -10,34 +10,19 @@ using GitVersion.Extensions; using GitVersion.Extensions.VersionAssemblyInfoResources; using GitVersion.Common; +using GitVersion.Configuration; +using GitVersion.Logging; namespace GitVersion { - internal class SpecifiedArgumentRunner + public class ExecCommand { private static readonly bool runningOnUnix = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static readonly string BuildTool = GetMsBuildToolPath(); - private static string GetMsBuildToolPath() - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe"; - } - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return "/usr/bin/msbuild"; - } - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - return "/usr/local/bin/msbuild"; - } - throw new Exception("MsBuild not found"); - } - - public static void Run(Arguments arguments, IFileSystem fileSystem, IEnvironment environment) + public void Execute(Arguments arguments, IFileSystem fileSystem, IEnvironment environment, ILog log, IConfigFileLocator configFileLocator) { - Logger.WriteInfo($"Running on {(runningOnUnix ? "Unix" : "Windows")}."); + log.Info($"Running on {(runningOnUnix ? "Unix" : "Windows")}."); var noFetch = arguments.NoFetch; var authentication = arguments.Authentication; @@ -50,15 +35,15 @@ public static void Run(Arguments arguments, IFileSystem fileSystem, IEnvironment var noCache = arguments.NoCache; var noNormalize = arguments.NoNormalize; - var executeCore = new ExecuteCore(fileSystem, environment, arguments.ConfigFileLocator); + var executeCore = new ExecuteCore(fileSystem, environment, log, configFileLocator); var variables = executeCore.ExecuteGitVersion(targetUrl, dynamicRepositoryLocation, authentication, targetBranch, noFetch, targetPath, commitId, overrideConfig, noCache, noNormalize); switch (arguments.Output) { case OutputType.BuildServer: { - BuildServerList.Init(environment); - foreach (var buildServer in BuildServerList.GetApplicableBuildServers()) + BuildServerList.Init(environment, log); + foreach (var buildServer in BuildServerList.GetApplicableBuildServers(log)) { buildServer.WriteIntegration(Console.WriteLine, variables); } @@ -88,21 +73,21 @@ public static void Run(Arguments arguments, IFileSystem fileSystem, IEnvironment if (arguments.UpdateWixVersionFile) { - using (var wixVersionFileUpdater = new WixVersionFileUpdater(targetPath, variables, fileSystem)) + using (var wixVersionFileUpdater = new WixVersionFileUpdater(targetPath, variables, fileSystem, log)) { wixVersionFileUpdater.Update(); } } - using (var assemblyInfoUpdater = new AssemblyInfoFileUpdater(arguments.UpdateAssemblyInfoFileName, targetPath, variables, fileSystem, arguments.EnsureAssemblyInfo)) + using (var assemblyInfoUpdater = new AssemblyInfoFileUpdater(arguments.UpdateAssemblyInfoFileName, targetPath, variables, fileSystem, log, arguments.EnsureAssemblyInfo)) { if (arguments.UpdateAssemblyInfo) { assemblyInfoUpdater.Update(); } - var execRun = RunExecCommandIfNeeded(arguments, targetPath, variables); - var msbuildRun = RunMsBuildIfNeeded(arguments, targetPath, variables); + var execRun = RunExecCommandIfNeeded(arguments, targetPath, variables, log); + var msbuildRun = RunMsBuildIfNeeded(arguments, targetPath, variables, log); if (!execRun && !msbuildRun) { @@ -118,13 +103,30 @@ public static void Run(Arguments arguments, IFileSystem fileSystem, IEnvironment } } - private static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) + private static string GetMsBuildToolPath() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe"; + } + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return "/usr/bin/msbuild"; + } + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return "/usr/local/bin/msbuild"; + } + throw new Exception("MsBuild not found"); + } + + private static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables, ILog log) { if (string.IsNullOrEmpty(args.Proj)) return false; - Logger.WriteInfo($"Launching build tool {BuildTool} \"{args.Proj}\" {args.ProjArgs}"); + log.Info($"Launching build tool {BuildTool} \"{args.Proj}\" {args.ProjArgs}"); var results = ProcessHelper.Run( - Logger.WriteInfo, Logger.WriteError, + m => log.Info(m), m => log.Error(m), null, BuildTool, $"\"{args.Proj}\" {args.ProjArgs}", workingDirectory, GetEnvironmentalVariables(variables)); @@ -134,13 +136,13 @@ private static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, return true; } - private static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) + private static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables, ILog log) { if (string.IsNullOrEmpty(args.Exec)) return false; - Logger.WriteInfo($"Launching {args.Exec} {args.ExecArgs}"); + log.Info($"Launching {args.Exec} {args.ExecArgs}"); var results = ProcessHelper.Run( - Logger.WriteInfo, Logger.WriteError, + m => log.Info(m), m => log.Error(m), null, args.Exec, args.ExecArgs, workingDirectory, GetEnvironmentalVariables(variables)); @@ -149,7 +151,8 @@ private static bool RunExecCommandIfNeeded(Arguments args, string workingDirecto return true; } - static KeyValuePair[] GetEnvironmentalVariables(VersionVariables variables) + + private static KeyValuePair[] GetEnvironmentalVariables(VersionVariables variables) { return variables .Select(v => new KeyValuePair("GitVersion_" + v.Key, v.Value)) diff --git a/src/GitVersionExe/GitVersionApplication.cs b/src/GitVersionExe/GitVersionApplication.cs new file mode 100644 index 0000000000..3ef845ca06 --- /dev/null +++ b/src/GitVersionExe/GitVersionApplication.cs @@ -0,0 +1,163 @@ +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; + +namespace GitVersion +{ + public class GitVersionApplication : IGitVersionApplication + { + private readonly IFileSystem fileSystem; + private readonly IEnvironment environment; + private readonly ILog log; + private readonly IConfigFileLocator configFileLocator; + private readonly IHelpWriter helpWriter; + private readonly IVersionWriter versionWriter; + + public GitVersionApplication(IFileSystem fileSystem, IEnvironment environment, ILog log, IConfigFileLocator configFileLocator) + { + this.fileSystem = fileSystem; + this.environment = environment; + this.log = log; + this.configFileLocator = configFileLocator; + + versionWriter = new VersionWriter(); + helpWriter = new HelpWriter(versionWriter); + } + + public int Run(Arguments arguments) + { + var exitCode = VerifyArgumentsAndRun(arguments); + + if (exitCode != 0) + { + // Dump log to console if we fail to complete successfully + Console.Write(log.ToString()); + } + + return exitCode; + } + + private int VerifyArgumentsAndRun(Arguments arguments) + { + try + { + if (arguments == null) + { + helpWriter.Write(); + return 1; + } + + if (arguments.IsVersion) + { + var assembly = Assembly.GetExecutingAssembly(); + versionWriter.Write(assembly); + return 0; + } + + if (arguments.IsHelp) + { + helpWriter.Write(); + return 0; + } + + if (arguments.Diag) + { + arguments.NoCache = true; + arguments.Output = OutputType.BuildServer; + } + + if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec)) + { + arguments.Output = OutputType.BuildServer; + } + + ConfigureLogging(arguments, log); + + if (arguments.Diag) + { + log.Info("Dumping commit graph: "); + LibGitExtensions.DumpGraph(arguments.TargetPath, mess => log.Info(mess), 100); + } + if (!Directory.Exists(arguments.TargetPath)) + { + log.Warning($"The working directory '{arguments.TargetPath}' does not exist."); + } + else + { + log.Info("Working directory: " + arguments.TargetPath); + } + + VerifyConfiguration(arguments); + + if (arguments.Init) + { + ConfigurationProvider.Init(arguments.TargetPath, fileSystem, new ConsoleAdapter(), log, configFileLocator); + return 0; + } + if (arguments.ShowConfig) + { + Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(arguments.TargetPath, configFileLocator)); + return 0; + } + + var execCommand = new ExecCommand(); + + execCommand.Execute(arguments, fileSystem, environment, log, configFileLocator); + } + catch (WarningException exception) + { + var error = $"An error occurred:\r\n{exception.Message}"; + log.Warning(error); + return 1; + } + catch (Exception exception) + { + var error = $"An unexpected error occurred:\r\n{exception}"; + log.Error(error); + + if (arguments == null) return 1; + + log.Info(string.Empty); + log.Info("Attempting to show the current git graph (please include in issue): "); + log.Info("Showing max of 100 commits"); + + try + { + LibGitExtensions.DumpGraph(arguments.TargetPath, mess => log.Info(mess), 100); + } + catch (Exception dumpGraphException) + { + log.Error("Couldn't dump the git graph due to the following error: " + dumpGraphException); + } + return 1; + } + + return 0; + } + + private void VerifyConfiguration(Arguments arguments) + { + var gitPreparer = new GitPreparer(log, arguments); + configFileLocator.Verify(gitPreparer); + } + + private static void ConfigureLogging(Arguments arguments, ILog log) + { + if (arguments.Output == OutputType.BuildServer || arguments.LogFilePath == "console" || arguments.Init) + { + log.AddLogAppender(new ConsoleAppender()); + } + + if (arguments.LogFilePath != null && arguments.LogFilePath != "console") + { + log.AddLogAppender(new FileAppender(arguments.LogFilePath)); + } + } + } +} diff --git a/src/GitVersionExe/HelpWriter.cs b/src/GitVersionExe/HelpWriter.cs index 313efaeb3b..6ea499ca54 100644 --- a/src/GitVersionExe/HelpWriter.cs +++ b/src/GitVersionExe/HelpWriter.cs @@ -3,19 +3,25 @@ namespace GitVersion { - class HelpWriter + public class HelpWriter : IHelpWriter { - public static void Write() + private readonly IVersionWriter versionWriter; + + public HelpWriter(IVersionWriter versionWriter) + { + this.versionWriter = versionWriter; + } + + public void Write() { WriteTo(Console.WriteLine); } - internal static void WriteTo(Action writeAction) + public void WriteTo(Action writeAction) { string version = string.Empty; Assembly assembly = Assembly.GetExecutingAssembly(); - VersionWriter.WriteTo(assembly, v => version = v); - + versionWriter.WriteTo(assembly, v => version = v); string message = "GitVersion " + version + @" Use convention to derive a SemVer product version from a GitFlow or GitHub based repository. @@ -76,8 +82,6 @@ All the GitVersion variables are written to 'GitVersion_WixVersion.wxi'. gitversion init Configuration utility for gitversion "; - - writeAction(message); } } diff --git a/src/GitVersionExe/IArgumentParser.cs b/src/GitVersionExe/IArgumentParser.cs new file mode 100644 index 0000000000..d557a9b3e0 --- /dev/null +++ b/src/GitVersionExe/IArgumentParser.cs @@ -0,0 +1,8 @@ +namespace GitVersion +{ + public interface IArgumentParser + { + Arguments ParseArguments(string commandLineArguments); + Arguments ParseArguments(string[] commandLineArguments); + } +} diff --git a/src/GitVersionExe/IGitVersionApplication.cs b/src/GitVersionExe/IGitVersionApplication.cs new file mode 100644 index 0000000000..7f1c37658f --- /dev/null +++ b/src/GitVersionExe/IGitVersionApplication.cs @@ -0,0 +1,7 @@ +namespace GitVersion +{ + public interface IGitVersionApplication + { + int Run(Arguments arguments); + } +} \ No newline at end of file diff --git a/src/GitVersionExe/IHelpWriter.cs b/src/GitVersionExe/IHelpWriter.cs new file mode 100644 index 0000000000..cea916e73e --- /dev/null +++ b/src/GitVersionExe/IHelpWriter.cs @@ -0,0 +1,10 @@ +using System; + +namespace GitVersion +{ + public interface IHelpWriter + { + void Write(); + void WriteTo(Action writeAction); + } +} diff --git a/src/GitVersionExe/IVersionWriter.cs b/src/GitVersionExe/IVersionWriter.cs new file mode 100644 index 0000000000..7c6ee50ef1 --- /dev/null +++ b/src/GitVersionExe/IVersionWriter.cs @@ -0,0 +1,11 @@ +using System; +using System.Reflection; + +namespace GitVersion +{ + public interface IVersionWriter + { + void Write(Assembly assembly); + void WriteTo(Assembly assembly, Action writeAction); + } +} diff --git a/src/GitVersionExe/Program.cs b/src/GitVersionExe/Program.cs index 4510cc3c97..c4ff18fe8a 100644 --- a/src/GitVersionExe/Program.cs +++ b/src/GitVersionExe/Program.cs @@ -1,215 +1,64 @@ -using GitVersion.Helpers; using System; -using System.Collections.Generic; using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using GitVersion.Configuration; -using GitVersion.Exceptions; -using GitVersion.OutputFormatters; using GitVersion.Common; +using GitVersion.Configuration; +using GitVersion.Logging; +using Console = System.Console; using Environment = GitVersion.Common.Environment; namespace GitVersion { - class Program + internal class Program { - static StringBuilder log = new StringBuilder(); - - static void Main() + private static void Main(string[] args) { - var exitCode = VerifyArgumentsAndRun(); - - if (Debugger.IsAttached) - { - Console.ReadKey(); - } - - if (exitCode != 0) - { - // Dump log to console if we fail to complete successfully - Console.Write(log.ToString()); - } + var arguments = ParseArguments(args); - System.Environment.Exit(exitCode); - } - - static int VerifyArgumentsAndRun() - { - Arguments arguments = null; - try + var exitCode = 1; + if (arguments != null) { var fileSystem = new FileSystem(); var environment = new Environment(); - var argumentsWithoutExeName = GetArgumentsWithoutExeName(); try { - arguments = ArgumentParser.ParseArguments(argumentsWithoutExeName); - } - catch (Exception exception) - { - Console.WriteLine("Failed to parse arguments: {0}", string.Join(" ", argumentsWithoutExeName)); - if (!string.IsNullOrWhiteSpace(exception.Message)) - { - Console.WriteLine(); - Console.WriteLine(exception.Message); - Console.WriteLine(); - } + var log = new Log { Verbosity = arguments.Verbosity }; - HelpWriter.Write(); - return 1; - } - - if (arguments.IsVersion) - { - var assembly = Assembly.GetExecutingAssembly(); - VersionWriter.Write(assembly); - return 0; - } - - if (arguments.IsHelp) - { - HelpWriter.Write(); - return 0; - } + var configFileLocator = string.IsNullOrWhiteSpace(arguments.ConfigFile) + ? (IConfigFileLocator) new DefaultConfigFileLocator(fileSystem, log) + : new NamedConfigFileLocator(arguments.ConfigFile, fileSystem, log); - if (arguments.Diag) - { - arguments.NoCache = true; - arguments.Output = OutputType.BuildServer; - } + var app = new GitVersionApplication(fileSystem, environment, log, configFileLocator); - ConfigureLogging(arguments); - if (arguments.Diag) - { - Logger.WriteInfo("Dumping commit graph: "); - LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100); - } - if (!Directory.Exists(arguments.TargetPath)) - { - Logger.WriteWarning($"The working directory '{arguments.TargetPath}' does not exist."); - } - else - { - Logger.WriteInfo("Working directory: " + arguments.TargetPath); - } - VerifyConfiguration(arguments, fileSystem); - - if (arguments.Init) - { - ConfigurationProvider.Init(arguments.TargetPath, fileSystem, new ConsoleAdapter(), arguments.ConfigFileLocator); - return 0; - } - if (arguments.ShowConfig) - { - Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(arguments.TargetPath, fileSystem, arguments.ConfigFileLocator)); - return 0; + exitCode = app.Run(arguments); } - - if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec)) + catch (Exception exception) { - arguments.Output = OutputType.BuildServer; + Console.Error.WriteLine(exception.Message); } - - SpecifiedArgumentRunner.Run(arguments, fileSystem, environment); - } - catch (WarningException exception) - { - var error = $"An error occurred:\r\n{exception.Message}"; - Logger.WriteWarning(error); - return 1; } - catch (Exception exception) - { - var error = $"An unexpected error occurred:\r\n{exception}"; - Logger.WriteError(error); - if (arguments != null) - { - Logger.WriteInfo(string.Empty); - Logger.WriteInfo("Attempting to show the current git graph (please include in issue): "); - Logger.WriteInfo("Showing max of 100 commits"); - - try - { - LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100); - } - catch (Exception dumpGraphException) - { - Logger.WriteError("Couldn't dump the git graph due to the following error: " + dumpGraphException); - } - } - return 1; + if (Debugger.IsAttached) + { + Console.ReadKey(); } - return 0; - } - - static void VerifyConfiguration(Arguments arguments, IFileSystem fileSystem) - { - var gitPreparer = new GitPreparer(arguments.TargetUrl, arguments.DynamicRepositoryLocation, arguments.Authentication, arguments.NoFetch, arguments.TargetPath); - arguments.ConfigFileLocator.Verify(gitPreparer, fileSystem); + System.Environment.Exit(exitCode); } - static void ConfigureLogging(Arguments arguments) + private static Arguments ParseArguments(string[] args) { - var writeActions = new List> - { - s => log.AppendLine(s) - }; - - if (arguments.Output == OutputType.BuildServer || arguments.LogFilePath == "console" || arguments.Init) + var argumentParser = new ArgumentParser(); + Arguments arguments = null; + try { - writeActions.Add(Console.WriteLine); + arguments = argumentParser.ParseArguments(args); } - - Exception exception = null; - if (arguments.LogFilePath != null && arguments.LogFilePath != "console") + catch (Exception exception) { - try - { - var logFileFullPath = Path.GetFullPath(arguments.LogFilePath); - var logFile = new FileInfo(logFileFullPath); - - // NOTE: logFile.Directory will be null if the path is i.e. C:\logfile.log. @asbjornu - logFile.Directory?.Create(); - - using (logFile.CreateText()) - { - } - - writeActions.Add(x => WriteLogEntry(arguments, x)); - } - catch (Exception ex) - { - exception = ex; - } + Console.Error.WriteLine(exception.Message); } - - Logger.SetLoggers( - s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Debug) a(s); }), - s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Info) a(s); }), - s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Warn) a(s); }), - s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Error) a(s); })); - - if (exception != null) - Logger.WriteError($"Failed to configure logging for '{arguments.LogFilePath}': {exception.Message}"); - } - - static void WriteLogEntry(Arguments arguments, string s) - { - var contents = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}\t\t{s}\r\n"; - File.AppendAllText(arguments.LogFilePath, contents); - } - - static List GetArgumentsWithoutExeName() - { - return System.Environment.GetCommandLineArgs() - .Skip(1) - .ToList(); + return arguments; } } } diff --git a/src/GitVersionExe/VersionWriter.cs b/src/GitVersionExe/VersionWriter.cs index 3f1af885f9..2679da64bc 100644 --- a/src/GitVersionExe/VersionWriter.cs +++ b/src/GitVersionExe/VersionWriter.cs @@ -4,14 +4,14 @@ namespace GitVersion { - class VersionWriter + public class VersionWriter : IVersionWriter { - public static void Write(Assembly assembly) + public void Write(Assembly assembly) { WriteTo(assembly, Console.WriteLine); } - public static void WriteTo(Assembly assembly, Action writeAction) + public void WriteTo(Assembly assembly, Action writeAction) { var version = GetAssemblyVersion(assembly); writeAction(version); diff --git a/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs b/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs index 6fd3989420..92e95431ec 100644 --- a/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs +++ b/src/GitVersionTask.MsBuild/LibGit2Sharp/LibGit2SharpLoader.cs @@ -1,7 +1,10 @@ // This code originally copied and adapted from https://raw.githubusercontent.com/dotnet/sourcelink/master/src/Microsoft.Build.Tasks.Git/TaskImplementation.cs +#if NET472 using System; using System.Collections.Generic; +#endif + using System.IO; using System.Reflection; @@ -9,7 +12,7 @@ namespace GitVersionTask.MsBuild.LibGit2Sharp { public class LibGit2SharpLoader { - private static string taskDirectory; + private static readonly string taskDirectory = Path.GetDirectoryName(typeof(LibGit2SharpLoader).Assembly.Location); public static LibGit2SharpLoader Instance { get; private set; } public Assembly Assembly { get; } @@ -18,7 +21,6 @@ public class LibGit2SharpLoader private LibGit2SharpLoader(string tasksAssembly) { - taskDirectory = Path.GetDirectoryName(typeof(LibGit2SharpLoader).Assembly.Location); #if NETFRAMEWORK nullVersion = new Version(0, 0, 0, 0); loaderLog = new List(); diff --git a/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs b/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs index 6a1855b281..beb7cda68f 100644 --- a/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs +++ b/src/GitVersionTask.Tests/GitVersionTaskDirectoryTests.cs @@ -1,6 +1,7 @@ using System; using System.IO; using GitVersion; +using GitVersion.Logging; using LibGit2Sharp; using NUnit.Framework; using GitVersionTask.Tests.Helpers; @@ -21,7 +22,7 @@ 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()); + executeCore = new ExecuteCore(new TestFileSystem(), new TestEnvironment(), new Log()); Assert.NotNull(gitDirectory); } diff --git a/src/GitVersionTask.Tests/Helpers/TestStream.cs b/src/GitVersionTask.Tests/Helpers/TestStream.cs index c8dd08742e..03b4e38c94 100644 --- a/src/GitVersionTask.Tests/Helpers/TestStream.cs +++ b/src/GitVersionTask.Tests/Helpers/TestStream.cs @@ -1,7 +1,4 @@ -using System; using System.IO; -using System.Threading; -using System.Threading.Tasks; namespace GitVersionTask.Tests.Helpers { @@ -50,21 +47,6 @@ public override void Write(byte[] buffer, int offset, int count) underlying.Write(buffer, offset, count); } - public override void WriteByte(byte value) - { - base.WriteByte(value); - } - - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - return base.BeginWrite(buffer, offset, count, callback, state); - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return base.WriteAsync(buffer, offset, count, cancellationToken); - } - public override bool CanRead => underlying.CanRead; public override bool CanSeek => underlying.CanSeek; public override bool CanWrite => underlying.CanWrite; @@ -76,4 +58,4 @@ public override long Position set => underlying.Position = value; } } -} \ No newline at end of file +} diff --git a/src/GitVersionTask.Tests/ModuleInitializer.cs b/src/GitVersionTask.Tests/ModuleInitializer.cs deleted file mode 100644 index bac1f7c928..0000000000 --- a/src/GitVersionTask.Tests/ModuleInitializer.cs +++ /dev/null @@ -1,23 +0,0 @@ -using GitVersion.Helpers; - -namespace GitVersionTask.Tests -{ - /// - /// Used by the ModuleInit. All code inside the Initialize method is ran as soon as the assembly is loaded. - /// - public static class ModuleInitializer - { - /// - /// Initializes the module. - /// - public static void Initialize() - { - Logger.SetLoggers( - s => System.Console.WriteLine(s), - s => System.Console.WriteLine(s), - s => System.Console.WriteLine(s), - s => System.Console.WriteLine(s)); - } - - } -} diff --git a/src/GitVersionTask.Tests/TestBase.cs b/src/GitVersionTask.Tests/TestBase.cs index b9166f272b..1b1911195f 100644 --- a/src/GitVersionTask.Tests/TestBase.cs +++ b/src/GitVersionTask.Tests/TestBase.cs @@ -1,12 +1,7 @@ -namespace GitVersionTask.Tests +namespace GitVersionTask.Tests { public class TestBase { - static TestBase() - { - ModuleInitializer.Initialize(); - } - } } diff --git a/src/GitVersionTask/GitVersionTasks.cs b/src/GitVersionTask/GitVersionTasks.cs index 3797c294f5..2b531db1f6 100644 --- a/src/GitVersionTask/GitVersionTasks.cs +++ b/src/GitVersionTask/GitVersionTasks.cs @@ -4,21 +4,32 @@ using GitVersion.BuildServers; using GitVersion.Configuration; using GitVersion.Exceptions; -using GitVersion.Helpers; using GitVersion.OutputFormatters; using GitVersion.OutputVariables; using GitVersionTask.MsBuild; using GitVersionTask.MsBuild.Tasks; -using Microsoft.Build.Framework; using GitVersion.Extensions.GitVersionInformationResources; using GitVersion.Extensions.VersionAssemblyInfoResources; using GitVersion.Common; +using GitVersion.Logging; using Environment = GitVersion.Common.Environment; namespace GitVersionTask { public static class GitVersionTasks { + private static readonly ILog log; + private static readonly IEnvironment environment; + private static readonly IFileSystem fileSystem; + private static readonly IConfigFileLocator configFileLocator; + + static GitVersionTasks() + { + log = new Log(); + environment = new Environment(); + fileSystem = new FileSystem(); + } + public static bool GetVersion(GetVersion task) { return ExecuteGitVersionTask(task, t => @@ -46,7 +57,7 @@ public static bool UpdateAssemblyInfo(UpdateAssemblyInfo task) t.AssemblyInfoTempFilePath = Path.Combine(fileWriteInfo.WorkingDirectory, fileWriteInfo.FileName); - using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(fileWriteInfo.FileName, fileWriteInfo.WorkingDirectory, versionVariables, new FileSystem(), true)) + using (var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(fileWriteInfo.FileName, fileWriteInfo.WorkingDirectory, versionVariables, new FileSystem(), log, true)) { assemblyInfoFileUpdater.Update(); assemblyInfoFileUpdater.CommitChanges(); @@ -75,8 +86,8 @@ public static bool WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) if (!GetVersionVariables(task, out var versionVariables)) return; var logger = t.Log; - BuildServerList.Init(new Environment()); - foreach (var buildServer in BuildServerList.GetApplicableBuildServers()) + BuildServerList.Init(environment, log); + foreach (var buildServer in BuildServerList.GetApplicableBuildServers(log)) { logger.LogMessage($"Executing GenerateSetVersionMessage for '{ buildServer.GetType().Name }'."); logger.LogMessage(buildServer.GenerateSetVersionMessage(versionVariables)); @@ -92,32 +103,32 @@ public static bool WriteVersionInfoToBuildLog(WriteVersionInfoToBuildLog task) private static bool ExecuteGitVersionTask(T task, Action action) where T : GitVersionTaskBase { - void LogDebug(string message) => task.Log.LogMessage(MessageImportance.Low, message); - void LogInfo(string message) => task.Log.LogMessage(MessageImportance.Normal, message); - void LogWarning(string message) => task.Log.LogWarning(message); - void LogError(string message) => task.Log.LogError(message); - - Logger.SetLoggers(LogDebug, LogInfo, LogWarning, LogError); - var log = task.Log; + var taskLog = task.Log; try { action(task); } catch (WarningException errorException) { - log.LogWarningFromException(errorException); + taskLog.LogWarningFromException(errorException); return true; } catch (Exception exception) { - log.LogErrorFromException(exception); + taskLog.LogErrorFromException(exception); return false; } - return !log.HasLoggedErrors; + return !taskLog.HasLoggedErrors; } private static bool GetVersionVariables(GitVersionTaskBase task, out VersionVariables versionVariables) - => new ExecuteCore(new FileSystem(), new Environment(), ConfigFileLocator.GetLocator(task.ConfigFilePath)).TryGetVersion(task.SolutionDirectory, out versionVariables, task.NoFetch, new Authentication()); + => new ExecuteCore(fileSystem, environment, log, GetLocator(task.ConfigFilePath)) + .TryGetVersion(task.SolutionDirectory, out versionVariables, task.NoFetch, new Authentication()); + + private static IConfigFileLocator GetLocator(string filePath = null) => + !string.IsNullOrEmpty(filePath) + ? (IConfigFileLocator) new NamedConfigFileLocator(filePath, fileSystem, log) + : new DefaultConfigFileLocator(fileSystem, log); } }