private int VerifyArgumentsAndRun(Arguments arguments)
        {
            try
            {
                if (HandleNonMainCommand(arguments, out var exitCode))
                {
                    return(exitCode);
                }

                gitPreparer.Prepare();
                var variables = gitVersionCalculator.CalculateVersionVariables();
                execCommand.Execute(variables);
            }
            catch (WarningException exception)
            {
                var error = $"An error occurred:{System.Environment.NewLine}{exception.Message}";
                log.Warning(error);
                return(1);
            }
            catch (Exception exception)
            {
                var error = $"An unexpected error occurred:{System.Environment.NewLine}{exception}";
                log.Error(error);

                if (arguments == null)
                {
                    return(1);
                }

                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);
        }
Example #2
0
        private int RunGitVersionTool(GitVersionOptions gitVersionOptions)
        {
            try
            {
                var variables = gitVersionTool.CalculateVersionVariables();

                gitVersionTool.OutputVariables(variables);
                gitVersionTool.UpdateAssemblyInfo(variables);
                gitVersionTool.UpdateWixVersionFile(variables);

                execCommand.Execute(variables);
            }
            catch (WarningException exception)
            {
                var error = $"An error occurred:{System.Environment.NewLine}{exception.Message}";
                log.Warning(error);
                return(1);
            }
            catch (Exception exception)
            {
                var error = $"An unexpected error occurred:{System.Environment.NewLine}{exception}";
                log.Error(error);

                if (gitVersionOptions == null)
                {
                    return(1);
                }

                log.Info("Attempting to show the current git graph (please include in issue): ");
                log.Info("Showing max of 100 commits");

                try
                {
                    LibGitExtensions.DumpGraph(gitVersionOptions.WorkingDirectory, 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);
        }
Example #3
0
        private int VerifyArgumentsAndRun(Arguments arguments)
        {
            try
            {
                if (arguments == null)
                {
                    helpWriter.Write();
                    return(1);
                }
                var targetPath = arguments.TargetPath;

                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;
                }

                var buildServer = buildServerResolver.Resolve();
                arguments.NoFetch = arguments.NoFetch || buildServer != null && buildServer.PreventFetch();

                ConfigureLogging(arguments, log);

                if (arguments.Diag)
                {
                    log.Info("Dumping commit graph: ");
                    LibGitExtensions.DumpGraph(targetPath, mess => log.Info(mess), 100);
                }
                if (!Directory.Exists(targetPath))
                {
                    log.Warning($"The working directory '{targetPath}' does not exist.");
                }
                else
                {
                    log.Info("Working directory: " + targetPath);
                }

                VerifyConfiguration();

                if (arguments.Init)
                {
                    configProvider.Init(targetPath);
                    return(0);
                }
                if (arguments.ShowConfig)
                {
                    var config = configProvider.Provide(targetPath);
                    Console.WriteLine(config.ToString());
                    return(0);
                }

                execCommand.Execute();
            }
            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);
        }
