Exemple #1
0
    public static CachedVersion GetVersion(string gitDirectory, Config configuration)
    {
        using (var repo = RepositoryLoader.GetRepo(gitDirectory))
        {
            var versionFinder = new GitVersionFinder();
            var context = new GitVersionContext(repo, configuration);
            var ticks = DirectoryDateFinder.GetLastDirectoryWrite(gitDirectory);
            var key = string.Format("{0}:{1}:{2}", repo.Head.CanonicalName, repo.Head.Tip.Sha, ticks);
            CachedVersion cachedVersion;
            if (versionCacheVersions.TryGetValue(key, out cachedVersion))
            {
                if (cachedVersion.Timestamp != ticks)
                {
                    Logger.WriteInfo("Change detected. flushing cache.");
                    cachedVersion.SemanticVersion = versionFinder.FindVersion(context);
                    cachedVersion.MasterReleaseDate = LastMinorVersionFinder.Execute(repo, new Config(), repo.Head.Tip);
                }
                return cachedVersion;
            }
            Logger.WriteInfo("Version not in cache. Calculating version.");

            return versionCacheVersions[key] = new CachedVersion
            {
                SemanticVersion = versionFinder.FindVersion(context),
                MasterReleaseDate = LastMinorVersionFinder.Execute(repo, new Config(), repo.Head.Tip),
                Timestamp = ticks
            };

        }
    }
Exemple #2
0
 static SemanticVersion GetSemanticVersion(Repository repository)
 {
     var versionForRepositoryFinder = new GitVersionFinder();
     var gitVersionContext = new GitVersionContext(repository);
     Logger.WriteInfo("Running against branch: " + gitVersionContext.CurrentBranch.Name);
     return versionForRepositoryFinder.FindVersion(gitVersionContext);
 }
Exemple #3
0
        public static VersionVariables ExecuteGitVersion(IFileSystem fileSystem, string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId)
        {
            // Normalise if we are running on build server
            var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, targetBranch, noFetch, workingDirectory);

            gitPreparer.Initialise(BuildServerList.GetApplicableBuildServers().Any());
            var dotGitDirectory = gitPreparer.GetDotGitDirectory();
            var projectRoot     = gitPreparer.GetProjectRootDirectory();

            Logger.WriteInfo(string.Format("Project root is: " + projectRoot));
            if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
            {
                // TODO Link to wiki article
                throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'.", workingDirectory));
            }
            VersionVariables variables;
            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(projectRoot, fileSystem);

            using (var repo = RepositoryLoader.GetRepo(dotGitDirectory))
            {
                var gitVersionContext = new GitVersionContext(repo, configuration, commitId: commitId);
                var semanticVersion   = versionFinder.FindVersion(gitVersionContext);
                var config            = gitVersionContext.Configuration;
                variables = VariableProvider.GetVariablesFor(semanticVersion, config.AssemblyVersioningScheme, config.VersioningMode, config.ContinuousDeploymentFallbackTag, gitVersionContext.IsCurrentCommitTagged);
            }

            return(variables);
        }
Exemple #4
0
    public static Tuple<CachedVersion, GitVersionContext> GetVersion(string gitDirectory, Config configuration)
    {
        using (var repo = RepositoryLoader.GetRepo(gitDirectory))
        {
            var versionFinder = new GitVersionFinder();
            var context = new GitVersionContext(repo, configuration);
            var ticks = DirectoryDateFinder.GetLastDirectoryWrite(gitDirectory);
            var key = string.Format("{0}:{1}:{2}", repo.Head.CanonicalName, repo.Head.Tip.Sha, ticks);

            Tuple<CachedVersion, GitVersionContext> result;
            if (versionCacheVersions.TryGetValue(key, out result))
            {
                if (result.Item1.Timestamp != ticks)
                {
                    Logger.WriteInfo("Change detected. flushing cache.");
                    result.Item1.SemanticVersion = versionFinder.FindVersion(context);
                }
                return result;
            }
            Logger.WriteInfo("Version not in cache. Calculating version.");

            return versionCacheVersions[key] = Tuple.Create(new CachedVersion
            {
                SemanticVersion = versionFinder.FindVersion(context),
                Timestamp = ticks
            }, context);
        }
    }
