Esempio n. 1
0
        public override async Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default)
        {
            AssemblyResolver.Register();

            var codeFixerOptions = new CodeFixerOptions(
                severityLevel: SeverityLevel,
                ignoreCompilerErrors: Options.IgnoreCompilerErrors,
                ignoreAnalyzerReferences: Options.IgnoreAnalyzerReferences,
                supportedDiagnosticIds: Options.SupportedDiagnostics,
                ignoredDiagnosticIds: Options.IgnoredDiagnostics,
                ignoredCompilerDiagnosticIds: Options.IgnoredCompilerDiagnostics,
                projectNames: Options.Projects,
                ignoredProjectNames: Options.IgnoredProjects,
                diagnosticIdsFixableOneByOne: Options.DiagnosticsFixableOneByOne,
                diagnosticFixMap: DiagnosticFixMap,
                diagnosticFixerMap: DiagnosticFixerMap,
                fileBanner: Options.FileBanner,
                language: Language,
                maxIterations: Options.MaxIterations,
                batchSize: Options.BatchSize,
                format: Options.Format);

            IEnumerable <AnalyzerAssembly> analyzerAssemblies = Options.AnalyzerAssemblies
                                                                .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(path).Select(info => info.AnalyzerAssembly));

            CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null;

            return(await FixAsync(projectOrSolution, analyzerAssemblies, codeFixerOptions, culture, cancellationToken));
        }
        public CommandResult Execute(AnalyzeAssemblyCommandLineOptions options)
        {
            var assemblies = new HashSet <Assembly>();

            AnalyzerAssemblyInfo[] analyzerAssemblies = options.GetPaths()
                                                        .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(
                                                                        path: path,
                                                                        loadAnalyzers: !options.NoAnalyzers,
                                                                        loadFixers: !options.NoFixers,
                                                                        language: Language))
                                                        .OrderBy(f => f.AnalyzerAssembly.Assembly.GetName().Name)
                                                        .ThenBy(f => f.FilePath)
                                                        .ToArray();

            for (int i = 0; i < analyzerAssemblies.Length; i++)
            {
                AnalyzerAssembly analyzerAssembly = analyzerAssemblies[i].AnalyzerAssembly;

                if (assemblies.Add(analyzerAssembly.Assembly))
                {
                    WriteLine(analyzerAssembly.FullName, ConsoleColor.Cyan, Verbosity.Minimal);

                    if (ShouldWrite(Verbosity.Normal))
                    {
                        WriteAnalyzerAssembly(analyzerAssemblies[i], DiagnosticMap.Create(analyzerAssembly));

                        if (i < analyzerAssemblies.Length - 1)
                        {
                            WriteLine(Verbosity.Normal);
                        }
                    }
                }
                else
                {
                    Write(analyzerAssembly.FullName, ConsoleColor.DarkGray, Verbosity.Minimal);
                    WriteLine($" [{analyzerAssemblies[i].FilePath}]", ConsoleColor.DarkGray, Verbosity.Minimal);
                }
            }

            if (ShouldWrite(Verbosity.Detailed) &&
                analyzerAssemblies.Length > 1)
            {
                DiagnosticMap map = DiagnosticMap.Create(analyzerAssemblies.Select(f => f.AnalyzerAssembly));

                WriteLine(Verbosity.Detailed);
                WriteDiagnostics(map, allProperties: true, useAssemblyQualifiedName: true);
            }

            WriteLine(Verbosity.Minimal);
            WriteLine($"{assemblies.Count} analyzer {((assemblies.Count == 1) ? "assembly" : "assemblies")} found", ConsoleColor.Green, Verbosity.Minimal);
            WriteLine(Verbosity.Minimal);

            if (options.Output != null &&
                analyzerAssemblies.Length > 0)
            {
                AnalyzerAssemblyXmlSerializer.Serialize(analyzerAssemblies, options.Output);
            }

            return(CommandResult.Success);
        }
