Skip to content

Commit a38765d

Browse files
committed
initial refactoring injection CodeFix
1 parent 593e5ba commit a38765d

5 files changed

Lines changed: 109 additions & 43 deletions

File tree

System.IO.Abstractions.Analyzers.Tests/CodeFixes/FileServiceInterfaceInjectionCodeFixTests.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ public class FileServiceInterfaceInjectionCodeFixTests :
1212
{
1313
[Theory]
1414
[InlineData("BeforeFix.txt", "AfterFix.txt")]
15+
[InlineData("BeforeFixWithoutConstructor.txt", "AfterFix.txt")]
1516
public void CodeFix(string sourceBefore, string sourceAfter)
1617
{
1718
var sourceBeforeFix = ReadFile(sourceBefore);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System.IO;
2+
3+
namespace SomeNameSpace
4+
{
5+
public class WithOutFileSystem
6+
{
7+
public void SomeMethod()
8+
{
9+
const string filePath = "C:\\temp.txt";
10+
11+
if (File.Exists(filePath))
12+
{
13+
File.Delete(filePath);
14+
}
15+
}
16+
}
17+
}

System.IO.Abstractions.Analyzers/CodeActions/FileServiceInterfaceInjectionCodeAction.cs

Lines changed: 86 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,17 @@ namespace System.IO.Abstractions.Analyzers.CodeActions
1515
/// <inheritdoc />
1616
public class FileServiceInterfaceInjectionCodeAction : CodeAction
1717
{
18-
private readonly ConstructorDeclarationSyntax _constructor;
18+
private const string FieldFileSystemName = "_fileSystem";
19+
20+
private const string ParameterFileSystemName = "fileSystem";
21+
22+
private readonly ClassDeclarationSyntax _class;
1923

2024
private readonly Document _document;
2125

22-
public FileServiceInterfaceInjectionCodeAction(string title, Document document, ConstructorDeclarationSyntax constructor)
26+
public FileServiceInterfaceInjectionCodeAction(string title, Document document, ClassDeclarationSyntax @class)
2327
{
24-
_constructor = constructor;
28+
_class = @class;
2529
_document = document;
2630
Title = title;
2731
}
@@ -34,40 +38,21 @@ protected override async Task<Document> GetChangedDocumentAsync(CancellationToke
3438
{
3539
var editor = await DocumentEditor.CreateAsync(_document, cancellationToken).ConfigureAwait(false);
3640

37-
var parameter = CreateFileSystemParameterDeclaration();
38-
39-
if (!(_constructor.Parent is ClassDeclarationSyntax classDeclarationSyntax))
40-
{
41-
editor.AddParameter(_constructor, parameter);
42-
43-
return editor.GetChangedDocument();
44-
}
45-
46-
var fileSystem = classDeclarationSyntax.Members
47-
.OfType<FieldDeclarationSyntax>()
48-
.FirstOrDefault(x => x.NormalizeWhitespace().ToFullString().Equals(Constants.FileSystemName));
49-
50-
if (fileSystem != null)
41+
if (!HasFileSystemProperty(_class))
5142
{
52-
return editor.GetChangedDocument();
43+
var fileSystemPropertyDeclaration = CreateFileSystemPropertyDeclaration();
44+
45+
editor.InsertMembers(_class,
46+
0,
47+
new SyntaxNode[]
48+
{
49+
fileSystemPropertyDeclaration
50+
});
5351
}
5452

55-
var fileSystemPropertyDeclaration = CreateFileSystemPropertyDeclaration();
56-
57-
editor.InsertMembers(classDeclarationSyntax,
58-
0,
59-
new SyntaxNode[]
60-
{
61-
fileSystemPropertyDeclaration
62-
});
63-
64-
var newConstructor = _constructor.WithBody(_constructor.Body.AddStatements(CreateAssignmentExpression()))
65-
.AddParameterListParameters(parameter)
66-
.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation)
67-
.NormalizeWhitespace();
53+
ConstructorAddParameter(_class, editor);
6854

69-
editor.ReplaceNode(_constructor, newConstructor);
70-
var compilationUnitSyntax = GetCompilationUnit(_constructor);
55+
var compilationUnitSyntax = GetCompilationUnit(_class);
7156

7257
editor.ReplaceNode(compilationUnitSyntax.Usings.FirstOrDefault(),
7358
SF.UsingDirective(SF.ParseName(Constants.FileSystemNameSpace)));
@@ -77,33 +62,33 @@ protected override async Task<Document> GetChangedDocumentAsync(CancellationToke
7762

7863
private static FieldDeclarationSyntax CreateFileSystemPropertyDeclaration()
7964
{
80-
return SF.FieldDeclaration(SF.VariableDeclaration(CreateFileSystemType())
81-
.WithVariables(SF.SingletonSeparatedList(SF.VariableDeclarator(SF.Identifier("_fileSystem")))))
65+
return SF.FieldDeclaration(SF.VariableDeclaration(GetFileSystemType())
66+
.WithVariables(SF.SingletonSeparatedList(SF.VariableDeclarator(SF.Identifier(FieldFileSystemName)))))
8267
.WithModifiers(SF.TokenList(SF.Token(SyntaxKind.PrivateKeyword),
8368
SF.Token(SyntaxKind.ReadOnlyKeyword)));
8469
}
8570

8671
private static ParameterSyntax CreateFileSystemParameterDeclaration()
8772
{
88-
return SF.Parameter(SF.Identifier("fileSystem"))
89-
.WithType(CreateFileSystemType())
73+
return SF.Parameter(SF.Identifier(ParameterFileSystemName))
74+
.WithType(GetFileSystemType())
9075
.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.SpecialTypeAnnotation)
9176
.NormalizeWhitespace();
9277
}
9378

94-
private static TypeSyntax CreateFileSystemType()
79+
private static TypeSyntax GetFileSystemType()
9580
{
9681
return SF.ParseTypeName(Constants.FileSystemName);
9782
}
9883

9984
private static ExpressionStatementSyntax CreateAssignmentExpression()
10085
{
10186
return SF.ExpressionStatement(SF.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
102-
SF.IdentifierName("_fileSystem"),
103-
SF.IdentifierName("fileSystem")));
87+
SF.IdentifierName(FieldFileSystemName),
88+
SF.IdentifierName(ParameterFileSystemName)));
10489
}
10590

106-
private CompilationUnitSyntax GetCompilationUnit(SyntaxNode node)
91+
private static CompilationUnitSyntax GetCompilationUnit(SyntaxNode node)
10792
{
10893
switch (node)
10994
{
@@ -118,5 +103,65 @@ private CompilationUnitSyntax GetCompilationUnit(SyntaxNode node)
118103
return GetCompilationUnit(node.Parent);
119104
}
120105
}
106+
107+
private static bool HasFileSystemProperty(TypeDeclarationSyntax classDeclaration)
108+
{
109+
return classDeclaration.Members.OfType<PropertyDeclarationSyntax>()
110+
.Any(x => x.Identifier.Text == FieldFileSystemName && x.Type == GetFileSystemType());
111+
}
112+
113+
private static ConstructorDeclarationSyntax GetConstructor(SyntaxNode classDeclaration)
114+
{
115+
return classDeclaration.ChildNodes().OfType<ConstructorDeclarationSyntax>().FirstOrDefault();
116+
}
117+
118+
private static bool ConstructorHasFileSystemParameter(BaseMethodDeclarationSyntax constructor)
119+
{
120+
return constructor.ParameterList.Parameters
121+
.Any(x => x.Identifier.Text == ParameterFileSystemName && x.Type == GetFileSystemType());
122+
}
123+
124+
private static bool ConstructorHasAssignmentExpression(BaseMethodDeclarationSyntax constructor)
125+
{
126+
return constructor.Body.Statements.OfType<ExpressionStatementSyntax>()
127+
.Any(x => x.IsKind(SyntaxKind.SimpleAssignmentExpression)
128+
&& x.Expression.Contains(SF.IdentifierName(FieldFileSystemName))
129+
&& x.Expression.Contains(SF.IdentifierName(ParameterFileSystemName)));
130+
}
131+
132+
private static bool HasConstructor(SyntaxNode classDeclaration)
133+
{
134+
return classDeclaration.ChildNodes().OfType<ConstructorDeclarationSyntax>().Any();
135+
}
136+
137+
private static void ConstructorAddParameter(ClassDeclarationSyntax classDeclaration, DocumentEditor editor)
138+
{
139+
var constructor = HasConstructor(classDeclaration)
140+
? GetConstructor(classDeclaration)
141+
: SF.ConstructorDeclaration(classDeclaration.Identifier);
142+
143+
var newConstructor = constructor.WithBody(constructor.Body?.AddStatements(CreateAssignmentExpression()))
144+
.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation)
145+
.NormalizeWhitespace();
146+
147+
if (!ConstructorHasFileSystemParameter(newConstructor))
148+
{
149+
var parameter = CreateFileSystemParameterDeclaration();
150+
newConstructor = newConstructor.AddParameterListParameters(parameter);
151+
}
152+
153+
if (HasConstructor(classDeclaration))
154+
{
155+
editor.ReplaceNode(constructor, newConstructor);
156+
} else
157+
{
158+
editor.InsertMembers(classDeclaration,
159+
0,
160+
new SyntaxNode[]
161+
{
162+
newConstructor
163+
});
164+
}
165+
}
121166
}
122167
}

System.IO.Abstractions.Analyzers/CodeFixes/FileServiceInterfaceInjectionCodeFix.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@ public class FileServiceInterfaceInjectionCodeFix : CodeFixProvider
2323
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
2424
{
2525
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
26-
var constructorDeclarationSyntax = root.FindNode(context.Span).FirstAncestorOrSelf<ConstructorDeclarationSyntax>();
26+
var classDeclarationSyntax = root.FindNode(context.Span).FirstAncestorOrSelf<ClassDeclarationSyntax>();
2727

2828
context.RegisterCodeFix(new FileServiceInterfaceInjectionCodeAction(Title,
2929
context.Document,
30-
constructorDeclarationSyntax),
30+
classDeclarationSyntax),
3131
context.Diagnostics);
3232
}
3333
}

System.IO.Abstractions.Analyzers/System.IO.Abstractions.Analyzers.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,7 @@
4747
<None Update="tools\*.ps1" CopyToOutputDirectory="Always" Pack="true" PackagePath="" />
4848
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
4949
</ItemGroup>
50+
<ItemGroup>
51+
<Folder Include="Helpers" />
52+
</ItemGroup>
5053
</Project>

0 commit comments

Comments
 (0)