Exemple #5
0
        public static VersionVariables ExecuteGitVersion(IFileSystem fileSystem, string targetUrl, string dynamicRepositoryLocation, Authentication authentication, string targetBranch, bool noFetch, string workingDirectory, string commitId)
        {
            // Normalise if we are running on build server
            var gitPreparer = new GitPreparer(targetUrl, dynamicRepositoryLocation, authentication, noFetch, workingDirectory);
            var applicableBuildServers = BuildServerList.GetApplicableBuildServers();
            var buildServer = applicableBuildServers.FirstOrDefault();
            var currentBranch = buildServer == null ? null : buildServer.GetCurrentBranch();
            if (!string.IsNullOrEmpty(currentBranch))
            {
                Logger.WriteInfo("Branch from build environment: " + currentBranch);
            }
            gitPreparer.Initialise(buildServer != null, currentBranch ?? targetBranch);
            var dotGitDirectory = gitPreparer.GetDotGitDirectory();
            var projectRoot = gitPreparer.GetProjectRootDirectory();
            Logger.WriteInfo(string.Format("Project root is: " + projectRoot));
            if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot))
            {
                // TODO Link to wiki article
                throw new Exception(string.Format("Failed to prepare or find the .git directory in path '{0}'.", workingDirectory));
            }
            VersionVariables variables;
            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(projectRoot, fileSystem);

            using (var repo = RepositoryLoader.GetRepo(dotGitDirectory))
            {
                var gitVersionContext = new GitVersionContext(repo, configuration, commitId: commitId);
                var semanticVersion = versionFinder.FindVersion(gitVersionContext);
                var config = gitVersionContext.Configuration;
                variables = VariableProvider.GetVariablesFor(semanticVersion, config.AssemblyVersioningScheme, config.VersioningMode, config.ContinuousDeploymentFallbackTag, gitVersionContext.IsCurrentCommitTagged);
            }

            return variables;
        }
        public static SemanticVersion GetSemanticVersion(Repository repository)
        {
            var versionForRepositoryFinder = new GitVersionFinder();
            var gitVersionContext          = new GitVersionContext(repository);

            Logger.WriteInfo("Running against branch: " + gitVersionContext.CurrentBranch.Name);
            return(versionForRepositoryFinder.FindVersion(gitVersionContext));
        }
Exemple #7
0
        VersionVariables ExecuteInternal(string targetBranch, string commitId, IRepository repo, GitPreparer gitPreparer, string projectRoot, IBuildServer buildServer, Config overrideConfig = null)
        {
            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(projectRoot, fileSystem, overrideConfig: overrideConfig);

            var gitVersionContext = new GitVersionContext(repo, configuration, commitId: commitId);
            var semanticVersion   = versionFinder.FindVersion(gitVersionContext);

            return(VariableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged));
        }
