Ejemplo n.º 1
0
        private static string GetConfigFileHash(IFileSystem fileSystem, GitPreparer gitPreparer)
        {
            // will return the same hash even when config file will be moved
            // from workingDirectory to rootProjectDirectory. It's OK. Config essentially is the same.
            var configFilePath = ConfigurationProvider.SelectConfigFilePath(gitPreparer, fileSystem);

            if (!fileSystem.Exists(configFilePath))
            {
                return(string.Empty);
            }

            var configFileContent = fileSystem.ReadAllText(configFilePath);

            return(GetHash(configFileContent));
        }
        /// <summary>
        /// Gets the <see cref="BranchConfig"/> for the current commit.
        /// </summary>
        public static BranchConfig GetBranchConfiguration(GitVersionContext context, Branch targetBranch, IList <Branch> excludedInheritBranches = null)
        {
            var matchingBranches = context.FullConfiguration.GetConfigForBranch(targetBranch.FriendlyName);

            if (matchingBranches == null)
            {
                Logger.WriteInfo(string.Format(
                                     "No branch configuration found for branch {0}, falling back to default configuration",
                                     targetBranch.FriendlyName));

                matchingBranches = new BranchConfig {
                    Name = string.Empty
                };
                ConfigurationProvider.ApplyBranchDefaults(context.FullConfiguration, matchingBranches, "", new List <string>());
            }

            return(matchingBranches.Increment == IncrementStrategy.Inherit ?
                   InheritBranchConfiguration(context, targetBranch, matchingBranches, excludedInheritBranches) :
                   matchingBranches);
        }
Ejemplo n.º 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, 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);
        }
Ejemplo n.º 4
0
        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");
                    //}
                }
            }
        }
Ejemplo n.º 5
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.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");
                    GitTools.LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100);
                }
                return(1);
            }

            return(0);
        }
Ejemplo n.º 6
0
        static int VerifyArgumentsAndRun()
        {
            try
            {
                var fileSystem = new FileSystem();

                Arguments arguments;
                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);
                    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);
                return(1);
            }

            return(0);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        static void VerifyConfiguration(Arguments arguments, IFileSystem fileSystem)
        {
            var gitPreparer = new GitPreparer(arguments.TargetUrl, arguments.DynamicRepositoryLocation, arguments.Authentication, arguments.NoFetch, arguments.TargetPath);

            ConfigurationProvider.Verify(gitPreparer, fileSystem);
        }
Ejemplo n.º 9
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);
        }
        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);
        }