diff --git a/GitVersionCore.Tests/GitDirFinderTests.cs b/GitVersionCore.Tests/GitDirFinderTests.cs index 35672b988b..acae8f587d 100644 --- a/GitVersionCore.Tests/GitDirFinderTests.cs +++ b/GitVersionCore.Tests/GitDirFinderTests.cs @@ -30,26 +30,26 @@ public void Cleanup() [Test] public void From_WorkingDirectory() { - Assert.AreEqual(gitDirectory, GitDirFinder.TreeWalkForGitDir(workDirectory)); + Assert.AreEqual(gitDirectory, GitDirFinder.TreeWalkForDotGitDir(workDirectory)); } [Test] public void From_WorkingDirectory_Parent() { var parentDirectory = Directory.GetParent(workDirectory).FullName; - Assert.Null(GitDirFinder.TreeWalkForGitDir(parentDirectory)); + Assert.Null(GitDirFinder.TreeWalkForDotGitDir(parentDirectory)); } [Test] public void From_GitDirectory() { - Assert.AreEqual(gitDirectory, GitDirFinder.TreeWalkForGitDir(gitDirectory)); + Assert.AreEqual(gitDirectory, GitDirFinder.TreeWalkForDotGitDir(gitDirectory)); } [Test] public void From_RefsDirectory() { var refsDirectory = Path.Combine(gitDirectory, "refs"); - Assert.AreEqual(gitDirectory, GitDirFinder.TreeWalkForGitDir(refsDirectory)); + Assert.AreEqual(gitDirectory, GitDirFinder.TreeWalkForDotGitDir(refsDirectory)); } } diff --git a/GitVersionCore/GitDirFinder.cs b/GitVersionCore/GitDirFinder.cs index af0de4a893..9478cc8da8 100644 --- a/GitVersionCore/GitDirFinder.cs +++ b/GitVersionCore/GitDirFinder.cs @@ -5,7 +5,7 @@ public class GitDirFinder { - public static string TreeWalkForGitDir(string currentDirectory) + public static string TreeWalkForDotGitDir(string currentDirectory) { var gitDirectory = Repository.Discover(currentDirectory); diff --git a/GitVersionCore/GitVersionCore.csproj b/GitVersionCore/GitVersionCore.csproj index 1ed5c382ff..db45bf0ca9 100644 --- a/GitVersionCore/GitVersionCore.csproj +++ b/GitVersionCore/GitVersionCore.csproj @@ -84,6 +84,7 @@ + diff --git a/GitVersionCore/Helpers/DeleteHelper.cs b/GitVersionCore/Helpers/DeleteHelper.cs index 83ad19f277..37888943d4 100644 --- a/GitVersionCore/Helpers/DeleteHelper.cs +++ b/GitVersionCore/Helpers/DeleteHelper.cs @@ -2,26 +2,6 @@ { using System.IO; - public static class ServiceMessageEscapeHelper - { - public static string EscapeValue(string value) - { - if (value == null) - { - return null; - } - // List of escape values from http://confluence.jetbrains.com/display/TCD8/Build+Script+Interaction+with+TeamCity - - value = value.Replace("|", "||"); - value = value.Replace("'", "|'"); - value = value.Replace("[", "|["); - value = value.Replace("]", "|]"); - value = value.Replace("\r", "|r"); - value = value.Replace("\n", "|n"); - - return value; - } - } public static class DeleteHelper { public static void DeleteGitRepository(string directory) diff --git a/GitVersionCore/Helpers/ServiceMessageEscapeHelper.cs b/GitVersionCore/Helpers/ServiceMessageEscapeHelper.cs new file mode 100644 index 0000000000..98b2ae0c0b --- /dev/null +++ b/GitVersionCore/Helpers/ServiceMessageEscapeHelper.cs @@ -0,0 +1,23 @@ +namespace GitVersion +{ + public static class ServiceMessageEscapeHelper + { + public static string EscapeValue(string value) + { + if (value == null) + { + return null; + } + // List of escape values from http://confluence.jetbrains.com/display/TCD8/Build+Script+Interaction+with+TeamCity + + value = value.Replace("|", "||"); + value = value.Replace("'", "|'"); + value = value.Replace("[", "|["); + value = value.Replace("]", "|]"); + value = value.Replace("\r", "|r"); + value = value.Replace("\n", "|n"); + + return value; + } + } +} \ No newline at end of file diff --git a/GitVersionExe.Tests/ArgumentParserTests.cs b/GitVersionExe.Tests/ArgumentParserTests.cs index 4b1cce7368..1a5ab9bff6 100644 --- a/GitVersionExe.Tests/ArgumentParserTests.cs +++ b/GitVersionExe.Tests/ArgumentParserTests.cs @@ -205,6 +205,13 @@ public void update_assembly_info_with_relative_filename() arguments.UpdateAssemblyInfoFileName.ShouldBe("..\\..\\CommonAssemblyInfo.cs"); } + [Test] + public void dynamicRepoLocation() + { + var arguments = ArgumentParser.ParseArguments("-dynamicRepoLocation c:\\foo\\"); + arguments.DynamicRepositoryLocation.ShouldBe("c:\\foo\\"); + } + [Test] public void can_log_to_console() { diff --git a/GitVersionExe.Tests/GitPreparerTests.cs b/GitVersionExe.Tests/GitPreparerTests.cs index 2a1682114d..5fa000fd96 100644 --- a/GitVersionExe.Tests/GitPreparerTests.cs +++ b/GitVersionExe.Tests/GitPreparerTests.cs @@ -1,4 +1,6 @@ -using System.IO; +using System; +using System.IO; +using System.Linq; using GitVersion; using LibGit2Sharp; using NUnit.Framework; @@ -18,64 +20,103 @@ public GitPreparerTests() const string SpecificBranchName = "feature/foo"; [Test] - [TestCase(null, DefaultBranchName, false)] - [TestCase(SpecificBranchName, SpecificBranchName, false)] - [TestCase(null, DefaultBranchName, true)] - [TestCase(SpecificBranchName, SpecificBranchName, true)] - public void WorksCorrectlyWithRemoteRepository(string branchName, string expectedBranchName, bool checkConfig) + [TestCase(null, DefaultBranchName)] + [TestCase(SpecificBranchName, SpecificBranchName)] + public void WorksCorrectlyWithRemoteRepository(string branchName, string expectedBranchName) { - var tempDir = Path.GetTempPath(); + var repoName = Guid.NewGuid().ToString(); + var tempPath = Path.GetTempPath(); + var tempDir = Path.Combine(tempPath, repoName); + Directory.CreateDirectory(tempDir); + string dynamicRepositoryPath = null; - using (var fixture = new EmptyRepositoryFixture(new Config())) + try { - fixture.Repository.MakeCommits(5); - - if (checkConfig) + using (var fixture = new EmptyRepositoryFixture(new Config())) { - fixture.Repository.CreateFileAndCommit("GitVersionConfig.yaml"); - } + var expectedDynamicRepoLocation = Path.Combine(tempPath, fixture.RepositoryPath.Split('\\').Last()); - fixture.Repository.CreateBranch(SpecificBranchName); + fixture.Repository.MakeCommits(5); + fixture.Repository.CreateFileAndCommit("TestFile.txt"); - if (checkConfig) - { - fixture.Repository.Refs.UpdateTarget(fixture.Repository.Refs.Head, fixture.Repository.Refs["refs/heads/" + SpecificBranchName]); + fixture.Repository.CreateBranch(SpecificBranchName); - fixture.Repository.CreateFileAndCommit("GitVersionConfig.yaml"); + var arguments = new Arguments + { + TargetPath = tempDir, + TargetUrl = fixture.RepositoryPath + }; - fixture.Repository.Refs.UpdateTarget(fixture.Repository.Refs.Head, fixture.Repository.Refs["refs/heads/" + DefaultBranchName]); - } + // Copy contents into working directory + File.Copy(Path.Combine(fixture.RepositoryPath, "TestFile.txt"), Path.Combine(tempDir, "TestFile.txt")); - var arguments = new Arguments - { - TargetPath = tempDir, - TargetUrl = fixture.RepositoryPath - }; + if (!string.IsNullOrWhiteSpace(branchName)) + { + arguments.TargetBranch = branchName; + } - if (!string.IsNullOrWhiteSpace(branchName)) - { - arguments.TargetBranch = branchName; - } + var gitPreparer = new GitPreparer(arguments); + gitPreparer.InitialiseDynamicRepositoryIfNeeded(); + dynamicRepositoryPath = gitPreparer.GetDotGitDirectory(); - var gitPreparer = new GitPreparer(arguments); - var dynamicRepositoryPath = gitPreparer.Prepare(); + gitPreparer.IsDynamicGitRepository.ShouldBe(true); + gitPreparer.DynamicGitRepositoryPath.ShouldBe(expectedDynamicRepoLocation + "\\.git"); - dynamicRepositoryPath.ShouldBe(Path.Combine(tempDir, "_dynamicrepository", ".git")); - gitPreparer.IsDynamicGitRepository.ShouldBe(true); + using (var repository = new Repository(dynamicRepositoryPath)) + { + var currentBranch = repository.Head.CanonicalName; - using (var repository = new Repository(dynamicRepositoryPath)) - { - var currentBranch = repository.Head.CanonicalName; + currentBranch.EndsWith(expectedBranchName).ShouldBe(true); + } + } + } + finally + { + Directory.Delete(tempDir, true); + if (dynamicRepositoryPath != null) + DeleteHelper.DeleteGitRepository(dynamicRepositoryPath); + } + } + + [Test] + public void PicksAnotherDirectoryNameWhenDynamicRepoFolderTaken() + { + var repoName = Guid.NewGuid().ToString(); + var tempPath = Path.GetTempPath(); + var tempDir = Path.Combine(tempPath, repoName); + Directory.CreateDirectory(tempDir); + string expectedDynamicRepoLocation = null; - currentBranch.EndsWith(expectedBranchName).ShouldBe(true); + try + { + using (var fixture = new EmptyRepositoryFixture(new Config())) + { + fixture.Repository.CreateFileAndCommit("TestFile.txt"); + File.Copy(Path.Combine(fixture.RepositoryPath, "TestFile.txt"), Path.Combine(tempDir, "TestFile.txt")); + expectedDynamicRepoLocation = Path.Combine(tempPath, fixture.RepositoryPath.Split('\\').Last()); + Directory.CreateDirectory(expectedDynamicRepoLocation); - if (checkConfig) + var arguments = new Arguments { - var expectedConfigPath = Path.Combine(dynamicRepositoryPath, "..\\GitVersionConfig.yaml"); - File.Exists(expectedConfigPath).ShouldBe(true); - } + TargetPath = tempDir, + TargetUrl = fixture.RepositoryPath + }; + + var gitPreparer = new GitPreparer(arguments); + gitPreparer.InitialiseDynamicRepositoryIfNeeded(); + + gitPreparer.IsDynamicGitRepository.ShouldBe(true); + gitPreparer.DynamicGitRepositoryPath.ShouldBe(expectedDynamicRepoLocation + "_1\\.git"); } } + finally + { + Directory.Delete(tempDir, true); + if (expectedDynamicRepoLocation != null) + Directory.Delete(expectedDynamicRepoLocation, true); + if (expectedDynamicRepoLocation != null) + DeleteHelper.DeleteGitRepository(expectedDynamicRepoLocation + "_1"); + } } [Test] @@ -89,7 +130,7 @@ public void WorksCorrectlyWithLocalRepository() }; var gitPreparer = new GitPreparer(arguments); - var dynamicRepositoryPath = gitPreparer.Prepare(); + var dynamicRepositoryPath = gitPreparer.GetDotGitDirectory(); dynamicRepositoryPath.ShouldBe(null); gitPreparer.IsDynamicGitRepository.ShouldBe(false); diff --git a/GitVersionExe.Tests/HelpWriterTests.cs b/GitVersionExe.Tests/HelpWriterTests.cs index 63fb99bad8..eb5a5ef6bc 100644 --- a/GitVersionExe.Tests/HelpWriterTests.cs +++ b/GitVersionExe.Tests/HelpWriterTests.cs @@ -15,6 +15,7 @@ public void AllArgsAreInHelp() { "Init", "init" }, { "TargetBranch", "/b" }, { "LogFilePath" , "/l" }, + { "DynamicRepositoryLocation" , "/dynamicRepoLocation" }, { "IsHelp", "/?" } }; string helpText = null; diff --git a/GitVersionExe/ArgumentParser.cs b/GitVersionExe/ArgumentParser.cs index 8e2717eb9d..dfdcf365fc 100644 --- a/GitVersionExe/ArgumentParser.cs +++ b/GitVersionExe/ArgumentParser.cs @@ -84,6 +84,12 @@ public static Arguments ParseArguments(List commandLineArguments) continue; } + if (IsSwitch("dynamicRepoLocation", name)) + { + arguments.DynamicRepositoryLocation = value; + continue; + } + if (IsSwitch("url", name)) { arguments.TargetUrl = value; diff --git a/GitVersionExe/Arguments.cs b/GitVersionExe/Arguments.cs index 4706c0158e..f7d37304a0 100644 --- a/GitVersionExe/Arguments.cs +++ b/GitVersionExe/Arguments.cs @@ -15,6 +15,7 @@ public Arguments() public string TargetUrl; public string TargetBranch; public string CommitId; + public string DynamicRepositoryLocation; public bool Init; diff --git a/GitVersionExe/GitPreparer.cs b/GitVersionExe/GitPreparer.cs index 10d3516b32..dee73838e2 100644 --- a/GitVersionExe/GitPreparer.cs +++ b/GitVersionExe/GitPreparer.cs @@ -1,5 +1,6 @@ namespace GitVersion { + using System; using System.IO; using System.Linq; using LibGit2Sharp; @@ -20,31 +21,74 @@ public bool IsDynamicGitRepository public string DynamicGitRepositoryPath { get; private set; } - public string Prepare() + public void InitialiseDynamicRepositoryIfNeeded() { - var gitPath = arguments.TargetPath; + if (string.IsNullOrWhiteSpace(arguments.TargetUrl)) return; - if (!string.IsNullOrWhiteSpace(arguments.TargetUrl)) + var targetPath = CalculateTemporaryRepositoryPath(arguments.TargetUrl, arguments.DynamicRepositoryLocation); + DynamicGitRepositoryPath = CreateDynamicRepository(targetPath, arguments.Authentication, arguments.TargetUrl, arguments.TargetBranch); + } + + string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation) + { + var userTemp = dynamicRepositoryLocation ?? Path.GetTempPath(); + var repositoryName = targetUrl.Split('/', '\\').Last().Replace(".git", string.Empty); + var possiblePath = Path.Combine(userTemp, repositoryName); + + // Verify that the existing directory is ok for us to use + if (Directory.Exists(possiblePath)) { - gitPath = GetGitInfoFromUrl(); + if (!GitRepoHasMatchingRemote(possiblePath, targetUrl)) + { + var i = 1; + var originalPath = possiblePath; + bool possiblePathExists; + do + { + possiblePath = string.Concat(originalPath, "_", i++.ToString()); + possiblePathExists = Directory.Exists(possiblePath); + } while (possiblePathExists && !GitRepoHasMatchingRemote(possiblePath, targetUrl)); + } } - return GitDirFinder.TreeWalkForGitDir(gitPath); + return possiblePath; } - string GetGitInfoFromUrl() + static bool GitRepoHasMatchingRemote(string possiblePath, string targetUrl) { - var gitRootDirectory = Path.Combine(arguments.TargetPath, "_dynamicrepository"); - var gitDirectory = Path.Combine(gitRootDirectory, ".git"); - if (Directory.Exists(gitRootDirectory)) + try + { + using (var repository = new Repository(possiblePath)) + { + return repository.Network.Remotes.Any(r => r.Url == targetUrl); + } + } + catch (Exception) { - Logger.WriteInfo(string.Format("Deleting existing .git folder from '{0}' to force new checkout from url", gitRootDirectory)); + return false; + } + + } + + public string GetDotGitDirectory() + { + if (IsDynamicGitRepository) + return DynamicGitRepositoryPath; - DeleteHelper.DeleteGitRepository(gitRootDirectory); + return GitDirFinder.TreeWalkForDotGitDir(arguments.TargetPath); + } + + static string CreateDynamicRepository(string targetPath, Authentication authentication, string repositoryUrl, string targetBranch) + { + var gitDirectory = Path.Combine(targetPath, ".git"); + if (Directory.Exists(targetPath)) + { + Logger.WriteInfo("Git repository already exists at {0}, skipping clone"); + + return gitDirectory; } Credentials credentials = null; - var authentication = arguments.Authentication; if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password)) { Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username)); @@ -56,9 +100,9 @@ string GetGitInfoFromUrl() }; } - Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", arguments.TargetUrl)); + Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl)); - Repository.Clone(arguments.TargetUrl, gitDirectory, + Repository.Clone(repositoryUrl, gitDirectory, new CloneOptions { IsBare = true, @@ -67,11 +111,10 @@ string GetGitInfoFromUrl() }); // Normalize (download branches) before using the branch - GitHelper.NormalizeGitDirectory(gitDirectory, arguments.Authentication); + GitHelper.NormalizeGitDirectory(gitDirectory, authentication); using (var repository = new Repository(gitDirectory)) { - var targetBranch = arguments.TargetBranch; if (string.IsNullOrWhiteSpace(targetBranch)) { targetBranch = repository.Head.Name; @@ -87,10 +130,10 @@ string GetGitInfoFromUrl() if (newHead == null) { - var remoteReference = GetRemoteReference(repository, targetBranch, arguments.TargetUrl); + var remoteReference = GetRemoteReference(repository, targetBranch, repositoryUrl); if (remoteReference != null) { - repository.Network.Fetch(arguments.TargetUrl, new[] + repository.Network.Fetch(repositoryUrl, new[] { string.Format("{0}:{1}", remoteReference.CanonicalName, targetBranch) }); @@ -105,16 +148,8 @@ string GetGitInfoFromUrl() repository.Refs.UpdateTarget(repository.Refs.Head, newHead); } - - // < 3.0 method - repository.CheckoutFilesIfExist("NextVersion.txt"); - - // > 3.0 method - repository.CheckoutFilesIfExist("GitVersionConfig.yaml"); } - DynamicGitRepositoryPath = gitDirectory; - return gitDirectory; } diff --git a/GitVersionExe/GitVersionExe.csproj b/GitVersionExe/GitVersionExe.csproj index aa3bca63b1..6b324afe88 100644 --- a/GitVersionExe/GitVersionExe.csproj +++ b/GitVersionExe/GitVersionExe.csproj @@ -61,6 +61,7 @@ + diff --git a/GitVersionExe/HelpWriter.cs b/GitVersionExe/HelpWriter.cs index 51d4bb6362..e6bce69b7a 100644 --- a/GitVersionExe/HelpWriter.cs +++ b/GitVersionExe/HelpWriter.cs @@ -38,6 +38,8 @@ Specify name of AssemblyInfo file. Can also /updateAssemblyInfo GlobalAssemblyIn /u Username in case authentication is required. /p Password in case authentication is required. /c The commit id to check. If not specified, the latest available commit on the specified branch will be used. + /dynamicRepoLocation + By default dynamic repositories will be cloned to %tmp%. Use this switch to override # Execute build args /exec Executes target executable making GitVersion variables available as environmental variables diff --git a/GitVersionExe/Program.cs b/GitVersionExe/Program.cs index 93fc002112..58b30b3f5a 100644 --- a/GitVersionExe/Program.cs +++ b/GitVersionExe/Program.cs @@ -11,11 +11,10 @@ namespace GitVersion class Program { static StringBuilder log = new StringBuilder(); - const string MsBuild = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe"; static void Main() { - var exitCode = Run(); + var exitCode = VerifyArgumentsAndRun(); if (Debugger.IsAttached) { @@ -31,10 +30,12 @@ static void Main() Environment.Exit(exitCode); } - static int Run() + static int VerifyArgumentsAndRun() { try { + var fileSystem = new FileSystem(); + Arguments arguments; var argumentsWithoutExeName = GetArgumentsWithoutExeName(); try @@ -48,108 +49,32 @@ static int Run() HelpWriter.Write(); return 1; } - if (arguments.IsHelp) { HelpWriter.Write(); return 0; } - if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec)) - { - arguments.Output = OutputType.BuildServer; - } - - ConfigureLogging(arguments); - - var gitPreparer = new GitPreparer(arguments); - var gitDirectory = gitPreparer.Prepare(); - if (string.IsNullOrEmpty(gitDirectory)) - { - Console.Error.WriteLine("Failed to prepare or find the .git directory in path '{0}'", arguments.TargetPath); - return 1; - } - - var fileSystem = new FileSystem(); if (arguments.Init) { - ConfigurationProvider.WriteSample(gitDirectory, fileSystem); + ConfigurationProvider.WriteSample(arguments.TargetPath, fileSystem); return 0; } if (arguments.ShowConfig) { - Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(gitDirectory, fileSystem)); + Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(arguments.TargetPath, fileSystem)); return 0; } - var workingDirectory = Directory.GetParent(gitDirectory).FullName; - Logger.WriteInfo("Working directory: " + workingDirectory); - var applicableBuildServers = GetApplicableBuildServers(arguments.Authentication).ToList(); - - foreach (var buildServer in applicableBuildServers) - { - buildServer.PerformPreProcessingSteps(gitDirectory); - } - VersionVariables variables; - var versionFinder = new GitVersionFinder(); - var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); - - using (var repo = RepositoryLoader.GetRepo(gitDirectory)) - { - var gitVersionContext = new GitVersionContext(repo, configuration, commitId: arguments.CommitId); - var semanticVersion = versionFinder.FindVersion(gitVersionContext); - var config = gitVersionContext.Configuration; - variables = VariableProvider.GetVariablesFor(semanticVersion, config.AssemblyVersioningScheme, config.VersioningMode, config.ContinuousDeploymentFallbackTag, gitVersionContext.IsCurrentCommitTagged); - } - - if (arguments.Output == OutputType.BuildServer) - { - foreach (var buildServer in applicableBuildServers) - { - buildServer.WriteIntegration(Console.WriteLine, variables); - } - } - - if (arguments.Output == OutputType.Json) + if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec)) { - switch (arguments.ShowVariable) - { - case null: - Console.WriteLine(JsonOutputFormatter.ToJson(variables)); - break; - - default: - string part; - if (!variables.TryGetValue(arguments.ShowVariable, out part)) - { - throw new WarningException(string.Format("'{0}' variable does not exist", arguments.ShowVariable)); - } - Console.WriteLine(part); - break; - } + arguments.Output = OutputType.BuildServer; } - using (var assemblyInfoUpdate = new AssemblyInfoFileUpdate(arguments, workingDirectory, variables, fileSystem)) - { - var execRun = RunExecCommandIfNeeded(arguments, workingDirectory, variables); - var msbuildRun = RunMsBuildIfNeeded(arguments, workingDirectory, variables); - if (!execRun && !msbuildRun) - { - assemblyInfoUpdate.DoNotRestoreAssemblyInfo(); - //TODO Put warning back - //if (!context.CurrentBuildServer.IsRunningInBuildAgent()) - //{ - // Console.WriteLine("WARNING: Not running in build server and /ProjectFile or /Exec arguments not passed"); - // Console.WriteLine(); - // Console.WriteLine("Run GitVersion.exe /? for help"); - //} - } - } + ConfigureLogging(arguments); + Logger.WriteInfo("Working directory: " + arguments.TargetPath); - if (gitPreparer.IsDynamicGitRepository) - { - DeleteHelper.DeleteGitRepository(gitPreparer.DynamicGitRepositoryPath); - } + SpecifiedArgumentRunner.Run(arguments, fileSystem); } catch (WarningException exception) { @@ -167,11 +92,6 @@ static int Run() return 0; } - static IEnumerable GetApplicableBuildServers(Authentication authentication) - { - return BuildServerList.GetApplicableBuildServers(authentication); - } - static void ConfigureLogging(Arguments arguments) { var writeActions = new List> @@ -223,43 +143,5 @@ static List GetArgumentsWithoutExeName() .Skip(1) .ToList(); } - - static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) - { - if (string.IsNullOrEmpty(args.Proj)) return false; - - Logger.WriteInfo(string.Format("Launching {0} \"{1}\" {2}", MsBuild, args.Proj, args.ProjArgs)); - var results = ProcessHelper.Run( - Logger.WriteInfo, Logger.WriteError, - null, MsBuild, string.Format("\"{0}\" {1}", args.Proj, args.ProjArgs), workingDirectory, - GetEnvironmentalVariables(variables)); - - if (results != 0) - throw new WarningException("MsBuild execution failed, non-zero return code"); - - return true; - } - - static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) - { - if (string.IsNullOrEmpty(args.Exec)) return false; - - Logger.WriteInfo(string.Format("Launching {0} {1}", args.Exec, args.ExecArgs)); - var results = ProcessHelper.Run( - Logger.WriteInfo, Logger.WriteError, - null, args.Exec, args.ExecArgs, workingDirectory, - GetEnvironmentalVariables(variables)); - if (results != 0) - throw new WarningException(string.Format("Execution of {0} failed, non-zero return code", args.Exec)); - - return true; - } - - static KeyValuePair[] GetEnvironmentalVariables(VersionVariables variables) - { - return variables - .Select(v => new KeyValuePair("GitVersion_" + v.Key, v.Value)) - .ToArray(); - } } } \ No newline at end of file diff --git a/GitVersionExe/SpecifiedArgumentRunner.cs b/GitVersionExe/SpecifiedArgumentRunner.cs new file mode 100644 index 0000000000..a1e7dd1a10 --- /dev/null +++ b/GitVersionExe/SpecifiedArgumentRunner.cs @@ -0,0 +1,127 @@ +namespace GitVersion +{ + using System; + using System.Collections.Generic; + using System.Linq; + using GitVersion.Helpers; + + class SpecifiedArgumentRunner + { + const string MsBuild = @"c:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe"; + + public static void Run(Arguments arguments, IFileSystem fileSystem) + { + var gitPreparer = new GitPreparer(arguments); + gitPreparer.InitialiseDynamicRepositoryIfNeeded(); + var dotGitDirectory = gitPreparer.GetDotGitDirectory(); + if (string.IsNullOrEmpty(dotGitDirectory)) + { + throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'", arguments.TargetPath)); + } + var applicableBuildServers = GetApplicableBuildServers(arguments.Authentication).ToList(); + + foreach (var buildServer in applicableBuildServers) + { + buildServer.PerformPreProcessingSteps(dotGitDirectory); + } + VersionVariables variables; + var versionFinder = new GitVersionFinder(); + var configuration = ConfigurationProvider.Provide(dotGitDirectory, fileSystem); + + using (var repo = RepositoryLoader.GetRepo(dotGitDirectory)) + { + var gitVersionContext = new GitVersionContext(repo, configuration, commitId: arguments.CommitId); + var semanticVersion = versionFinder.FindVersion(gitVersionContext); + var config = gitVersionContext.Configuration; + variables = VariableProvider.GetVariablesFor(semanticVersion, config.AssemblyVersioningScheme, config.VersioningMode, config.ContinuousDeploymentFallbackTag, gitVersionContext.IsCurrentCommitTagged); + } + + if (arguments.Output == OutputType.BuildServer) + { + foreach (var buildServer in applicableBuildServers) + { + buildServer.WriteIntegration(Console.WriteLine, variables); + } + } + + if (arguments.Output == OutputType.Json) + { + switch (arguments.ShowVariable) + { + case null: + Console.WriteLine(JsonOutputFormatter.ToJson(variables)); + break; + + default: + string part; + if (!variables.TryGetValue(arguments.ShowVariable, out part)) + { + throw new WarningException(string.Format("'{0}' variable does not exist", arguments.ShowVariable)); + } + Console.WriteLine(part); + break; + } + } + + using (var assemblyInfoUpdate = new AssemblyInfoFileUpdate(arguments, arguments.TargetPath, variables, fileSystem)) + { + var execRun = RunExecCommandIfNeeded(arguments, arguments.TargetPath, variables); + var msbuildRun = RunMsBuildIfNeeded(arguments, arguments.TargetPath, variables); + if (!execRun && !msbuildRun) + { + assemblyInfoUpdate.DoNotRestoreAssemblyInfo(); + //TODO Put warning back + //if (!context.CurrentBuildServer.IsRunningInBuildAgent()) + //{ + // Console.WriteLine("WARNING: Not running in build server and /ProjectFile or /Exec arguments not passed"); + // Console.WriteLine(); + // Console.WriteLine("Run GitVersion.exe /? for help"); + //} + } + } + } + + static IEnumerable GetApplicableBuildServers(Authentication authentication) + { + return BuildServerList.GetApplicableBuildServers(authentication); + } + + static bool RunMsBuildIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) + { + if (string.IsNullOrEmpty(args.Proj)) return false; + + Logger.WriteInfo(string.Format("Launching {0} \"{1}\" {2}", MsBuild, args.Proj, args.ProjArgs)); + var results = ProcessHelper.Run( + Logger.WriteInfo, Logger.WriteError, + null, MsBuild, string.Format("\"{0}\" {1}", args.Proj, args.ProjArgs), workingDirectory, + GetEnvironmentalVariables(variables)); + + if (results != 0) + throw new WarningException("MsBuild execution failed, non-zero return code"); + + return true; + } + + static bool RunExecCommandIfNeeded(Arguments args, string workingDirectory, VersionVariables variables) + { + if (string.IsNullOrEmpty(args.Exec)) return false; + + Logger.WriteInfo(string.Format("Launching {0} {1}", args.Exec, args.ExecArgs)); + var results = ProcessHelper.Run( + Logger.WriteInfo, Logger.WriteError, + null, args.Exec, args.ExecArgs, workingDirectory, + GetEnvironmentalVariables(variables)); + if (results != 0) + throw new WarningException(string.Format("Execution of {0} failed, non-zero return code", args.Exec)); + + return true; + } + + static KeyValuePair[] GetEnvironmentalVariables(VersionVariables variables) + { + return variables + .Select(v => new KeyValuePair("GitVersion_" + v.Key, v.Value)) + .ToArray(); + } + } +} \ No newline at end of file diff --git a/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs b/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs index f8eb3ef433..2fc3073eac 100644 --- a/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs +++ b/GitVersionTask/AssemblyInfoBuilder/UpdateAssemblyInfo.cs @@ -66,7 +66,7 @@ public void InnerExecute() InvalidFileChecker.CheckForInvalidFiles(CompileFiles, ProjectFile); - var gitDirectory = GitDirFinder.TreeWalkForGitDir(SolutionDirectory); + var gitDirectory = GitDirFinder.TreeWalkForDotGitDir(SolutionDirectory); if (string.IsNullOrEmpty(gitDirectory)) return; diff --git a/GitVersionTask/GetVersion.cs b/GitVersionTask/GetVersion.cs index c8c124af44..bbbb678109 100644 --- a/GitVersionTask/GetVersion.cs +++ b/GitVersionTask/GetVersion.cs @@ -82,7 +82,7 @@ public override bool Execute() try { Tuple versionAndBranch; - var gitDirectory = GitDirFinder.TreeWalkForGitDir(SolutionDirectory); + var gitDirectory = GitDirFinder.TreeWalkForDotGitDir(SolutionDirectory); var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); if (VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out versionAndBranch, configuration)) diff --git a/GitVersionTask/VersionAndBranchFinder.cs b/GitVersionTask/VersionAndBranchFinder.cs index 81ee90e302..bc10a9a77f 100644 --- a/GitVersionTask/VersionAndBranchFinder.cs +++ b/GitVersionTask/VersionAndBranchFinder.cs @@ -7,7 +7,7 @@ public static class VersionAndBranchFinder static List processedDirectories = new List(); public static bool TryGetVersion(string directory, out Tuple versionAndBranch, Config configuration) { - var gitDirectory = GitDirFinder.TreeWalkForGitDir(directory); + var gitDirectory = GitDirFinder.TreeWalkForDotGitDir(directory); if (string.IsNullOrEmpty(gitDirectory)) { diff --git a/GitVersionTask/WriteVersionInfoToBuildLog.cs b/GitVersionTask/WriteVersionInfoToBuildLog.cs index 12ffa26d97..7365f194a8 100644 --- a/GitVersionTask/WriteVersionInfoToBuildLog.cs +++ b/GitVersionTask/WriteVersionInfoToBuildLog.cs @@ -50,7 +50,7 @@ public override bool Execute() public void InnerExecute() { Tuple result; - var gitDirectory = GitDirFinder.TreeWalkForGitDir(SolutionDirectory); + var gitDirectory = GitDirFinder.TreeWalkForDotGitDir(SolutionDirectory); var configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem); if (!VersionAndBranchFinder.TryGetVersion(SolutionDirectory, out result, configuration)) {