Exemple #8
0
        VersionVariables ExecuteInternal(string targetBranch, string commitId, IRepository repo, GitPreparer gitPreparer, string projectRoot, IBuildServer buildServer)
        {
            gitPreparer.Initialise(buildServer != null, ResolveCurrentBranch(buildServer, targetBranch, gitPreparer.IsDynamicGitRepository));

            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(projectRoot, fileSystem);

            var gitVersionContext = new GitVersionContext(repo, configuration, commitId: commitId);
            var semanticVersion   = versionFinder.FindVersion(gitVersionContext);

            return(VariableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged));
        }
        VersionVariables ExecuteInternal(string targetBranch, string commitId, IRepository repo, GitPreparer gitPreparer, string projectRoot, IBuildServer buildServer)
        {
            gitPreparer.Initialise(buildServer != null, ResolveCurrentBranch(buildServer, targetBranch, gitPreparer.IsDynamicGitRepository));

            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(projectRoot, fileSystem);

            var gitVersionContext = new GitVersionContext(repo, configuration, commitId : commitId);
            var semanticVersion = versionFinder.FindVersion(gitVersionContext);

            return VariableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged);
        }
    public void CanDetermineTheVersionFromAFetchedFeature()
    {
        var gitDirectory = FakeTeamCityFetchAndCheckout(ASBMTestRepoWorkingDirPath, "refs/heads/feature/one");

        var arguments = new Arguments();
        GitHelper.NormalizeGitDirectory(gitDirectory, arguments);

        using (var repository = new Repository(gitDirectory))
        {
            var semanticVersion = new GitVersionFinder().FindVersion(new GitVersionContext(repository));
            Assert.IsNotNull(semanticVersion);
        }
    }
Exemple #11
0
    public void CanDetermineTheVersionFromAFetchedMaster()
    {
        var gitDirectory = FakeTeamCityFetchAndCheckout(ASBMTestRepoWorkingDirPath, "refs/heads/master");

        var authentication = new Authentication();
        GitHelper.NormalizeGitDirectory(gitDirectory, authentication);

        using (var repository = new Repository(gitDirectory))
        {
            var semanticVersion = new GitVersionFinder().FindVersion(new GitVersionContext(repository, new Config()));
            Assert.IsNotNull(semanticVersion);
        }
    }
Exemple #12
0
    public void Foo()
    {
        using (var repository = new Repository(@"C:\Code\ServiceControl"))
        {
            var branch = repository.Branches.First(x => x.Name == "develop");

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext(repository, branch, new Config()));
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
        }
    }
        public ExecutionResults ExecuteGitVersion(bool inProcess = true)
        {
            if (!inProcess)
            {
                return GitVersionHelper.ExecuteIn(RepositoryPath);
            }

            var vf = new GitVersionFinder();
            var sv = vf.FindVersion(new GitVersionContext(Repository));

            var vars = VariableProvider.GetVariablesFor(sv);

            return new InProcessExecutionResults(vars);
        }
        VersionVariables ExecuteInternal(string targetBranch, string commitId, GitPreparer gitPreparer, Config overrideConfig = null)
        {
            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(gitPreparer, overrideConfig: overrideConfig, configFileLocator: configFileLocator);

            return(gitPreparer.WithRepository(repo =>
            {
                var gitVersionContext = new GitVersionContext(repo, log, targetBranch, configuration, commitId: commitId);
                var semanticVersion = versionFinder.FindVersion(log, gitVersionContext);

                var variableProvider = new VariableProvider(log);
                return variableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged);
            }));
        }
