This repository has been archived by the owner on Feb 25, 2021. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Encourage encapsulation of component parameter properties (#713)
* Before refactoring ParameterCollection assignment logic, add more test coverage * Begin caching parameter assignment info * Factor out some reflection code to a reusable location * Use IPropertySetter to avoid all per-property-assignment reflection * More error cases and tests for parameter assignment * Enable binding to nonpublic properties * Add analyzer to warn and provide fix for public component parameters * Unit test for analyzer * Component tag helper now includes private properties if they have [Parameter] * CR feedback: Remove garbage from csproj * CR feedback: Rename .Build.Analyzers to .Analyzers * CR feedback: Move BlazorApi.cs to shared; use it from Analyzers test * Fix incorrect test name * Make as many parameters private as possible. Replace ILayoutComponent with BlazorLayoutComponent. * In component tag helper discovery, consider private members too * Reduce the work in component parameter discovery by not inspecting the BlazorComponent base class (or System.Object)
- Loading branch information
1 parent
a178cd4
commit e90432c
Showing
60 changed files
with
2,004 additions
and
239 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
src/Microsoft.AspNetCore.Blazor.Analyzers/ComponentParametersShouldNotBePublicAnalyzer.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using Microsoft.AspNetCore.Blazor.Shared; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using System.Collections.Immutable; | ||
using System.Linq; | ||
|
||
namespace Microsoft.AspNetCore.Blazor.Analyzers | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public class ComponentParametersShouldNotBePublicAnalyzer : DiagnosticAnalyzer | ||
{ | ||
public const string DiagnosticId = "BL9993"; | ||
private const string Category = "Encapsulation"; | ||
|
||
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.ComponentParametersShouldNotBePublic_Title), Resources.ResourceManager, typeof(Resources)); | ||
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.ComponentParametersShouldNotBePublic_Format), Resources.ResourceManager, typeof(Resources)); | ||
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.ComponentParametersShouldNotBePublic_Description), Resources.ResourceManager, typeof(Resources)); | ||
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor( | ||
DiagnosticId, | ||
Title, | ||
MessageFormat, | ||
Category, | ||
DiagnosticSeverity.Warning, | ||
isEnabledByDefault: true, | ||
description: Description); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics | ||
=> ImmutableArray.Create(Rule); | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.PropertyDeclaration); | ||
} | ||
|
||
private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) | ||
{ | ||
var semanticModel = context.SemanticModel; | ||
var declaration = (PropertyDeclarationSyntax)context.Node; | ||
|
||
var parameterAttribute = declaration.AttributeLists | ||
.SelectMany(list => list.Attributes) | ||
.Where(attr => semanticModel.GetTypeInfo(attr).Type?.ToDisplayString() == BlazorApi.ParameterAttribute.FullTypeName) | ||
.FirstOrDefault(); | ||
|
||
if (parameterAttribute != null && IsPublic(declaration)) | ||
{ | ||
var identifierText = declaration.Identifier.Text; | ||
if (!string.IsNullOrEmpty(identifierText)) | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create( | ||
Rule, | ||
declaration.GetLocation(), | ||
identifierText)); | ||
} | ||
} | ||
} | ||
|
||
private static bool IsPublic(PropertyDeclarationSyntax declaration) | ||
=> declaration.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)); | ||
} | ||
} |
73 changes: 73 additions & 0 deletions
73
...rosoft.AspNetCore.Blazor.Analyzers/ComponentParametersShouldNotBePublicCodeFixProvider.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
|
||
namespace Microsoft.AspNetCore.Blazor.Analyzers | ||
{ | ||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ComponentParametersShouldNotBePublicCodeFixProvider)), Shared] | ||
public class ComponentParametersShouldNotBePublicCodeFixProvider : CodeFixProvider | ||
{ | ||
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.ComponentParametersShouldNotBePublic_FixTitle), Resources.ResourceManager, typeof(Resources)); | ||
|
||
public override ImmutableArray<string> FixableDiagnosticIds | ||
=> ImmutableArray.Create(ComponentParametersShouldNotBePublicAnalyzer.DiagnosticId); | ||
|
||
public sealed override FixAllProvider GetFixAllProvider() | ||
{ | ||
// See https://github.com/dotnet/roslyn/blob/master/docs/analyzers/FixAllProvider.md for more information on Fix All Providers | ||
return WellKnownFixAllProviders.BatchFixer; | ||
} | ||
|
||
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
var diagnostic = context.Diagnostics.First(); | ||
var diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
||
// Find the type declaration identified by the diagnostic. | ||
var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().First(); | ||
|
||
// Register a code action that will invoke the fix. | ||
var title = Title.ToString(); | ||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
title: title, | ||
createChangedDocument: c => GetTransformedDocumentAsync(context.Document, root, declaration), | ||
equivalenceKey: title), | ||
diagnostic); | ||
} | ||
|
||
private Task<Document> GetTransformedDocumentAsync( | ||
Document document, | ||
SyntaxNode root, | ||
PropertyDeclarationSyntax declarationNode) | ||
{ | ||
var updatedDeclarationNode = HandlePropertyDeclaration(declarationNode); | ||
var newSyntaxRoot = root.ReplaceNode(declarationNode, updatedDeclarationNode); | ||
return Task.FromResult(document.WithSyntaxRoot(newSyntaxRoot)); | ||
} | ||
|
||
private SyntaxNode HandlePropertyDeclaration(PropertyDeclarationSyntax node) | ||
{ | ||
TypeSyntax type = node.Type; | ||
if (type == null || type.IsMissing) | ||
{ | ||
return null; | ||
} | ||
|
||
var publicModifier = node.Modifiers.FirstOrDefault(m => m.IsKind(SyntaxKind.PublicKeyword)); | ||
node = node.WithModifiers( | ||
node.Modifiers.Remove(publicModifier)); | ||
return node; | ||
} | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
src/Microsoft.AspNetCore.Blazor.Analyzers/Microsoft.AspNetCore.Blazor.Analyzers.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>netstandard1.3</TargetFramework> | ||
<IncludeBuildOutput>false</IncludeBuildOutput> | ||
<NoPackageAnalysis>true</NoPackageAnalysis> | ||
<GenerateDocumentationFile>false</GenerateDocumentationFile> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="2.4.0" PrivateAssets="all" /> | ||
<PackageReference Update="NETStandard.Library" PrivateAssets="all" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Compile Update="Resources.Designer.cs"> | ||
<DesignTime>True</DesignTime> | ||
<AutoGen>True</AutoGen> | ||
<DependentUpon>Resources.resx</DependentUpon> | ||
</Compile> | ||
|
||
<EmbeddedResource Update="Resources.resx"> | ||
<Generator>ResXFileCodeGenerator</Generator> | ||
<LastGenOutput>Resources.Designer.cs</LastGenOutput> | ||
</EmbeddedResource> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Compile Include="..\shared\BlazorApi.cs" Link="shared\%(Filename)%(Extension)" /> | ||
</ItemGroup> | ||
|
||
</Project> |
100 changes: 100 additions & 0 deletions
100
src/Microsoft.AspNetCore.Blazor.Analyzers/Resources.Designer.cs
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.