Skip to content

Commit

Permalink
add extra rules
Browse files Browse the repository at this point in the history
  • Loading branch information
NikiforovAll committed Sep 18, 2024
1 parent 78a7880 commit 4d8c203
Show file tree
Hide file tree
Showing 10 changed files with 174 additions and 34 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ To configure the playground, set the `PLAYGROUND_CONNECTION_STRING=https://elast

## Analyzer

This repository contains [Nall.NEST.MigtarionAnalyzer](https://github.com/NikiforovAll/elasticsearch-dotnet-playground/pkgs/nuget/Nall.NEST.MigtarionAnalyzer) analyzer that helps with migration from `Nest` to `Elastic.Clients.Elasticsearch`.
This repository contains [Nall.NEST.MigtarionAnalyzer](https://www.nuget.org/packages/Nall.NEST.MigtarionAnalyzer) analyzer that helps with migration from `Nest` to `Elastic.Clients.Elasticsearch`.

```bash
dotnet add package Nall.NEST.MigtarionAnalyzer --version 1.0.0
dotnet add package Nall.NEST.MigtarionAnalyzer --version 1.1.0
```

## Devcontainer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,53 @@ CancellationToken cancellationToken
)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document
.GetSemanticModelAsync(cancellationToken)
.ConfigureAwait(false);

root = ReplaceUsings(root);
root = ReplaceConnectionSettings(root);

var nodesToReplace = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(node =>
node.Identifier.ValueText == "IElasticClient"
|| node.Identifier.ValueText == "ElasticClient"
);

root = root.ReplaceNodes(
nodesToReplace,
(node, _) =>
SyntaxFactory.IdentifierName("ElasticsearchClient").WithTriviaFrom(node)
);

return document.WithSyntaxRoot(root);
}

private SyntaxNode ReplaceConnectionSettings(SyntaxNode root)
{
var nodesToReplace = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(node => node.Identifier.ValueText == "ConnectionSettings");

root = root.ReplaceNodes(
nodesToReplace,
(node, _) =>
SyntaxFactory.IdentifierName("ElasticsearchClientSettings").WithTriviaFrom(node)
);

return root;
}

private static SyntaxNode ReplaceUsings(SyntaxNode root)
{
// Replace the using directive
var oldUsingDirective = root.DescendantNodes()
.OfType<UsingDirectiveSyntax>()
.FirstOrDefault(u => u.Name.ToString() == "Nest");

if (oldUsingDirective != null)
{
var newUsingDirective = SyntaxFactory.UsingDirective(
SyntaxFactory.ParseName("Elastic.Clients.Elasticsearch")
).WithTriviaFrom(oldUsingDirective); // Preserve trivia
var newUsingDirective = SyntaxFactory
.UsingDirective(SyntaxFactory.ParseName("Elastic.Clients.Elasticsearch"))
.WithTriviaFrom(oldUsingDirective); // Preserve trivia
root = root.ReplaceNode(oldUsingDirective, newUsingDirective);
}
else
Expand All @@ -93,17 +126,7 @@ CancellationToken cancellationToken
}
}

// Replace IElasticClient with ElasticsearchClient
var nodesToReplace = root.DescendantNodes()
.OfType<IdentifierNameSyntax>()
.Where(node => node.Identifier.ValueText == "IElasticClient");

root = root.ReplaceNodes(
nodesToReplace,
(node, _) => SyntaxFactory.IdentifierName("ElasticsearchClient").WithTriviaFrom(node) // Preserve trivia
);

return document.WithSyntaxRoot(root);
return root;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<PropertyGroup>
<PackageId>Nall.NEST.MigtarionAnalyzer</PackageId>
<PackageVersion>1.0.0.0</PackageVersion>
<PackageVersion>1.1.0.0</PackageVersion>
<Authors>Oleksii_Nikiforov</Authors>
<PackageLicenseUrl>https://github.com/NikiforovAll/elasticsearch-dotnet-playground/LICENSE.md</PackageLicenseUrl>
<PackageProjectUrl>https://github.com/NikiforovAll/elasticsearch-dotnet-playground</PackageProjectUrl>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,35 @@ public ElasticsearchService({|#1:IElasticClient|} client)
await VerifyCS.VerifyAnalyzerAsync(test, expected1, expected2);
}

[TestMethod]
public async Task TestNestUsageAsClass()
{
var test =
@"
using Nest;
public class ElasticsearchService
{
private readonly {|#0:ElasticClient|} _client;
public ElasticsearchService({|#1:ElasticClient|} client)
{
_client = client;
}
}";

var expected1 = VerifyCS
.Diagnostic("ELS001")
.WithLocation(0)
.WithArguments("ElasticClient");

var expected2 = VerifyCS
.Diagnostic("ELS001")
.WithLocation(1)
.WithArguments("ElasticClient");

await VerifyCS.VerifyAnalyzerAsync(test, expected1, expected2);
}

//Diagnostic and CodeFix both triggered and checked for
[TestMethod]
public async Task TestCodeFix()
Expand Down Expand Up @@ -114,6 +143,52 @@ public ElasticsearchService( ElasticsearchClient client)

await VerifyCS.VerifyCodeFixAsync(test, [expected1, expected2], fixtest);
}

[TestMethod]
public async Task TestCodeFixWithSettings()
{
var test = """
using Nest;
public class ElasticsearchService
{
private readonly {|#0:ElasticClient|} _client;
public ElasticsearchService()
{
var settings = new ConnectionSettings(new Uri("https://elastic:[email protected]:9200/"));
_client = new {|#1:ElasticClient|}(settings);
}
}
""";

var fixtest = """
using Elastic.Clients.Elasticsearch;
public class ElasticsearchService
{
private readonly ElasticsearchClient _client;
public ElasticsearchService()
{
var settings = new ElasticsearchClientSettings(new Uri("https://elastic:[email protected]:9200/"));
_client = new ElasticsearchClient(settings);
}
}
""";

var expected1 = VerifyCS
.Diagnostic("ELS001")
.WithLocation(0)
.WithArguments("ElasticClient");

var expected2 = VerifyCS
.Diagnostic("ELS001")
.WithLocation(1)
.WithArguments("ElasticClient");

await VerifyCS.VerifyCodeFixAsync(test, [expected1, expected2], fixtest);
}
}

public static class VerifyCS
Expand Down Expand Up @@ -149,7 +224,7 @@ string fixedSource
test.TestState.AdditionalReferences.Add(s_nestReference);
test.TestState.AdditionalReferences.Add(s_elasticReference);
test.ExpectedDiagnostics.AddRange(expected);
// we need this becaues of
// we need this becaues of
// error CS1705: Assembly 'Elastic.Clients.Elasticsearch' with identity 'Elastic.Clients.Elasticsearch, Version=8.0.0.0, Culture=neutral, PublicKeyToken=96c599bbe3e70f5d' uses 'System.Runtime, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'System.Runtime' with identity 'System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
test.CompilerDiagnostics = CompilerDiagnostics.None;
return test.RunAsync();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Id="Nall.NEST.MigtarionAnalyzer.79afaeb1-a5b0-45cc-ac3a-33980131a010" Version="1.2" Language="en-US" Publisher="Oleksii_Nikiforov"/>
<Identity Id="Nall.NEST.MigtarionAnalyzer.79afaeb1-a5b0-45cc-ac3a-33980131a010" Version="1.1" Language="en-US" Publisher="Oleksii_Nikiforov"/>
<DisplayName>Nall.NEST.MigtarionAnalyzer</DisplayName>
<Description xml:space="preserve">This package helps with migration from Nest to Elastic.Clients.Elasticsearch.</Description>
</Metadata>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var identifierNode = (IdentifierNameSyntax)context.Node;

if (identifierNode.Identifier.Text != "IElasticClient")
var indetifierText = identifierNode.Identifier.Text;

if (indetifierText != "IElasticClient" && indetifierText != "ElasticClient")
{
return;
}
Expand Down
4 changes: 4 additions & 0 deletions analyzer/Playground/Playground.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Nall.NEST.MigtarionAnalyzer" Version="1.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="NEST" Version="7.17.5" />
<PackageReference Include="Elastic.Clients.Elasticsearch" Version="8.15.6" />
</ItemGroup>
Expand Down
22 changes: 22 additions & 0 deletions analyzer/Playground/Playground.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Playground", "Playground.csproj", "{CF7AE166-9099-4DCE-995B-85842C623790}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CF7AE166-9099-4DCE-995B-85842C623790}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF7AE166-9099-4DCE-995B-85842C623790}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF7AE166-9099-4DCE-995B-85842C623790}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF7AE166-9099-4DCE-995B-85842C623790}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
24 changes: 22 additions & 2 deletions analyzer/Playground/Program.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
using System.Text.Json;
#pragma warning disable CS8321 // Local function is declared but never used

using System.Text.Json;
using Elastic.Clients.Elasticsearch;
using Elastic.Transport;
using Nest;

// ElasticClient -> ElasticsearchClient
// IElasticClient -> ElasticsearchClient
// ConnectionSettings -> ElasticsearchClientSettings

var settings = new ConnectionSettings(new Uri("https://elastic:[email protected]:9200/"))
.DisableDirectStreaming()
.ServerCertificateValidationCallback(CertificateValidations.AllowAll);

var client = new ElasticClient(settings);
IElasticClient client = new ElasticClient(settings);

var nodeInfo = await client.Nodes.InfoAsync();

Console.WriteLine(
JsonSerializer.Serialize(nodeInfo, new JsonSerializerOptions { WriteIndented = true })
);

static IElasticClient Create1(ConnectionSettings settings)
{
return new ElasticClient(settings);
}
static ElasticClient Create2(ConnectionSettings settings)
{
return new ElasticClient(settings);
}
static ElasticsearchClient Create3(ElasticsearchClientSettings settings)
{
return new ElasticsearchClient(settings);
}
12 changes: 3 additions & 9 deletions analyzer/analyzer.sln
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nall.NEST.MigtarionAnalyzer
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nall.NEST.MigtarionAnalyzer.Vsix", "Nall.NEST.MigtarionAnalyzer.Vsix\Nall.NEST.MigtarionAnalyzer.Vsix.csproj", "{60AA48E2-2F4D-4CD9-9CCC-F4B9332B3865}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Playground", "Playground\Playground.csproj", "{CAF7F28D-995E-4FB8-BAE9-13C082C3BAEB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5B3F3DB1-20B9-4834-83CC-17334839193B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5B3F3DB1-20B9-4834-83CC-17334839193B}.Debug|Any CPU.Build.0 = Debug|Any CPU
Expand All @@ -44,9 +39,8 @@ Global
{60AA48E2-2F4D-4CD9-9CCC-F4B9332B3865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{60AA48E2-2F4D-4CD9-9CCC-F4B9332B3865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{60AA48E2-2F4D-4CD9-9CCC-F4B9332B3865}.Release|Any CPU.Build.0 = Release|Any CPU
{CAF7F28D-995E-4FB8-BAE9-13C082C3BAEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CAF7F28D-995E-4FB8-BAE9-13C082C3BAEB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CAF7F28D-995E-4FB8-BAE9-13C082C3BAEB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CAF7F28D-995E-4FB8-BAE9-13C082C3BAEB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

0 comments on commit 4d8c203

Please sign in to comment.