Exemple #15
0
    public void NServiceBusDevelop()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "develop");

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext(repository, branch));
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
Exemple #16
0
    public void NServiceBusDevelopOlderCommit()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "develop");
            repository.Checkout("c0e0a5e13775552cd3e08e039f453e4cf1fd4235");

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext(repository, branch, new Config()));
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
Exemple #17
0
    public void CanDetermineTheVersionFromAPullRequest()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        CreateFakePullRequest(repoPath, "1735");

        var gitDirectory = FakeTeamCityFetchAndCheckout(repoPath, "refs/pull/1735/merge");

        var authentication = new Authentication();
        GitHelper.NormalizeGitDirectory(gitDirectory, authentication);

        using (var repository = new Repository(gitDirectory))
        {
            var semanticVersion = new GitVersionFinder().FindVersion(new GitVersionContext(repository, new Config()));
            Assert.IsNotNull(semanticVersion);
        }
    }
    public void AFeatureBranchPrefixIsNotIncludedInTag()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            repo.Branches["develop"].ForceCheckout();

            const string branchName = "feature/ABC-1234_SomeDescription";
            repo.Branches.Add(branchName, repo.Head.Tip).ForceCheckout();

            AddOneCommitToHead(repo, "code");

            var finder = new GitVersionFinder();

            var versionAndBranch = finder.FindVersion(new GitVersionContext(repo));

            ObjectApprover.VerifyWithJson(versionAndBranch, Scrubbers.GuidAndDateScrubber);
        }
    }
    public void AFeatureBranchIsRequiredToBranchOffOfDevelopBranch()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            const string branchName = "feature/unborn";

            // Create a new unborn feature branch sharing no history with "develop"
            repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName);

            AddOneCommitToHead(repo, "feature");

            var feature = repo.Branches[branchName];

            var finder = new GitVersionFinder();

            Assert.Throws<WarningException>(() => finder.FindVersion(new GitVersionContext(repo, feature)));
        }
    }
    public void AFeatureBranchDoesNotRequireASpecificPrefix()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            repo.Branches["develop"].ForceCheckout();

            const string branchName = "every-feature-is-welcome";
            repo.Branches.Add(branchName, repo.Head.Tip).ForceCheckout();

            AddOneCommitToHead(repo, "code");

            var finder = new GitVersionFinder();

            var versionAndBranch = finder.FindVersion(new GitVersionContext(repo));

            ObjectApprover.VerifyWithJson(versionAndBranch, Scrubbers.GuidAndDateScrubber);
        }
    }
    public void AHotfixBranchIsRequiredToBranchOffOfMasterBranch()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            const string branchName = "hotfix/1.0.2";

            // Create a new unborn hotfix branch sharing no history with "master"
            repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName);

            AddOneCommitToHead(repo, "hotfix");

            var feature = repo.Branches[branchName];

            var finder = new GitVersionFinder();

            Assert.Throws<ErrorException>(() => finder.FindVersion(new GitVersionContext
            {
                Repository = repo,
                CurrentBranch = feature,
            }));
        }
    }
    public void RequiresALocalDevelopBranch()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            repo.Branches["feature/one"].ForceCheckout();

            repo.Branches.Remove("develop");

            var finder = new GitVersionFinder();

            Assert.Throws<ErrorException>(() => finder.FindVersion(new GitVersionContext
            {
                Repository = repo,
                CurrentBranch = repo.Head,
            }));
        }
    }
        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, arguments.NoFetch);
            }
            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");
                    //}
                }
            }
        }
        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, arguments.NoFetch);
            }
            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");
                    //}
                }
            }
        }
 SemanticVersion ExecuteGitVersion(GitVersionContext context)
 {
     var vf = new GitVersionFinder();
     return vf.FindVersion(context);
 }
    public void APullRequestBranchIsRequiredToBranchOffOfDevelopBranch()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            const string branchName = "pull/1735/merge";

            // Create a new unborn pull request branch sharing no history with "develop"
            repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName);

            AddOneCommitToHead(repo, "code");

            var pull = repo.Branches[branchName];

            var finder = new GitVersionFinder();

            Assert.Throws<ErrorException>(() => finder.FindVersion(new GitVersionContext
            {
                Repository = repo,
                CurrentBranch = pull,
            }));
        }
    }
