Ejemplo n.º 1
0
        private static void WriteXmlDescriptorFiles(string rulePath, string profilePath, string lang)
        {
            var language = AnalyzerLanguage.Parse(lang);

            var genericRuleDetails = RuleDetailBuilder.GetAllRuleDetails(language).ToList();
            var ruleDetails        = genericRuleDetails.Select(RuleDetail.Convert).ToList();

            Directory.CreateDirectory(lang);

            WriteRuleDescriptorFile(Path.Combine(lang, rulePath), ruleDetails);
            WriteQualityProfileFile(Path.Combine(lang, profilePath), ruleDetails, language);
        }
Ejemplo n.º 2
0
        public static int Main(string[] args)
        {
            if (args.Length != 3)
            {
                Write("Expected parameters: ");
                Write("[Input configuration path]");
                Write("[Output file path]");
                Write("[AnalyzerLanguage: 'cs' for C#, 'vbnet' for VB.Net]");

                return(-1);
            }

            var language = AnalyzerLanguage.Parse(args[2]);

            Write($"SonarLint for Visual Studio version {typeof (Program).Assembly.GetName().Version}");

            var configuration     = new Configuration(args[0], language);
            var diagnosticsRunner = new DiagnosticsRunner(configuration);

            var xmlOutSettings = new XmlWriterSettings
            {
                Encoding    = Encoding.UTF8,
                Indent      = true,
                IndentChars = "  "
            };

            using (var xmlOut = XmlWriter.Create(args[1], xmlOutSettings))
            {
                xmlOut.WriteComment("This XML format is not an API");
                xmlOut.WriteStartElement("AnalysisOutput");

                xmlOut.WriteStartElement("Files");
                var n = 0;
                foreach (var file in configuration.Files)
                {
                    xmlOut.Flush();
                    Write(n + "/" + configuration.Files.Count() + " files analyzed, starting to analyze: " + file);
                    n++;

                    try
                    {
                        var solution = CompilationHelper.GetSolutionFromFiles(file, language);

                        var compilation = solution.Projects.First().GetCompilationAsync().Result;
                        var syntaxTree  = compilation.SyntaxTrees.First();

                        var metrics = language == AnalyzerLanguage.CSharp
                            ? (MetricsBase) new Common.CSharp.Metrics(syntaxTree)
                            : new Common.VisualBasic.Metrics(syntaxTree);

                        xmlOut.WriteStartElement("File");
                        xmlOut.WriteElementString("Path", file);

                        xmlOut.WriteStartElement("Metrics");

                        xmlOut.WriteElementString("Lines", metrics.GetLineCount().ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteElementString("Classes", metrics.GetClassCount().ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteElementString("Accessors", metrics.GetAccessorCount().ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteElementString("Statements", metrics.GetStatementCount().ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteElementString("Functions", metrics.GetFunctionCount().ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteElementString("PublicApi", metrics.GetPublicApiCount().ToString(CultureInfo.InvariantCulture));
                        xmlOut.WriteElementString("PublicUndocumentedApi", metrics.GetPublicUndocumentedApiCount().ToString(CultureInfo.InvariantCulture));

                        var complexity = metrics.GetComplexity();
                        xmlOut.WriteElementString("Complexity", complexity.ToString(CultureInfo.InvariantCulture));

                        // TODO This is a bit ridiculous, but is how SonarQube works
                        var fileComplexityDistribution = new Distribution(0, 5, 10, 20, 30, 60, 90);
                        fileComplexityDistribution.Add(complexity);
                        xmlOut.WriteElementString("FileComplexityDistribution", fileComplexityDistribution.ToString());

                        xmlOut.WriteElementString("FunctionComplexityDistribution", metrics.GetFunctionComplexityDistribution().ToString());

                        var comments = metrics.GetComments(configuration.IgnoreHeaderComments);
                        xmlOut.WriteStartElement("Comments");
                        xmlOut.WriteStartElement("NoSonar");
                        foreach (var line in comments.NoSonar)
                        {
                            xmlOut.WriteElementString("Line", line.ToString(CultureInfo.InvariantCulture));
                        }
                        xmlOut.WriteEndElement();
                        xmlOut.WriteStartElement("NonBlank");
                        foreach (var line in comments.NonBlank)
                        {
                            xmlOut.WriteElementString("Line", line.ToString(CultureInfo.InvariantCulture));
                        }
                        xmlOut.WriteEndElement();
                        xmlOut.WriteEndElement();

                        xmlOut.WriteStartElement("LinesOfCode");
                        foreach (var line in metrics.GetLinesOfCode())
                        {
                            xmlOut.WriteElementString("Line", line.ToString(CultureInfo.InvariantCulture));
                        }
                        xmlOut.WriteEndElement();

                        xmlOut.WriteEndElement();

                        xmlOut.WriteStartElement("Issues");

                        foreach (var diagnostic in diagnosticsRunner.GetDiagnostics(compilation))
                        {
                            xmlOut.WriteStartElement("Issue");
                            xmlOut.WriteElementString("Id", diagnostic.Id);
                            if (diagnostic.Location != Location.None)
                            {
                                xmlOut.WriteElementString("Line", (diagnostic.GetLineNumberToReport()).ToString(CultureInfo.InvariantCulture));
                            }
                            xmlOut.WriteElementString("Message", diagnostic.GetMessage());
                            xmlOut.WriteEndElement();
                        }

                        xmlOut.WriteEndElement();

                        xmlOut.WriteEndElement();
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("Failed to analyze the file: " + file);
                        Console.Error.WriteLine(e);
                        return(1);
                    }
                }

                xmlOut.WriteEndElement();

                xmlOut.WriteEndElement();
                xmlOut.WriteEndDocument();

                xmlOut.Flush();
                return(0);
            }
        }
Ejemplo n.º 3
0
        public static int RunAnalysis(ScannerAnalyzerConfiguration conf)
        {
            var language = AnalyzerLanguage.Parse(conf.Language);

            Write($"SonarAnalyzer for {language.GetFriendlyName()} version {FileVersionInfo.GetVersionInfo(typeof(Program).Assembly.Location).FileVersion}");

            var configuration     = new Configuration(conf.InputConfigurationPath, conf.WorkDirectoryConfigFilePath, language);
            var diagnosticsRunner = new DiagnosticsRunner(configuration);

            var outputDirectory = conf.OutputFolderPath;

            Directory.CreateDirectory(outputDirectory);

            var currentFileIndex = 0;

            using (var tokentypeStream = File.Create(Path.Combine(outputDirectory, Rules.TokenTypeAnalyzerBase.TokenTypeFileName)))
                using (var symRefStream = File.Create(Path.Combine(outputDirectory, Rules.SymbolReferenceAnalyzerBase.SymbolReferenceFileName)))
                    using (var cpdStream = File.Create(Path.Combine(outputDirectory, Rules.CopyPasteTokenAnalyzerBase.CopyPasteTokenFileName)))
                        using (var metricsStream = File.Create(Path.Combine(outputDirectory, Rules.MetricsAnalyzerBase.MetricsFileName)))
                            using (var encodingStream = File.Create(Path.Combine(outputDirectory, Rules.FileEncodingAnalyzerBase.EncodingFileName)))
                                using (var issuesStream = File.Create(Path.Combine(outputDirectory, IssuesFileName)))
                                {
                                    foreach (var file in configuration.Files)
                                    {
                                        #region Single file processing

                                        Write(currentFileIndex + "/" + configuration.Files.Count + " files analyzed, starting to analyze: " + file);
                                        currentFileIndex++;

                                        try
                                        {
                                            var solution = CompilationHelper.GetSolutionFromFiles(file, configuration.Encoding, language);

                                            var compilation = solution.Projects.First().GetCompilationAsync().Result;
                                            var syntaxTree  = compilation.SyntaxTrees.First();

                                            var tokenCollector = new TokenCollector(file, solution.GetDocument(syntaxTree));

                                            tokenCollector.TokenTypeInfo.WriteDelimitedTo(tokentypeStream);
                                            tokenCollector.SymbolReferenceInfo.WriteDelimitedTo(symRefStream);
                                            tokenCollector.CopyPasteTokenInfo.WriteDelimitedTo(cpdStream);

                                            MetricsBase metrics;
                                            Rules.FileEncodingAnalyzerBase encodingCalculator;

                                            if (language == AnalyzerLanguage.CSharp)
                                            {
                                                metrics            = new Common.CSharp.Metrics(syntaxTree);
                                                encodingCalculator = new Rules.CSharp.FileEncodingAnalyzer();
                                            }
                                            else
                                            {
                                                metrics            = new Common.VisualBasic.Metrics(syntaxTree);
                                                encodingCalculator = new Rules.VisualBasic.FileEncodingAnalyzer();
                                            }

                                            var metricsInfo = Rules.MetricsAnalyzerBase.CalculateMetrics(metrics, file, configuration.IgnoreHeaderComments);
                                            metricsInfo.WriteDelimitedTo(metricsStream);

                                            var encodingInfo = Rules.FileEncodingAnalyzerBase.CalculateEncoding(encodingCalculator, syntaxTree, file);
                                            encodingInfo.WriteDelimitedTo(encodingStream);

                                            var issuesInFile = new FileIssues
                                            {
                                                FilePath = file
                                            };

                                            foreach (var diagnostic in diagnosticsRunner.GetDiagnostics(compilation))
                                            {
                                                var issue = new FileIssues.Types.Issue
                                                {
                                                    Id      = diagnostic.Id,
                                                    Message = diagnostic.GetMessage()
                                                };

                                                if (diagnostic.Location != Location.None)
                                                {
                                                    issue.Location = Rules.UtilityAnalyzerBase.GetTextRange(diagnostic.Location.GetLineSpan());
                                                }

                                                issuesInFile.Issue.Add(issue);
                                            }

                                            if (issuesInFile.Issue.Any())
                                            {
                                                issuesInFile.WriteDelimitedTo(issuesStream);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Error.WriteLine("Failed to analyze the file: " + file);
                                            Console.Error.WriteLine(e);
                                            return(1);
                                        }

                                        #endregion
                                    }
                                }

            return(0);
        }
Ejemplo n.º 4
0
        public void AnalyzerLanguage_Parse_Fail()
        {
            var parsed = AnalyzerLanguage.Parse("csharp");

            parsed.Should().Be(AnalyzerLanguage.CSharp);
        }
        public void AnalyzerLanguage_Parse_Fail()
        {
            var parsed = AnalyzerLanguage.Parse("csharp");

            Assert.AreEqual(AnalyzerLanguage.CSharp, parsed);
        }
Ejemplo n.º 6
0
 public void AnalyzerLanguage_Parse_Fail() =>
 Assert.ThrowsException <NotSupportedException>(() => AnalyzerLanguage.Parse("csharp"));