Esempio n. 3
0
        public override async Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default)
        {
            AssemblyResolver.Register();

            var codeAnalyzerOptions = new CodeAnalyzerOptions(
                ignoreAnalyzerReferences: Options.IgnoreAnalyzerReferences,
                ignoreCompilerDiagnostics: Options.IgnoreCompilerDiagnostics,
                reportNotConfigurable: Options.ReportNotConfigurable,
                reportSuppressedDiagnostics: Options.ReportSuppressedDiagnostics,
                logAnalyzerExecutionTime: Options.ExecutionTime,
                severityLevel: SeverityLevel,
                supportedDiagnosticIds: Options.SupportedDiagnostics,
                ignoredDiagnosticIds: Options.IgnoredDiagnostics,
                projectNames: Options.Projects,
                ignoredProjectNames: Options.IgnoredProjects,
                language: Language);

            IEnumerable <AnalyzerAssembly> analyzerAssemblies = Options.AnalyzerAssemblies
                                                                .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(path, loadFixers: false).Select(info => info.AnalyzerAssembly));

            if (Options.UseRoslynatorAnalyzers)
            {
                analyzerAssemblies = analyzerAssemblies.Concat(AnalyzerAssemblyLoader.LoadFiles(RoslynatorAnalyzersAssemblies, loadFixers: false));
            }

            CultureInfo culture = (Options.Culture != null) ? CultureInfo.GetCultureInfo(Options.Culture) : null;

            var codeAnalyzer = new CodeAnalyzer(
                analyzerAssemblies: analyzerAssemblies,
                formatProvider: culture,
                options: codeAnalyzerOptions);

            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                WriteLine($"Analyze '{project.Name}'", ConsoleColor.Cyan, Verbosity.Minimal);

                Stopwatch stopwatch = Stopwatch.StartNew();

                ProjectAnalysisResult result = await codeAnalyzer.AnalyzeProjectAsync(project, cancellationToken);

                stopwatch.Stop();

                WriteLine($"Done analyzing project '{project.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal);

                if (Options.Output != null &&
                    result.Diagnostics.Any())
                {
                    DiagnosticXmlSerializer.Serialize(result, project, Options.Output, culture);
                }
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                ImmutableArray <ProjectAnalysisResult> results = await codeAnalyzer.AnalyzeSolutionAsync(solution, cancellationToken);

                if (Options.Output != null &&
                    results.Any(f => f.Diagnostics.Any()))
                {
                    DiagnosticXmlSerializer.Serialize(results, solution, Options.Output, culture);
                }
            }

            return(CommandResult.Success);
        }
