Exemplo 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 override async Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default)
        {
            var codeMetricsOptions = new CodeMetricsOptions(includeGenerated: Options.IncludeGeneratedCode);

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

                CodeMetricsCounter counter = CodeMetricsCounterFactory.GetLogicalLinesCounter(project.Language);

                if (counter != null)
                {
                    await CountLinesAsync(project, counter, codeMetricsOptions, cancellationToken);
                }
                else
                {
                    WriteLine($"Cannot count logical lines for language '{project.Language}'", ConsoleColor.Yellow, Verbosity.Minimal);
                }
            }
            else
            {
                CountLines(projectOrSolution.AsSolution(), codeMetricsOptions, cancellationToken);
            }

            return(CommandResult.Success);
        }
        public override async Task<CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default)
        {
            var codeMetricsOptions = new CodeMetricsOptions(
                includeGenerated: Options.IncludeGeneratedCode,
                includeWhitespace: Options.IncludeWhitespace,
                includeComments: Options.IncludeComments,
                includePreprocessorDirectives: Options.IncludePreprocessorDirectives,
                ignoreBlockBoundary: Options.IgnoreBlockBoundary);

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

                ICodeMetricsService service = MefWorkspaceServices.Default.GetService<ICodeMetricsService>(project.Language);

                if (service != null)
                {
                    await CountLinesAsync(project, service, codeMetricsOptions, cancellationToken);
                }
                else
                {
                    WriteLine($"Cannot count lines for '{project.FilePath}', language '{project.Language}' is not supported", ConsoleColor.Yellow, Verbosity.Minimal);
                }
            }
            else
            {
                CountLines(projectOrSolution.AsSolution(), codeMetricsOptions, cancellationToken);
            }

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

            ImmutableArray <UnusedSymbolInfo> allUnusedSymbols;

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

                allUnusedSymbols = await AnalyzeProject(project, cancellationToken);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                ImmutableArray <UnusedSymbolInfo> .Builder unusedSymbols = null;

                foreach (Project project in FilterProjects(solution, Options, s => s
                                                           .GetProjectDependencyGraph()
                                                           .GetTopologicallySortedProjects(cancellationToken)
                                                           .ToImmutableArray()))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    ImmutableArray <UnusedSymbolInfo> unusedSymbols2 = await AnalyzeProject(project, cancellationToken);

                    if (unusedSymbols2.Any())
                    {
                        (unusedSymbols ?? (unusedSymbols = ImmutableArray.CreateBuilder <UnusedSymbolInfo>())).AddRange(unusedSymbols2);
                    }
                }

                allUnusedSymbols = unusedSymbols?.ToImmutableArray() ?? ImmutableArray <UnusedSymbolInfo> .Empty;
            }

            if (allUnusedSymbols.Any())
            {
                WriteLine(Verbosity.Normal);

                Dictionary <UnusedSymbolKind, int> countByKind = allUnusedSymbols
                                                                 .GroupBy(f => UnusedSymbolFinder.GetUnusedSymbolKind(f.Symbol))
                                                                 .OrderByDescending(f => f.Count())
                                                                 .ThenBy(f => f.Key)
                                                                 .ToDictionary(f => f.Key, f => f.Count());

                int maxCountLength = countByKind.Sum(f => f.Value.ToString().Length);

                foreach (KeyValuePair <UnusedSymbolKind, int> kvp in countByKind)
                {
                    WriteLine($"{kvp.Value.ToString().PadLeft(maxCountLength)} {kvp.Key.ToString().ToLowerInvariant()} symbols", Verbosity.Normal);
                }
            }

            WriteLine(Verbosity.Minimal);
            WriteLine($"{allUnusedSymbols.Length} unused {((allUnusedSymbols.Length == 1) ? "symbol" : "symbols")} found", ConsoleColor.Green, Verbosity.Minimal);
            WriteLine(Verbosity.Minimal);

            return(CommandResult.Success);
        }
Exemplo n.º 5
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 <string> analyzerAssemblies = Options.AnalyzerAssemblies;

            if (Options.UseRoslynatorAnalyzers)
            {
                analyzerAssemblies = analyzerAssemblies.Concat(RoslynatorAnalyzersAssemblies);
            }

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

            var codeAnalyzer = new CodeAnalyzer(
                analyzerAssemblies: AnalyzerAssemblyLoader.LoadFiles(analyzerAssemblies, loadFixers: false),
                formatProvider: culture,
                options: codeAnalyzerOptions);

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

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

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

                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);
        }
Exemplo n.º 6
0
        internal static async Task <CommandResult> FixAsync(
            ProjectOrSolution projectOrSolution,
            IEnumerable <string> analyzerAssemblies,
            CodeFixerOptions codeFixerOptions,
            IFormatProvider formatProvider      = null,
            CancellationToken cancellationToken = default)
        {
            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                Solution solution = project.Solution;

                var codeFixer = new CodeFixer(solution, SyntaxFactsServiceFactory.Instance, analyzerAssemblies: analyzerAssemblies, formatProvider: formatProvider, options: codeFixerOptions);

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

                await codeFixer.FixProjectAsync(project, cancellationToken);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                var codeFixer = new CodeFixer(solution, SyntaxFactsServiceFactory.Instance, analyzerAssemblies: analyzerAssemblies, options: codeFixerOptions);

                await codeFixer.FixSolutionAsync(cancellationToken);
            }

            return(CommandResult.Success);
        }
