Ejemplo n.º 1
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");
                    GitTools.LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100);
                }
                return(1);
            }

            return(0);
        }
Ejemplo n.º 2
0
        private static bool Log(LogLevel loglevel, Func <string> messagefunc, Exception exception, object[] formatparameters)
        {
            // Create the main message. Careful of string format errors.
            string message;

            if (messagefunc == null)
            {
                message = null;
            }
            else
            {
                if (formatparameters == null || formatparameters.Length == 0)
                {
                    message = messagefunc();
                }
                else
                {
                    try
                    {
                        message = string.Format(messagefunc(), formatparameters);
                    }
                    catch (FormatException)
                    {
                        message = messagefunc();
                        Logger.WriteError(string.Format("LoggerWrapper.Log(): Incorrectly formatted string: message: '{0}'; formatparameters: {1}", message, string.Join(";", formatparameters)));
                    }
                }
            }

            if (exception != null)
            {
                // Append the exception to the end of the message.
                message = string.IsNullOrEmpty(message) ? exception.ToString() : string.Format("{0}\n{1}", message, exception);
            }

            if (!string.IsNullOrEmpty(message))
            {
                switch (loglevel)
                {
                case LogLevel.Trace:
                case LogLevel.Debug:
                    Logger.WriteDebug(message);
                    break;

                case LogLevel.Info:
                    Logger.WriteInfo(message);
                    break;

                case LogLevel.Warn:
                    Logger.WriteWarning(message);
                    break;

                case LogLevel.Error:
                case LogLevel.Fatal:
                    Logger.WriteError(message);
                    break;
                }
            }

            return(true);
        }
Ejemplo n.º 3
0
        static void ConfigureLogging(Arguments arguments)
        {
            var writeActions = new List <Action <string> >
            {
                s => log.AppendLine(s)
            };

            if (arguments.Output == OutputType.BuildServer || arguments.LogFilePath == "console" || arguments.Init)
            {
                writeActions.Add(Console.WriteLine);
            }

            Exception exception = null;

            if (arguments.LogFilePath != null && arguments.LogFilePath != "console")
            {
                try
                {
                    var logFileFullPath = Path.GetFullPath(arguments.LogFilePath);
                    var logFile         = new FileInfo(logFileFullPath);

                    // NOTE: logFile.Directory will be null if the path is i.e. C:\logfile.log. @asbjornu
                    if (logFile.Directory != null)
                    {
                        logFile.Directory.Create();
                    }

                    using (logFile.CreateText())
                    {
                    }

                    writeActions.Add(x => WriteLogEntry(arguments, x));
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            }

            Logger.SetLoggers(
                s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Debug)
                                                 {
                                                     a(s);
                                                 }
                                          }),
                s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Info)
                                                 {
                                                     a(s);
                                                 }
                                          }),
                s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Warn)
                                                 {
                                                     a(s);
                                                 }
                                          }),
                s => writeActions.ForEach(a => { if (arguments.Verbosity >= VerbosityLevel.Error)
                                                 {
                                                     a(s);
                                                 }
                                          }));

            if (exception != null)
            {
                Logger.WriteError(string.Format("Failed to configure logging for '{0}': {1}", arguments.LogFilePath, exception.Message));
            }
        }
Ejemplo n.º 4
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 NETDESKTOP
                if (arguments.Diag)
                {
                    Logger.WriteInfo("Dumping commit graph: ");
                    LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100);
                }
#endif
                if (!Directory.Exists(arguments.TargetPath))
                {
                    Logger.WriteWarning(string.Format("The working directory '{0}' does not exist.", arguments.TargetPath));
                }
                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 = 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("Attempting to show the current git graph (please include in issue): ");
                    Logger.WriteInfo("Showing max of 100 commits");

                    try
                    {
#if NETDESKTOP
                        LibGitExtensions.DumpGraph(arguments.TargetPath, Logger.WriteInfo, 100);
#endif
                    }
                    catch (Exception dumpGraphException)
                    {
                        Logger.WriteError("Couldn't dump the git graph due to the following error: " + dumpGraphException);
                    }
                }
                return(1);
            }

            return(0);
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        // based on https://msdn.microsoft.com/en-us/library/bb513869.aspx
        static List <string> CalculateDirectoryContents(string root)
        {
            var result = new List <string>();

            // Data structure to hold names of subfolders to be
            // examined for files.
            var dirs = new Stack <string>();

            if (!Directory.Exists(root))
            {
                throw new ArgumentException();
            }

            dirs.Push(root);

            while (dirs.Any())
            {
                string currentDir = dirs.Pop();

                var di = new DirectoryInfo(currentDir);
                result.Add(di.Name);

                string[] subDirs;
                try
                {
                    subDirs = Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable
                // to ignore the exception and continue enumerating the remaining files and
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The
                // choice of which exceptions to catch depends entirely on the specific task
                // you are intending to perform and also on how much you know with certainty
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException e)
                {
                    Logger.WriteError(e.Message);
                    continue;
                }
                catch (DirectoryNotFoundException e)
                {
                    Logger.WriteError(e.Message);
                    continue;
                }

                string[] files;
                try
                {
                    files = Directory.GetFiles(currentDir);
                }
                catch (UnauthorizedAccessException e)
                {
                    Logger.WriteError(e.Message);
                    continue;
                }
                catch (DirectoryNotFoundException e)
                {
                    Logger.WriteError(e.Message);
                    continue;
                }

                foreach (var file in files)
                {
                    try
                    {
                        var fi = new FileInfo(file);
                        result.Add(fi.Name);
                        result.Add(File.ReadAllText(file));
                    }
                    catch (IOException e)
                    {
                        Logger.WriteError(e.Message);
                    }
                }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                // push in reverse order
                for (var i = subDirs.Length - 1; i >= 0; i--)
                {
                    dirs.Push(subDirs[i]);
                }
            }

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

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

                ConfigureLogging(arguments);
                if (arguments.Init)
                {
                    ConfigurationProvider.WriteSample(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);
        }