示例#1
0
            ErrorCode writeOutput()
            {
                XmlTextWriter?metricFile = null;

                try
                {
                    // Create the writer
                    if (outputFile != null)
                    {
                        if (!quiet)
                        {
                            Console.WriteLine($"Writing output to '{outputFile}'...");
                        }
                        metricFile = new XmlTextWriter(outputFile, Encoding.UTF8);
                    }
                    else
                    {
                        metricFile = new XmlTextWriter(Console.OpenStandardOutput(), Console.OutputEncoding);
                    }

                    MetricsOutputWriter.WriteMetricFile(metricDatas, metricFile);
                    if (outputFile == null)
                    {
                        metricFile.WriteString(Environment.NewLine + Environment.NewLine);
                    }

                    return(ErrorCode.None);
                }
#pragma warning disable CA1031 // Do not catch general exception types - gracefully catch exceptions and log them to the console and output file.
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(ErrorCode.WriteException);
                }
#pragma warning restore CA1031 // Do not catch general exception types
                finally
                {
                    if (metricFile != null)
                    {
                        metricFile.Close();
                    }
                }
            }
示例#2
0
        private static async Task <ErrorCode> RunAsync(string[] args, CancellationToken cancellationToken)
        {
            var    projectsOrSolutions = new List <string>();
            string outputFile          = null;
            bool   quiet = false;

            if (args.Length == 0)
            {
                return(usage());
            }

            var errorCode = parseArguments();

            if (errorCode != ErrorCode.None)
            {
                return(errorCode);
            }

            cancellationToken.ThrowIfCancellationRequested();
            MSBuildLocator.RegisterDefaults();

            cancellationToken.ThrowIfCancellationRequested();
            (ImmutableArray <(string, CodeAnalysisMetricData)> metricDatas, ErrorCode exitCode) = await GetMetricDatasAsync(projectsOrSolutions, quiet, cancellationToken).ConfigureAwait(false);

            if (exitCode != ErrorCode.None)
            {
                return(exitCode);
            }

            cancellationToken.ThrowIfCancellationRequested();
            errorCode = writeOutput();
            if (!quiet && errorCode == ErrorCode.None)
            {
                Console.WriteLine("Completed Successfully.");
            }

            return(errorCode);

            ErrorCode parseArguments()
            {
                // Parse arguments
                for (int i = 0; i < args.Length; i++)
                {
                    var arg = args[i];
                    if (!arg.StartsWith("/", StringComparison.Ordinal) && !arg.StartsWith("-", StringComparison.Ordinal))
                    {
                        return(usage());
                    }

                    arg = arg.Substring(1);
                    switch (arg.ToUpperInvariant())
                    {
                    case "Q":
                    case "QUIET":
                        quiet = true;
                        continue;

                    case "?":
                    case "HELP":
                        return(usage());

                    default:
                        var index = arg.IndexOf(':');
                        if (index == -1 || index == arg.Length - 1)
                        {
                            return(usage());
                        }

                        var key   = arg.Substring(0, index).ToUpperInvariant();
                        var value = arg.Substring(index + 1);
                        switch (key)
                        {
                        case "P":
                        case "PROJECT":
                            if (!File.Exists(value))
                            {
                                return(fileNotExists(value));
                            }

                            if (!value.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase) &&
                                !value.EndsWith(".vbproj", StringComparison.OrdinalIgnoreCase))
                            {
                                return(notASupportedProject(value));
                            }

                            projectsOrSolutions.Add(value);
                            break;

                        case "S":
                        case "SOLUTION":
                            if (!File.Exists(value))
                            {
                                return(fileNotExists(value));
                            }

                            if (!value.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
                            {
                                return(notASolution(value));
                            }

                            projectsOrSolutions.Add(value);
                            break;

                        case "O":
                        case "OUT":
                            if (value.Length == 0)
                            {
                                return(invalidOutputFile(value));
                            }

                            outputFile = value;
                            break;

                        default:
                            return(usage());
                        }

                        break;
                    }
                }

                if (projectsOrSolutions.Count == 0)
                {
                    return(requiresProjectOrSolution());
                }

                return(ErrorCode.None);
            }

            ErrorCode usage()
            {
                Console.WriteLine(@"
Usage: Metrics.exe <arguments>

Help for command-line arguments:

/project:<project-file>  [Short form: /p:<project-file>]
Project(s) to analyze.

/solution:<solution-file>  [Short form: /s:<solution-file>]
Solution(s) to analyze.

/out:<file>  [Short form: /o:<file>]
Metrics results XML output file.

/quiet  [Short form: /q]
Silence all console output other than error reporting.

/help  [Short form: /?]
Display this help message.");
                return(ErrorCode.Usage);
            }

            ErrorCode fileNotExists(string path)
            {
                Console.WriteLine($"Error: File '{path}' does not exist.");
                return(ErrorCode.FileNotExists);
            }

            ErrorCode requiresProjectOrSolution()
            {
                Console.WriteLine($"Error: No project or solution provided.");
                return(ErrorCode.RequiresProjectOrSolution);
            }

            ErrorCode notASolution(string path)
            {
                Console.WriteLine($"Error: File '{path}' is not a solution file.");
                return(ErrorCode.NotASolution);
            }

            ErrorCode notASupportedProject(string path)
            {
                Console.WriteLine($"Error: File '{path}' is not a C# or VB project file.");
                return(ErrorCode.NotASupportedProject);
            }

            ErrorCode invalidOutputFile(string path)
            {
                Console.WriteLine($"Error: File '{path}' is not a valid output file.");
                return(ErrorCode.InvalidOutputFile);
            }

            ErrorCode writeOutput()
            {
                XmlTextWriter metricFile = null;

                try
                {
                    // Create the writer
                    if (outputFile != null)
                    {
                        if (!quiet)
                        {
                            Console.WriteLine($"Writing output to '{outputFile}'...");
                        }
                        metricFile = new XmlTextWriter(outputFile, Encoding.UTF8);
                    }
                    else
                    {
                        metricFile = new XmlTextWriter(Console.OpenStandardOutput(), Console.OutputEncoding);
                    }

                    MetricsOutputWriter.WriteMetricFile(metricDatas, metricFile);
                    if (outputFile == null)
                    {
                        metricFile.WriteString(Environment.NewLine + Environment.NewLine);
                    }

                    return(ErrorCode.None);
                }
#pragma warning disable CA1031 // Do not catch general exception types - gracefully catch exceptions and log them to the console and output file.
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return(ErrorCode.WriteException);
                }
#pragma warning restore CA1031 // Do not catch general exception types
                finally
                {
                    if (metricFile != null)
                    {
                        metricFile.Close();
                    }
                }
            }
        }