Exemple #27
0
    public void NServiceBusHead()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Head;

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext(repository, branch, new Config()));
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
Exemple #28
0
        static void Main()
        {
            int?exitCode = null;

            try
            {
                Arguments arguments;
                var       argumentsWithoutExeName = GetArgumentsWithoutExeName();
                try
                {
                    arguments = ArgumentParser.ParseArguments(argumentsWithoutExeName);
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to parse arguments: {0}", string.Join(" ", argumentsWithoutExeName));

                    HelpWriter.Write();
                    return;
                }

                if (arguments.IsHelp)
                {
                    HelpWriter.Write();
                    return;
                }

                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);
                    Environment.Exit(1);
                }

                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);
                }
                SemanticVersion semanticVersion;
                using (var repo = RepositoryLoader.GetRepo(gitDirectory))
                {
                    semanticVersion = GitVersionFinder.GetSemanticVersion(repo);
                }

                if (arguments.Output == OutputType.BuildServer)
                {
                    foreach (var buildServer in applicableBuildServers)
                    {
                        buildServer.WriteIntegration(semanticVersion, Console.WriteLine);
                    }
                }

                var variables = VariableProvider.GetVariablesFor(semanticVersion);
                if (arguments.Output == OutputType.Json)
                {
                    switch (arguments.VersionPart)
                    {
                    case null:
                        Console.WriteLine(JsonOutputFormatter.ToJson(variables));
                        break;

                    default:
                        string part;
                        if (!variables.TryGetValue(arguments.VersionPart, out part))
                        {
                            throw new WarningException(string.Format("Could not extract '{0}' from the available parts.", arguments.VersionPart));
                        }
                        Console.WriteLine(part);
                        break;
                    }
                }

                using (var assemblyInfoUpdate = new AssemblyInfoFileUpdate(arguments, workingDirectory, variables))
                {
                    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");
                        //}
                    }
                }

                if (gitPreparer.IsDynamicGitRepository)
                {
                    DeleteHelper.DeleteGitRepository(gitPreparer.DynamicGitRepositoryPath);
                }
            }
            catch (WarningException exception)
            {
                var error = string.Format("An error occurred:\r\n{0}", exception.Message);
                Logger.WriteWarning(error);

                exitCode = 1;
            }
            catch (Exception exception)
            {
                var error = string.Format("An unexpected error occurred:\r\n{0}", exception);
                Logger.WriteError(error);

                exitCode = 1;
            }

            if (Debugger.IsAttached)
            {
                Console.ReadKey();
            }

            if (!exitCode.HasValue)
            {
                exitCode = 0;
            }
            else
            {
                // Dump log to console if we fail to complete successfully
                Console.Write(log.ToString());
            }

            Environment.Exit(exitCode.Value);
        }
        VersionVariables ExecuteInternal(string targetBranch, string commitId, GitPreparer gitPreparer, IBuildServer buildServer, Config overrideConfig = null)
        {
            var versionFinder = new GitVersionFinder();
            var configuration = ConfigurationProvider.Provide(gitPreparer, fileSystem, overrideConfig: overrideConfig);

            return gitPreparer.WithRepository(repo =>
            {
                var gitVersionContext = new GitVersionContext(repo, configuration, commitId: commitId);
                var semanticVersion = versionFinder.FindVersion(gitVersionContext);

                return VariableProvider.GetVariablesFor(semanticVersion, gitVersionContext.Configuration, gitVersionContext.IsCurrentCommitTagged);
            });
        }