Esempio n. 4
0
        public CommandStatus Execute(AnalyzeAssemblyCommandLineOptions options)
        {
            var assemblies = new HashSet <Assembly>();

            AnalyzerAssemblyInfo[] analyzerAssemblies = options.GetPaths()
                                                        .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(
                                                                        path: path,
                                                                        searchPattern: options.FileNamePattern ?? AnalyzerAssemblyLoader.DefaultSearchPattern,
                                                                        loadAnalyzers: !options.NoAnalyzers,
                                                                        loadFixers: !options.NoFixers,
                                                                        language: Language))
                                                        .OrderBy(f => f.AnalyzerAssembly.Assembly.GetName().Name)
                                                        .ThenBy(f => f.FilePath)
                                                        .ToArray();

            for (int i = 0; i < analyzerAssemblies.Length; i++)
            {
                AnalyzerAssembly analyzerAssembly = analyzerAssemblies[i].AnalyzerAssembly;

                if (assemblies.Add(analyzerAssembly.Assembly))
                {
                    WriteLine(analyzerAssembly.FullName, ConsoleColors.Cyan, Verbosity.Minimal);

                    if (ShouldWrite(Verbosity.Normal))
                    {
                        WriteAnalyzerAssembly(analyzerAssemblies[i], DiagnosticMap.Create(analyzerAssembly));

                        if (i < analyzerAssemblies.Length - 1)
                        {
                            WriteLine(Verbosity.Normal);
                        }
                    }
                }
                else
                {
                    Write(analyzerAssembly.FullName, ConsoleColors.DarkGray, Verbosity.Minimal);
                    WriteLine($" [{analyzerAssemblies[i].FilePath}]", ConsoleColors.DarkGray, Verbosity.Minimal);
                }
            }

            if (ShouldWrite(Verbosity.Detailed) &&
                analyzerAssemblies.Length > 1)
            {
                DiagnosticMap map = DiagnosticMap.Create(analyzerAssemblies.Select(f => f.AnalyzerAssembly));

                WriteLine(Verbosity.Detailed);
                WriteDiagnostics(map, allProperties: true, useAssemblyQualifiedName: true);
            }

            WriteLine(Verbosity.Minimal);
            WriteLine($"{assemblies.Count} analyzer {((assemblies.Count == 1) ? "assembly" : "assemblies")} found", ConsoleColors.Green, Verbosity.Minimal);

            if (analyzerAssemblies.Length > 0)
            {
                CultureInfo culture = (options.Culture != null) ? CultureInfo.GetCultureInfo(options.Culture) : null;

                foreach (string path in options.Output)
                {
                    WriteLine($"Save '{path}'", ConsoleColors.DarkGray, Verbosity.Diagnostic);

                    string extension = Path.GetExtension(path);

                    if (string.Equals(extension, ".xml", StringComparison.OrdinalIgnoreCase))
                    {
                        AnalyzerAssemblyXmlSerializer.Serialize(path, analyzerAssemblies, culture);
                    }
                    else if (string.Equals(extension, ".ruleset", StringComparison.OrdinalIgnoreCase))
                    {
                        WriteLine($"Save ruleset to '{path}'", ConsoleColors.DarkGray, Verbosity.Diagnostic);

                        using (var fileStream = new FileStream(path, FileMode.Create))
                            using (XmlWriter xmlWriter = XmlWriter.Create(fileStream, new XmlWriterSettings()
                            {
                                Indent = true, IndentChars = "  ", CloseOutput = false
                            }))
                            {
                                RuleSetUtility.WriteXml(
                                    writer: xmlWriter,
                                    analyzerAssemblies: analyzerAssemblies.Select(f => f.AnalyzerAssembly),
                                    name: "",
                                    toolsVersion: new Version(15, 0),
                                    description: null,
                                    formatProvider: culture);
                            }
                    }
                }
            }

            return((analyzerAssemblies.Length > 0) ? CommandStatus.Success : CommandStatus.NotSuccess);
        }