Exemplo n.º 7
0
        public override async Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default)
        {
            ImmutableArray <string> supportedDiagnosticIds = Options
                                                             .GetSupportedDiagnostics()
                                                             .Select(f => f.Id)
                                                             .ToImmutableArray();

            if (supportedDiagnosticIds.Any())
            {
                var codeFixerOptions = new CodeFixerOptions(
                    severityLevel: DiagnosticSeverity.Hidden,
                    ignoreCompilerErrors: true,
                    ignoreAnalyzerReferences: true,
                    supportedDiagnosticIds: supportedDiagnosticIds,
                    projectNames: Options.Projects,
                    ignoredProjectNames: Options.IgnoredProjects,
                    language: Language,
                    batchSize: 1000,
                    format: true);

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

                return(await FixCommand.FixAsync(
                           projectOrSolution,
                           RoslynatorAnalyzerAssemblies.AnalyzersAndCodeFixes,
                           codeFixerOptions,
                           culture,
                           cancellationToken));
            }
            else if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                var options = new CodeFormatterOptions(includeGeneratedCode: Options.IncludeGeneratedCode);

                await FormatProjectAsync(project, options, cancellationToken);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                var options = new CodeFormatterOptions(includeGeneratedCode: Options.IncludeGeneratedCode);

                await FormatSolutionAsync(solution, options, cancellationToken);
            }

            return(CommandResult.Success);
        }
Exemplo n.º 8
0
        internal static async Task <CommandResult> FixAsync(
            ProjectOrSolution projectOrSolution,
            IEnumerable <AnalyzerAssembly> analyzerAssemblies,
            CodeFixerOptions codeFixerOptions,
            IFormatProvider formatProvider      = null,
            CancellationToken cancellationToken = default)
        {
            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                Solution solution = project.Solution;

                CodeFixer codeFixer = GetCodeFixer(solution);

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

                Stopwatch stopwatch = Stopwatch.StartNew();

                await codeFixer.FixProjectAsync(project, cancellationToken);

                stopwatch.Stop();

                WriteLine($"Done fixing project '{project.FilePath}' in {stopwatch.Elapsed:mm\\:ss\\.ff}", Verbosity.Minimal);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                CodeFixer codeFixer = GetCodeFixer(solution);

                await codeFixer.FixSolutionAsync(cancellationToken);
            }

            return(CommandResult.Success);

            CodeFixer GetCodeFixer(Solution solution)
            {
                return(new CodeFixer(
                           solution,
                           analyzerAssemblies: analyzerAssemblies,
                           formatProvider: formatProvider,
                           options: codeFixerOptions));
            }
        }
Exemplo n.º 9
0
        internal static async Task <CommandResult> FixAsync(
            ProjectOrSolution projectOrSolution,
            IEnumerable <string> analyzerAssemblies,
            CodeFixerOptions codeFixerOptions,
            IFormatProvider formatProvider      = null,
            CancellationToken cancellationToken = default)
        {
            if (projectOrSolution.IsProject)
            {
                Project project = projectOrSolution.AsProject();

                Solution solution = project.Solution;

                CodeFixer codeFixer = GetCodeFixer(solution);

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

                await codeFixer.FixProjectAsync(project, cancellationToken);
            }
            else
            {
                Solution solution = projectOrSolution.AsSolution();

                CodeFixer codeFixer = GetCodeFixer(solution);

                await codeFixer.FixSolutionAsync(cancellationToken);
            }

            return(CommandResult.Success);

            CodeFixer GetCodeFixer(Solution solution)
            {
                return(new CodeFixer(
                           solution,
                           analyzerAssemblies: AnalyzerAssemblyLoader.LoadFiles(analyzerAssemblies),
                           formatProvider: formatProvider,
                           options: codeFixerOptions));
            }
        }
        public async Task <CommandResult> ExecuteAsync(string path, string msbuildPath = null, IEnumerable <string> properties = null)
        {
            MSBuildWorkspace workspace = null;

            try
            {
                workspace = CreateMSBuildWorkspace(msbuildPath, properties);

                if (workspace == null)
                {
                    return(CommandResult.Fail);
                }

                workspace.WorkspaceFailed += WorkspaceFailed;

                var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, e) =>
                {
                    e.Cancel = true;
                    cts.Cancel();
                };

                CancellationToken cancellationToken = cts.Token;

                try
                {
                    CommandResult result = await ExecuteAsync(path, workspace, ConsoleProgressReporter.Default, cancellationToken);

                    if (result.Kind != CommandResultKind.None)
                    {
                        return(result);
                    }

                    ProjectOrSolution projectOrSolution = await OpenProjectOrSolutionAsync(path, workspace, ConsoleProgressReporter.Default, cancellationToken);

                    if (projectOrSolution != default)
                    {
                        return(await ExecuteAsync(projectOrSolution, cancellationToken));
                    }
                }
                catch (OperationCanceledException ex)
                {
                    OperationCanceled(ex);
                }
                catch (AggregateException ex)
                {
                    OperationCanceledException operationCanceledException = ex.GetOperationCanceledException();

                    if (operationCanceledException != null)
                    {
                        OperationCanceled(operationCanceledException);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            finally
            {
                workspace?.Dispose();
            }

            return(CommandResult.Fail);
        }
 public abstract Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default);
Exemplo n.º 12
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));

            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);
        }
Exemplo n.º 13
0
 public override Task <CommandResult> ExecuteAsync(ProjectOrSolution projectOrSolution, CancellationToken cancellationToken = default)
 {
     return(Task.FromResult(CommandResult.Success));
 }