Beispiel #1
0
        public static void WriteProjectFixResults(
            IList <ProjectFixResult> results,
            CodeFixerOptions options,
            IFormatProvider formatProvider = null)
        {
            if (options.FileBannerLines.Any())
            {
                int count = results.Sum(f => f.NumberOfAddedFileBanners);
                WriteLine(Verbosity.Normal);
                WriteLine($"{count} file {((count == 1) ? "banner" : "banners")} added", Verbosity.Normal);
            }

            if (options.Format)
            {
                int count = results.Sum(f => f.NumberOfFormattedDocuments);
                WriteLine(Verbosity.Normal);
                WriteLine($"{count} {((count == 1) ? "document" : "documents")} formatted", Verbosity.Normal);
            }

            WriteFixSummary(
                results.SelectMany(f => f.FixedDiagnostics),
                results.SelectMany(f => f.UnfixedDiagnostics),
                results.SelectMany(f => f.UnfixableDiagnostics),
                addEmptyLine: true,
                formatProvider: formatProvider,
                verbosity: Verbosity.Normal);

            int fixedCount = results.Sum(f => f.FixedDiagnostics.Length);

            WriteLine(Verbosity.Minimal);
            WriteLine($"{fixedCount} {((fixedCount == 1) ? "diagnostic" : "diagnostics")} fixed", ConsoleColor.Green, Verbosity.Minimal);
        }
Beispiel #2
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);
        }
Beispiel #3
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);
        }
Beispiel #4
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));
            }
        }
Beispiel #5
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));
            }
        }
Beispiel #6
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));

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

            if (Options.UseRoslynatorCodeFixes)
            {
                analyzerAssemblies = analyzerAssemblies.Concat(AnalyzerAssemblyLoader.LoadFiles(RoslynatorCodeFixesAssemblies));
            }

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

            return(await FixAsync(projectOrSolution, analyzerAssemblies, codeFixerOptions, culture, cancellationToken));
        }
Beispiel #7
0
        private static async Task <int> FixAsync(FixCommandLineOptions options)
        {
            var cts = new CancellationTokenSource();

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

            CancellationToken cancellationToken = cts.Token;

            if (options.MSBuildPath != null)
            {
                MSBuildLocator.RegisterMSBuildPath(options.MSBuildPath);
            }
            else
            {
                VisualStudioInstance instance = MSBuildLocator.QueryVisualStudioInstances()
                                                .OrderBy(f => f.Version)
                                                .LastOrDefault();

                if (instance == null)
                {
                    WriteLine("MSBuild location not found. Use option '--msbuild-path' to specify MSBuild location", ConsoleColor.Red);
                    return(1);
                }

                WriteLine($"MSBuild location is '{instance.MSBuildPath}'");

                MSBuildLocator.RegisterInstance(instance);
            }

            var properties = new Dictionary <string, string>();

            foreach (string property in options.Properties)
            {
                int index = property.IndexOf("=");

                if (index == -1)
                {
                    WriteLine($"Unable to parse property '{property}'", ConsoleColor.Red);
                    return(1);
                }

                string key = property.Substring(0, index);

                properties[key] = property.Substring(index + 1);
            }

            if (properties.Count > 0)
            {
                WriteLine("Add MSBuild properties");

                int maxLength = properties.Max(f => f.Key.Length);

                foreach (KeyValuePair <string, string> kvp in properties)
                {
                    WriteLine($"  {kvp.Key.PadRight(maxLength)} = {kvp.Value}");
                }
            }

            // https://github.com/Microsoft/MSBuildLocator/issues/16
            if (!properties.ContainsKey("AlwaysCompileMarkupFilesInSeparateDomain"))
            {
                properties["AlwaysCompileMarkupFilesInSeparateDomain"] = bool.FalseString;
            }

            using (MSBuildWorkspace workspace = MSBuildWorkspace.Create(properties))
            {
                workspace.WorkspaceFailed += (o, e) => WriteLine(e.Diagnostic.Message, ConsoleColor.Yellow);

                string solutionPath = options.SolutionPath;

                WriteLine($"Load solution '{solutionPath}'", ConsoleColor.Cyan);

                try
                {
                    Solution solution;

                    try
                    {
                        solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter(), cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        if (ex is FileNotFoundException ||
                            ex is InvalidOperationException)
                        {
                            WriteLine(ex.ToString(), ConsoleColor.Red);
                            return(1);
                        }
                        else
                        {
                            throw;
                        }
                    }

                    WriteLine($"Done loading solution '{solutionPath}'", ConsoleColor.Green);

                    var codeFixerOptions = new CodeFixerOptions(
                        ignoreCompilerErrors: options.IgnoreCompilerErrors,
                        ignoreAnalyzerReferences: options.IgnoreAnalyzerReferences,
                        ignoredDiagnosticIds: options.IgnoredDiagnostics,
                        ignoredCompilerDiagnosticIds: options.IgnoredCompilerDiagnostics,
                        ignoredProjectNames: options.IgnoredProjects,
                        batchSize: options.BatchSize);

                    var codeFixer = new CodeFixer(workspace, analyzerAssemblies: options.AnalyzerAssemblies, options: codeFixerOptions);

                    await codeFixer.FixAsync(cancellationToken);
                }
                catch (OperationCanceledException)
                {
                    WriteLine("Fixing was canceled.");
                }
            }

            return(0);
        }