Esempio n. 5
0
        public CommandResult Execute(AnalyzeAssemblyCommandLineOptions options)
        {
            var assemblies = new HashSet <Assembly>();

            foreach (AnalyzerAssemblyInfo analyzerAssemblyInfo in options.GetPaths()
                     .SelectMany(path => AnalyzerAssemblyLoader.LoadFrom(
                                     path: path,
                                     loadAnalyzers: !options.NoAnalyzers,
                                     loadFixers: !options.NoFixers,
                                     language: Language))
                     .OrderBy(f => f.AnalyzerAssembly.GetName().Name)
                     .ThenBy(f => f.FilePath))
            {
                AnalyzerAssembly analyzerAssembly = analyzerAssemblyInfo.AnalyzerAssembly;
                string           filePath         = analyzerAssemblyInfo.FilePath;

                if (assemblies.Add(analyzerAssembly.Assembly))
                {
                    Write($"{analyzerAssembly.FullName}", ConsoleColor.Cyan, Verbosity.Minimal);
                    WriteLine($" [{filePath}]", Verbosity.Minimal);
                }
                else
                {
                    Write($"{analyzerAssembly.FullName}", ConsoleColor.DarkGray, Verbosity.Minimal);
                    WriteLine($" [{filePath}]", ConsoleColor.DarkGray, Verbosity.Minimal);
                    continue;
                }

                DiagnosticAnalyzer[] analyzers = analyzerAssembly
                                                 .Analyzers
                                                 .SelectMany(f => f.Value)
                                                 .Distinct()
                                                 .ToArray();

                if (analyzers.Length > 0)
                {
                    Write($"  {analyzers.Length} DiagnosticAnalyzers (", Verbosity.Normal);

                    using (IEnumerator <KeyValuePair <string, ImmutableArray <DiagnosticAnalyzer> > > en = analyzerAssembly.Analyzers.OrderBy(f => f.Key).GetEnumerator())
                    {
                        if (en.MoveNext())
                        {
                            while (true)
                            {
                                Write($"{en.Current.Value.Length} {GetShortLanguageName(en.Current.Key)}", Verbosity.Normal);

                                if (en.MoveNext())
                                {
                                    Write(", ");
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    WriteLine(")", Verbosity.Normal);

                    foreach (DiagnosticAnalyzer analyzer in analyzers.OrderBy(f => f.GetType().FullName))
                    {
                        Type type = analyzer.GetType();

                        DiagnosticAnalyzerAttribute attribute = type.GetCustomAttribute <DiagnosticAnalyzerAttribute>();

                        WriteLine($"    {type.FullName}", Verbosity.Detailed);
                        WriteLine($"      Supported Languages:   {string.Join(", ", attribute.Languages.Select(f => GetShortLanguageName(f)).OrderBy(f => f))}", ConsoleColor.DarkGray, Verbosity.Detailed);
                        WriteLine($"      Supported Diagnostics: {string.Join(", ", analyzer.SupportedDiagnostics.Select(f => f.Id).OrderBy(f => f))}", ConsoleColor.DarkGray, Verbosity.Detailed);
                    }
                }

                CodeFixProvider[] fixers = analyzerAssembly
                                           .Fixers
                                           .SelectMany(f => f.Value)
                                           .Distinct()
                                           .ToArray();

                if (fixers.Length > 0)
                {
                    Write($"  {fixers.Length} CodeFixProviders (", Verbosity.Normal);

                    using (IEnumerator <KeyValuePair <string, ImmutableArray <CodeFixProvider> > > en = analyzerAssembly.Fixers.OrderBy(f => f.Key).GetEnumerator())
                    {
                        if (en.MoveNext())
                        {
                            while (true)
                            {
                                Write($"{en.Current.Value.Length} {GetShortLanguageName(en.Current.Key)}", Verbosity.Normal);

                                if (en.MoveNext())
                                {
                                    Write(", ");
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    WriteLine(")", Verbosity.Normal);

                    foreach (CodeFixProvider fixer in fixers.OrderBy(f => f.GetType().FullName))
                    {
                        Type type = fixer.GetType();

                        ExportCodeFixProviderAttribute attribute = type.GetCustomAttribute <ExportCodeFixProviderAttribute>();

                        WriteLine($"    {type.FullName}", Verbosity.Detailed);
                        WriteLine($"      Supported Languages: {string.Join(", ", attribute.Languages.Select(f => GetShortLanguageName(f)).OrderBy(f => f))}", ConsoleColor.DarkGray, Verbosity.Detailed);
                        WriteLine($"      Fixable Diagnostics: {string.Join(", ", fixer.FixableDiagnosticIds.OrderBy(f => f))}", ConsoleColor.DarkGray, Verbosity.Detailed);

                        Write("      FixAllProvider:      ", ConsoleColor.DarkGray, Verbosity.Detailed);

                        FixAllProvider fixAllProvider = fixer.GetFixAllProvider();

                        if (fixAllProvider != null)
                        {
                            WriteLine($"{fixAllProvider.GetType().FullName} ({string.Join(", ", fixAllProvider.GetSupportedFixAllScopes().Select(f => f.ToString()).OrderBy(f => f))})", ConsoleColor.DarkGray, Verbosity.Detailed);
                        }
                        else
                        {
                            WriteLine("-", ConsoleColor.DarkGray, Verbosity.Detailed);
                        }
                    }
                }
            }

            WriteLine(Verbosity.Minimal);
            WriteLine($"{assemblies.Count} analyzer {((assemblies.Count == 1) ? "assembly" : "assemblies")} found", ConsoleColor.Green, Verbosity.Minimal);
            WriteLine(Verbosity.Minimal);

            return(CommandResult.Success);
        }