Example #4
0
        private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int exitCode)
        {
            if (gitVersionOptions == null)
            {
                helpWriter.Write();
                exitCode = 1;
                return(true);
            }


            if (gitVersionOptions.IsVersion)
            {
                var assembly = Assembly.GetExecutingAssembly();
                versionWriter.Write(assembly);
                exitCode = 0;
                return(true);
            }

            if (gitVersionOptions.IsHelp)
            {
                helpWriter.Write();
                exitCode = 0;
                return(true);
            }

            if (gitVersionOptions.Diag)
            {
                gitVersionOptions.Settings.NoCache = true;
                gitVersionOptions.Output.Add(OutputType.BuildServer);
            }

#pragma warning disable CS0612 // Type or member is obsolete
            if (!string.IsNullOrEmpty(gitVersionOptions.Proj) || !string.IsNullOrEmpty(gitVersionOptions.Exec))
#pragma warning restore CS0612 // Type or member is obsolete
            {
                gitVersionOptions.Output.Add(OutputType.BuildServer);
            }

            ConfigureLogging(gitVersionOptions, log);

            var workingDirectory = gitVersionOptions.WorkingDirectory;
            if (gitVersionOptions.Diag)
            {
                log.Info("Dumping commit graph: ");
                LibGitExtensions.DumpGraph(workingDirectory, mess => log.Info(mess), 100);
            }

            if (!Directory.Exists(workingDirectory))
            {
                log.Warning($"The working directory '{workingDirectory}' does not exist.");
            }
            else
            {
                log.Info("Working directory: " + workingDirectory);
            }

            configFileLocator.Verify(gitVersionOptions);

            if (gitVersionOptions.Init)
            {
                configProvider.Init(workingDirectory);
                exitCode = 0;
                return(true);
            }

            if (gitVersionOptions.ConfigInfo.ShowConfig)
            {
                var config = configProvider.Provide(workingDirectory);
                console.WriteLine(config.ToString());
                exitCode = 0;
                return(true);
            }

            exitCode = 0;
            return(false);
        }
        private bool HandleNonMainCommand(Arguments arguments, out int exitCode)
        {
            if (arguments == null)
            {
                helpWriter.Write();
                exitCode = 1;
                return(true);
            }

            var targetPath = arguments.TargetPath;

            if (arguments.IsVersion)
            {
                var assembly = Assembly.GetExecutingAssembly();
                versionWriter.Write(assembly);
                exitCode = 0;
                return(true);
            }

            if (arguments.IsHelp)
            {
                helpWriter.Write();
                exitCode = 0;
                return(true);
            }

            if (arguments.Diag)
            {
                arguments.NoCache = true;
                arguments.Output.Add(OutputType.BuildServer);
            }

#pragma warning disable CS0612 // Type or member is obsolete
            if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec))
#pragma warning restore CS0612 // Type or member is obsolete
            {
                arguments.Output.Add(OutputType.BuildServer);
            }

            var buildServer = buildServerResolver.Resolve();
            arguments.NoFetch = arguments.NoFetch || buildServer != null && buildServer.PreventFetch();

            ConfigureLogging(arguments, log);

            if (arguments.Diag)
            {
                log.Info("Dumping commit graph: ");
                LibGitExtensions.DumpGraph(targetPath, mess => log.Info(mess), 100);
            }

            if (!Directory.Exists(targetPath))
            {
                log.Warning($"The working directory '{targetPath}' does not exist.");
            }
            else
            {
                log.Info("Working directory: " + targetPath);
            }

            configFileLocator.Verify(gitPreparer);

            if (arguments.Init)
            {
                configProvider.Init(targetPath);
                exitCode = 0;
                return(true);
            }

            if (arguments.ShowConfig)
            {
                var config = configProvider.Provide(targetPath);
                Console.WriteLine(config.ToString());
                exitCode = 0;
                return(true);
            }

            exitCode = 0;
            return(false);
        }
