Adding analyzer project

Contains two analyzers with fixes

* Use AnsiConsole over System.Console
* Favor local instance over static implementation
This commit is contained in:
Phil Scott
2021-06-20 19:47:19 -04:00
committed by Patrik Svensson
parent d015a4966f
commit 4f293d887d
20 changed files with 974 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Spectre.Console.Analyzer;
using Xunit;
using AnalyzerVerify =
Spectre.Console.Tests.CodeAnalyzers.SpectreAnalyzerVerifier<
Spectre.Console.Analyzer.FavorInstanceAnsiConsoleOverStaticAnalyzer>;
namespace Spectre.Console.Tests.CodeAnalyzers.Analyzers
{
public class FavorInstanceAnsiConsoleOverStaticAnalyzerTests
{
private static readonly DiagnosticResult _expectedDiagnostics = new(
Descriptors.S1010_FavorInstanceAnsiConsoleOverStatic.Id,
DiagnosticSeverity.Info);
[Fact]
public async void Console_Write_Has_Warning()
{
const string Source = @"
using Spectre.Console;
class TestClass
{
IAnsiConsole _ansiConsole = AnsiConsole.Console;
void TestMethod()
{
_ansiConsole.Write(""this is fine"");
AnsiConsole.Write(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyAnalyzerAsync(Source, _expectedDiagnostics.WithLocation(11, 9))
.ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,53 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Spectre.Console.Analyzer;
using Xunit;
using AnalyzerVerify =
Spectre.Console.Tests.CodeAnalyzers.SpectreAnalyzerVerifier<
Spectre.Console.Analyzer.UseSpectreInsteadOfSystemConsoleAnalyzer>;
namespace Spectre.Console.Tests.CodeAnalyzers.Analyzers
{
public class UseSpectreInsteadOfSystemConsoleAnalyzerTests
{
private static readonly DiagnosticResult _expectedDiagnostics = new(
Descriptors.S1000_UseAnsiConsoleOverSystemConsole.Id,
DiagnosticSeverity.Warning);
[Fact]
public async void Console_Write_Has_Warning()
{
const string Source = @"
using System;
class TestClass {
void TestMethod()
{
Console.Write(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyAnalyzerAsync(Source, _expectedDiagnostics.WithLocation(7, 9))
.ConfigureAwait(false);
}
[Fact]
public async void Console_WriteLine_Has_Warning()
{
const string Source = @"
using System;
class TestClass
{
void TestMethod() {
Console.WriteLine(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyAnalyzerAsync(Source, _expectedDiagnostics.WithLocation(7, 9))
.ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.VisualStudio.Composition;
using Spectre.Console.Analyzer;
using Spectre.Console.Analyzer.FixProviders;
namespace Spectre.Console.Tests.CodeAnalyzers
{
internal static class CodeFixProviderDiscovery
{
private static readonly Lazy<IExportProviderFactory> _exportProviderFactory;
static CodeFixProviderDiscovery()
{
_exportProviderFactory = new Lazy<IExportProviderFactory>(
() =>
{
var discovery = new AttributedPartDiscovery(Resolver.DefaultInstance, isNonPublicSupported: true);
var parts = Task.Run(() => discovery.CreatePartsAsync(typeof(SystemConsoleToAnsiConsoleFix).Assembly)).GetAwaiter().GetResult();
var catalog = ComposableCatalog.Create(Resolver.DefaultInstance).AddParts(parts);
var configuration = CompositionConfiguration.Create(catalog);
var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration);
return runtimeComposition.CreateExportProviderFactory();
},
LazyThreadSafetyMode.ExecutionAndPublication);
}
public static IEnumerable<CodeFixProvider> GetCodeFixProviders(string language)
{
var exportProvider = _exportProviderFactory.Value.CreateExportProvider();
var exports = exportProvider.GetExports<CodeFixProvider, LanguageMetadata>();
return exports.Where(export => export.Metadata.Languages.Contains(language)).Select(export => export.Value);
}
private class LanguageMetadata
{
public LanguageMetadata(IDictionary<string, object> data)
{
if (!data.TryGetValue(nameof(ExportCodeFixProviderAttribute.Languages), out var languages))
{
languages = Array.Empty<string>();
}
Languages = ((string[])languages).ToImmutableArray();
}
public ImmutableArray<string> Languages { get; }
}
}
}

View File

@@ -0,0 +1,54 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Spectre.Console.Analyzer;
using Xunit;
using AnalyzerVerify =
Spectre.Console.Tests.CodeAnalyzers.SpectreAnalyzerVerifier<
Spectre.Console.Analyzer.FavorInstanceAnsiConsoleOverStaticAnalyzer>;
namespace Spectre.Console.Tests.CodeAnalyzers.Fixes
{
public class UseInstanceOfStaticAnsiConsoleTests
{
private static readonly DiagnosticResult _expectedDiagnostic = new(
Descriptors.S1010_FavorInstanceAnsiConsoleOverStatic.Id,
DiagnosticSeverity.Info);
[Fact]
public async Task SystemConsole_replaced_with_AnsiConsole()
{
const string Source = @"
using Spectre.Console;
class TestClass
{
IAnsiConsole _ansiConsole = AnsiConsole.Console;
void TestMethod()
{
_ansiConsole.Write(""this is fine"");
AnsiConsole.Write(""Hello, World"");
}
}";
const string FixedSource = @"
using Spectre.Console;
class TestClass
{
IAnsiConsole _ansiConsole = AnsiConsole.Console;
void TestMethod()
{
_ansiConsole.Write(""this is fine"");
_ansiConsole.Write(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyCodeFixAsync(Source, _expectedDiagnostic.WithLocation(11, 9), FixedSource)
.ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,152 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Spectre.Console.Analyzer;
using Xunit;
using AnalyzerVerify =
Spectre.Console.Tests.CodeAnalyzers.SpectreAnalyzerVerifier<
Spectre.Console.Analyzer.UseSpectreInsteadOfSystemConsoleAnalyzer>;
namespace Spectre.Console.Tests.CodeAnalyzers.Fixes
{
public class UseSpectreInsteadOfSystemConsoleFixTests
{
private static readonly DiagnosticResult _expectedDiagnostic = new(
Descriptors.S1000_UseAnsiConsoleOverSystemConsole.Id,
DiagnosticSeverity.Warning);
[Fact]
public async Task SystemConsole_replaced_with_AnsiConsole()
{
const string Source = @"
using System;
class TestClass
{
void TestMethod()
{
Console.WriteLine(""Hello, World"");
}
}";
const string FixedSource = @"
using System;
using Spectre.Console;
class TestClass
{
void TestMethod()
{
AnsiConsole.WriteLine(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyCodeFixAsync(Source, _expectedDiagnostic.WithLocation(8, 9), FixedSource)
.ConfigureAwait(false);
}
[Fact]
public async Task SystemConsole_replaced_with_imported_AnsiConsole()
{
const string Source = @"
using System;
class TestClass
{
void TestMethod()
{
Console.WriteLine(""Hello, World"");
}
}";
const string FixedSource = @"
using System;
using Spectre.Console;
class TestClass
{
void TestMethod()
{
AnsiConsole.WriteLine(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyCodeFixAsync(Source, _expectedDiagnostic.WithLocation(8, 9), FixedSource)
.ConfigureAwait(false);
}
[Fact]
public async Task SystemConsole_replaced_with_field_AnsiConsole()
{
const string Source = @"
using System;
using Spectre.Console;
class TestClass
{
IAnsiConsole _ansiConsole;
void TestMethod()
{
Console.WriteLine(""Hello, World"");
}
}";
const string FixedSource = @"
using System;
using Spectre.Console;
class TestClass
{
IAnsiConsole _ansiConsole;
void TestMethod()
{
_ansiConsole.WriteLine(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyCodeFixAsync(Source, _expectedDiagnostic.WithLocation(11, 9), FixedSource)
.ConfigureAwait(false);
}
[Fact]
public async Task SystemConsole_replaced_with_static_field_AnsiConsole()
{
const string Source = @"
using System;
using Spectre.Console;
class TestClass
{
static IAnsiConsole _ansiConsole;
static void TestMethod()
{
Console.WriteLine(""Hello, World"");
}
}";
const string FixedSource = @"
using System;
using Spectre.Console;
class TestClass
{
static IAnsiConsole _ansiConsole;
static void TestMethod()
{
_ansiConsole.WriteLine(""Hello, World"");
}
}";
await AnalyzerVerify
.VerifyCodeFixAsync(Source, _expectedDiagnostic.WithLocation(11, 9), FixedSource)
.ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
namespace Spectre.Console.Tests.CodeAnalyzers
{
public static class SpectreAnalyzerVerifier<TAnalyzer>
where TAnalyzer : DiagnosticAnalyzer, new()
{
public static Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource)
=> VerifyCodeFixAsync(source, new[] { expected }, fixedSource);
private static Task VerifyCodeFixAsync(string source, IEnumerable<DiagnosticResult> expected, string fixedSource)
{
// Roslyn fixers always use \r\n for newlines, regardless of OS environment settings, so we normalize
// the source as it typically comes from multi-line strings with varying newlines.
if (Environment.NewLine != "\r\n")
{
source = source.Replace(Environment.NewLine, "\r\n");
fixedSource = fixedSource.Replace(Environment.NewLine, "\r\n");
}
var test = new Test
{
TestCode = source,
FixedCode = fixedSource,
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync();
}
public static Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
{
var test = new Test
{
TestCode = source,
CompilerDiagnostics = CompilerDiagnostics.All,
ReferenceAssemblies = CodeAnalyzerHelper.CurrentSpectre,
TestBehaviors = TestBehaviors.SkipGeneratedCodeCheck,
};
test.ExpectedDiagnostics.AddRange(expected);
return test.RunAsync();
}
// Code fix tests support both analyzer and code fix testing. This test class is derived from the code fix test
// to avoid the need to maintain duplicate copies of the customization work.
private class Test : CSharpCodeFixTest<TAnalyzer, EmptyCodeFixProvider, XUnitVerifier>
{
public Test()
{
ReferenceAssemblies = CodeAnalyzerHelper.CurrentSpectre;
TestBehaviors |= TestBehaviors.SkipGeneratedCodeCheck;
}
protected override IEnumerable<CodeFixProvider> GetCodeFixProviders()
{
var analyzer = new TAnalyzer();
foreach (var provider in CodeFixProviderDiscovery.GetCodeFixProviders(Language))
{
if (analyzer.SupportedDiagnostics.Any(diagnostic => provider.FixableDiagnosticIds.Contains(diagnostic.Id)))
{
yield return provider;
}
}
}
}
}
internal static class CodeAnalyzerHelper
{
internal static ReferenceAssemblies CurrentSpectre { get; }
static CodeAnalyzerHelper()
{
CurrentSpectre = ReferenceAssemblies.Net.Net50.AddAssemblies(ImmutableArray.Create(typeof(AnsiConsole).Assembly.Location.Replace(".dll", string.Empty)));
}
}
}