Exemple #30
0
        static int Run()
        {
            try
            {
                Arguments arguments;
                var       argumentsWithoutExeName = GetArgumentsWithoutExeName();
                try
                {
                    arguments = ArgumentParser.ParseArguments(argumentsWithoutExeName);
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to parse arguments: {0}", string.Join(" ", argumentsWithoutExeName));

                    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);
                    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);
                }
                SemanticVersion semanticVersion;
                var             versionFinder = new GitVersionFinder();
                var             configuration = ConfigurationProvider.Provide(gitDirectory, fileSystem);
                using (var repo = RepositoryLoader.GetRepo(gitDirectory))
                {
                    var gitVersionContext = new GitVersionContext(repo, configuration);
                    semanticVersion = versionFinder.FindVersion(gitVersionContext);
                }

                if (arguments.Output == OutputType.BuildServer)
                {
                    foreach (var buildServer in applicableBuildServers)
                    {
                        buildServer.WriteIntegration(semanticVersion, Console.WriteLine);
                    }
                }

                var variables = VariableProvider.GetVariablesFor(semanticVersion, configuration);
                if (arguments.Output == OutputType.Json)
                {
                    switch (arguments.VersionPart)
                    {
                    case null:
                        Console.WriteLine(JsonOutputFormatter.ToJson(variables));
                        break;

                    default:
                        string part;
                        if (!variables.TryGetValue(arguments.VersionPart, out part))
                        {
                            throw new WarningException(string.Format("Could not extract '{0}' from the available parts.", arguments.VersionPart));
                        }
                        Console.WriteLine(part);
                        break;
                    }
                }

                if (!string.IsNullOrWhiteSpace(arguments.AssemblyVersionFormat) && !variables.ContainsKey(arguments.AssemblyVersionFormat))
                {
                    Console.WriteLine("Unrecognised AssemblyVersionFormat argument. Valid values for this argument are: {0}", string.Join(" ", variables.Keys.OrderBy(a => a)));
                    HelpWriter.Write();
                    return(1);
                }


                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");
                        //}
                    }
                }

                if (gitPreparer.IsDynamicGitRepository)
                {
                    DeleteHelper.DeleteGitRepository(gitPreparer.DynamicGitRepositoryPath);
                }
            }
            catch (WarningException exception)
            {
                var error = string.Format("An error occurred:\r\n{0}", exception.Message);
                Logger.WriteWarning(error);
                return(1);
            }
            catch (Exception exception)
            {
                var error = string.Format("An unexpected error occurred:\r\n{0}", exception);
                Logger.WriteError(error);
                return(1);
            }

            return(0);
        }
    public void RequiresALocalMasterBranch()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            repo.Branches["feature/one"].ForceCheckout();

            repo.Branches.Remove("master");

            var finder = new GitVersionFinder();

            Assert.Throws<WarningException>(() => finder.FindVersion(new GitVersionContext(repo)));
        }
    }
    public void NServiceBusHotfix()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "hotfix-4.1.1");

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext
            {
                Repository = repository,
                CurrentBranch = branch
            });
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
 public SemanticVersion ExecuteGitVersion()
 {
     var vf = new GitVersionFinder();
     return vf.FindVersion(new GitVersionContext(Repository));
 }
    public void NServiceBusNhibernate()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus.Nhibernate"))
        {
            var branch = repository.FindBranch("develop");

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext
            {
                Repository = repository,
                CurrentBranch = branch
            });
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
    public void NServiceBusReleaseSpecificCommit()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "release-4.1.0");
            repository.Checkout("c0e0a5e13775552cd3e08e039f453e4cf1fd4235");

            var finder = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext
            {
                Repository = repository,
                CurrentBranch = branch
            });
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
    public void TimingOnNSB()
    {
        var startNew = Stopwatch.StartNew();
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "develop");

            var finder = new GitVersionFinder();
            finder.FindVersion(new GitVersionContext
            {
                Repository = repository,
                CurrentBranch = branch
            });
        }
        Debug.WriteLine(startNew.ElapsedMilliseconds);
        startNew = Stopwatch.StartNew();
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "develop");

            var finder = new GitVersionFinder();
            finder.FindVersion(new GitVersionContext
            {
                Repository = repository,
                CurrentBranch = branch
            });
        }
        Debug.WriteLine(startNew.ElapsedMilliseconds);
    }
    public void AReleaseBranchIsRequiredToBranchOffOfDevelopBranch()
    {
        var repoPath = Clone(ASBMTestRepoWorkingDirPath);
        using (var repo = new Repository(repoPath))
        {
            const string branchName = "release/1.2.0";

            // Create a new unborn release branch sharing no history with "develop"
            repo.Refs.UpdateTarget(repo.Refs.Head.CanonicalName, "refs/heads/" + branchName);

            var path = Path.Combine(repo.Info.WorkingDirectory, "README");
            File.AppendAllText(path, "Release\n");

            repo.Index.Stage(path);
            var sign = SignatureBuilder.SignatureNow();
            repo.Commit("release unborn", sign, sign);

            var feature = repo.Branches[branchName];

            var finder = new GitVersionFinder();

            Assert.Throws<WarningException>(() => finder.FindVersion(new GitVersionContext(repo, feature)));
        }
    }