Example #6
0
        static int VerifyArgumentsAndRun()
        {
            Arguments arguments = null;

            try
            {
                var fileSystem = new FileSystem();
                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();
                    }

                    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;
                }

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

                if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec))
                {
                    arguments.Output = OutputType.BuildServer;
                }

                SpecifiedArgumentRunner.Run(arguments, fileSystem);
            }
            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);
            }

            return(0);
        }
        /// <summary>
        /// Normalization 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 normalization against a local repository
        /// </summary>
        private void NormalizeGitDirectory(string gitDirectory, bool noFetch, string currentBranch, bool isDynamicRepository)
        {
            var authentication = options.Value.Authentication;

            using var repository = new Repository(gitDirectory);
            // Need to ensure the HEAD does not move, this is essentially a BugCheck
            var expectedSha        = repository.Head.Tip.Sha;
            var expectedBranchName = repository.Head.CanonicalName;

            try
            {
                var remote = repository.EnsureOnlyOneRemoteIsDefined(log);

                repository.AddMissingRefSpecs(log, 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)
                {
                    log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
                }
                else
                {
                    log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}.");
                    Commands.Fetch(repository, remote.Name, new string[0], authentication.ToFetchOptions(), null);
                }

                repository.EnsureLocalBranchExistsForCurrentBranch(log, remote, currentBranch);
                repository.CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, remote.Name);

                // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
                // if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
                if (expectedSha != repository.Head.Tip.Sha &&
                    (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
                {
                    var newExpectedSha        = repository.Head.Tip.Sha;
                    var newExpectedBranchName = repository.Head.CanonicalName;

                    log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");

                    expectedSha = newExpectedSha;
                }

                var headSha = repository.Refs.Head.TargetIdentifier;

                if (!repository.Info.IsHeadDetached)
                {
                    log.Info($"HEAD points at branch '{headSha}'.");
                    return;
                }

                log.Info($"HEAD is detached and points at commit '{headSha}'.");
                log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, repository.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})")));

                // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
                // If they do, go ahead and checkout that branch
                // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
                var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

                var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
                    ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
                    : null;
                if (matchingCurrentBranch != null)
                {
                    log.Info($"Checking out local branch '{currentBranch}'.");
                    Commands.Checkout(repository, matchingCurrentBranch);
                }
                else if (localBranchesWhereCommitShaIsHead.Count > 1)
                {
                    var          branchNames   = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
                    var          csvNames      = string.Join(", ", branchNames);
                    const string moveBranchMsg = "Move one of the branches along a commit to remove warning";

                    log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
                    var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
                    if (master != null)
                    {
                        log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
                        Commands.Checkout(repository, master);
                    }
                    else
                    {
                        var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
                        if (branchesWithoutSeparators.Count == 1)
                        {
                            var branchWithoutSeparator = branchesWithoutSeparators[0];
                            log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
                            Commands.Checkout(repository, branchWithoutSeparator);
                        }
                        else
                        {
                            throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
                        }
                    }
                }
                else if (localBranchesWhereCommitShaIsHead.Count == 0)
                {
                    log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
                    repository.CreateFakeBranchPointingAtThePullRequestTip(log, authentication);
                }
                else
                {
                    log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
                    Commands.Checkout(repository, repository.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
                }
            }
            finally
            {
                if (repository.Head.Tip.Sha != expectedSha)
                {
                    if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
                    {
                        // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
                        throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.

To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1

Please run `git {LibGitExtensions.CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
                    }
                }
            }
        }
        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);
        }
Example #9
0
        static int VerifyArgumentsAndRun()
        {
            Arguments arguments = null;

            try
            {
                var fileSystem = new FileSystem();

                var argumentsWithoutExeName = GetArgumentsWithoutExeName();
                try
                {
                    arguments = ArgumentParser.ParseArguments(argumentsWithoutExeName);
                }
                catch (WarningException ex)
                {
                    Console.WriteLine("Failed to parse arguments: {0}", string.Join(" ", argumentsWithoutExeName));
                    if (!string.IsNullOrWhiteSpace(ex.Message))
                    {
                        Console.WriteLine();
                        Console.WriteLine(ex.Message);
                        Console.WriteLine();
                    }

                    HelpWriter.Write();
                    return(1);
                }
                catch (Exception)
                {
                    Console.WriteLine("Failed to parse arguments: {0}", string.Join(" ", argumentsWithoutExeName));

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

                ConfigureLogging(arguments);
                if (arguments.Init)
                {
                    ConfigurationProvider.Init(arguments.TargetPath, fileSystem, new ConsoleAdapter());
                    return(0);
                }
                if (arguments.ShowConfig)
                {
                    Console.WriteLine(ConfigurationProvider.GetEffectiveConfigAsString(arguments.TargetPath, fileSystem));
                    return(0);
                }

                if (!string.IsNullOrEmpty(arguments.Proj) || !string.IsNullOrEmpty(arguments.Exec))
                {
                    arguments.Output = OutputType.BuildServer;
                }

                Logger.WriteInfo("Working directory: " + arguments.TargetPath);

                SpecifiedArgumentRunner.Run(arguments, fileSystem);
            }
            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);

                if (arguments != null)
                {
                    Logger.WriteInfo(string.Empty);
                    Logger.WriteInfo("Here is the current git graph (please include in issue): ");
                    Logger.WriteInfo("Showing max of 100 commits");
                    LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100);
                }
                return(1);
            }

            return(0);
        }