-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
282 additions
and
5 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using Biwen.AutoClassGen.DiagnosticAnalyzers; | ||
using Microsoft.CodeAnalysis.CSharp.Testing; | ||
using Microsoft.CodeAnalysis.Testing; | ||
using Biwen.AutoClassGen.CodeFixProviders; | ||
|
||
namespace AutoClassGenTest; | ||
|
||
public class MyVerifier : DefaultVerifier | ||
{ | ||
public override IVerifier PushContext(string context) | ||
{ | ||
return new MyVerifier(); | ||
} | ||
|
||
public override void Equal<T>(T expected, T actual, string? message = null) | ||
{ | ||
//0,1:返回成功 | ||
if (expected is 0 && actual is 1) return; | ||
|
||
base.Equal(expected, actual, message); | ||
} | ||
} | ||
|
||
public class AddFileHeaderCodeFixProviderTest : | ||
CSharpCodeFixVerifier<FileHeaderAnalyzer, AddFileHeaderCodeFixProvider, MyVerifier> | ||
{ | ||
|
||
[Fact] | ||
public async Task Test() | ||
{ | ||
var @code = "namespace Biwen { public interface IRequest {} }"; | ||
|
||
var fixedCode = """ | ||
// Licensed to the {Product} under one or more agreements. | ||
// The {Product} licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
namespace Biwen { public interface IRequest {} } | ||
"""; | ||
|
||
Diagnostic(FileHeaderAnalyzer.DiagnosticId) | ||
.WithSpan(1, 1, 1, 1) | ||
.WithLocation(1, 1); | ||
; | ||
|
||
//设置修复器的路径: | ||
|
||
|
||
|
||
|
||
await VerifyAnalyzerAsync(@code); | ||
await VerifyCodeFixAsync(@code, fixedCode); | ||
|
||
} | ||
} |
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,41 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
|
||
<IsPackable>false</IsPackable> | ||
<IsTestProject>true</IsTestProject> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
|
||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0-1.final" PrivateAssets="all" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.12.0-1.final" PrivateAssets="all" /> | ||
|
||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.XUnit" Version="1.1.2" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.XUnit" Version="1.1.2" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing.XUnit" Version="1.1.2" /> | ||
<PackageReference Include="coverlet.collector" Version="6.0.2"> | ||
<PrivateAssets>all</PrivateAssets> | ||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||
</PackageReference> | ||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" /> | ||
<PackageReference Include="xunit" Version="2.9.0" /> | ||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2"> | ||
<PrivateAssets>all</PrivateAssets> | ||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||
</PackageReference> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Biwen.AutoClassGen.Attributes\Biwen.AutoClassGen.Attributes.csproj" /> | ||
<ProjectReference Include="..\Biwen.AutoClassGen.Gen\Biwen.AutoClassGen.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Using Include="Xunit" /> | ||
</ItemGroup> | ||
|
||
</Project> |
2 changes: 1 addition & 1 deletion
2
Biwen.AutoClassGen.Attributes/Biwen.AutoClassGen.Attributes.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
111 changes: 111 additions & 0 deletions
111
Biwen.AutoClassGen.Gen/CodeFixProviders/AddFileHeaderCodeFixProvider.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,111 @@ | ||
using Biwen.AutoClassGen.DiagnosticAnalyzers; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.Text; | ||
using System; | ||
using System.Collections.Immutable; | ||
using System.Composition; | ||
using System.IO; | ||
using System.Text.RegularExpressions; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace Biwen.AutoClassGen.CodeFixProviders; | ||
|
||
/// <summary> | ||
/// 自动给文件添加头部注释 | ||
/// </summary> | ||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AddFileHeaderCodeFixProvider))] | ||
[Shared] | ||
public class AddFileHeaderCodeFixProvider : CodeFixProvider | ||
{ | ||
private const string Title = "添加文件头部信息"; | ||
private const string ConfigFileName = "Biwen.AutoClassGen.Comment"; | ||
|
||
private const string DefaultComment = """ | ||
// Licensed to the {Product} under one or more agreements. | ||
// The {Product} licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
"""; | ||
|
||
public sealed override ImmutableArray<string> FixableDiagnosticIds | ||
{ | ||
get { return [FileHeaderAnalyzer.DiagnosticId]; } | ||
} | ||
|
||
public sealed override FixAllProvider GetFixAllProvider() | ||
{ | ||
return WellKnownFixAllProviders.BatchFixer; | ||
} | ||
|
||
public override Task RegisterCodeFixesAsync(CodeFixContext context) | ||
{ | ||
var diagnostic = context.Diagnostics[0]; | ||
var diagnosticSpan = diagnostic.Location.SourceSpan; | ||
|
||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
title: Title, | ||
createChangedDocument: c => FixDocumentAsync(context.Document, diagnosticSpan, c), | ||
equivalenceKey: Title), | ||
diagnostic); | ||
|
||
return Task.CompletedTask; | ||
} | ||
|
||
private static async Task<Document> FixDocumentAsync(Document document, TextSpan span, CancellationToken cancellationToken) | ||
{ | ||
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
|
||
//从项目配置中获取文件头部信息 | ||
var projFilePath = document.Project.FilePath ?? "C:\\test.csproj";//单元测试时没有文件路径,因此使用默认路径 | ||
|
||
var projectDirectory = Path.GetDirectoryName(projFilePath); | ||
var configFilePath = Path.Combine(projectDirectory, ConfigFileName); | ||
|
||
var comment = DefaultComment; | ||
|
||
string? copyright = "MIT"; | ||
string? author = Environment.UserName; | ||
string? title = document.Project.Name; | ||
string? version = document.Project.Version.ToString(); | ||
string? product = document.Project.AssemblyName; | ||
string? file = Path.GetFileName(document.FilePath); | ||
#pragma warning disable CA1305 // 指定 IFormatProvider | ||
string? date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); | ||
#pragma warning restore CA1305 // 指定 IFormatProvider | ||
|
||
if (File.Exists(configFilePath)) | ||
{ | ||
comment = File.ReadAllText(configFilePath, System.Text.Encoding.UTF8); | ||
//使用正则表达式替换 | ||
comment = Regex.Replace(comment, @"\{(?<key>[^}]+)\}", m => | ||
{ | ||
var key = m.Groups["key"].Value; | ||
return key switch | ||
{ | ||
"Product" => product, | ||
"Title" => title, | ||
"Version" => version, | ||
"Date" => date, | ||
"Author" => author, | ||
"Copyright" => copyright, | ||
"File" => file, | ||
_ => m.Value, | ||
}; | ||
}); | ||
} | ||
|
||
var headerComment = SyntaxFactory.Comment(comment + Environment.NewLine); | ||
var newRoot = root?.WithLeadingTrivia(headerComment); | ||
if (newRoot == null) | ||
{ | ||
return document; | ||
} | ||
var newDocument = document.WithSyntaxRoot(newRoot); | ||
|
||
return newDocument; | ||
} | ||
} |
2 changes: 1 addition & 1 deletion
2
...oClassGen.Gen/SourceGenCodeFixProvider.cs → ...eFixProviders/SourceGenCodeFixProvider.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
51 changes: 51 additions & 0 deletions
51
Biwen.AutoClassGen.Gen/DiagnosticAnalyzers/FileHeaderAnalyzer.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,51 @@ | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Text; | ||
using System.Collections.Immutable; | ||
using System.Linq; | ||
|
||
namespace Biwen.AutoClassGen.DiagnosticAnalyzers; | ||
|
||
/// <summary> | ||
/// 文件头部分析器 | ||
/// </summary> | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public class FileHeaderAnalyzer : DiagnosticAnalyzer | ||
{ | ||
public const string DiagnosticId = "GEN050"; | ||
private static readonly LocalizableString Title = "文件缺少头部信息"; | ||
private static readonly LocalizableString MessageFormat = "文件缺少头部信息"; | ||
private static readonly LocalizableString Description = "每个文件应包含头部信息."; | ||
private const string Category = "Documentation"; | ||
|
||
private static readonly DiagnosticDescriptor Rule = new( | ||
DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); | ||
|
||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => [Rule]; | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
if (context is null) | ||
return; | ||
|
||
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
context.EnableConcurrentExecution(); | ||
context.RegisterSyntaxTreeAction(AnalyzeSyntaxTree); | ||
} | ||
|
||
private static void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) | ||
{ | ||
var root = context.Tree.GetRoot(context.CancellationToken); | ||
var firstToken = root.GetFirstToken(); | ||
|
||
// 检查文件是否以注释开头 | ||
var hasHeaderComment = firstToken.LeadingTrivia.Any(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia) || trivia.IsKind(SyntaxKind.MultiLineCommentTrivia)); | ||
|
||
if (!hasHeaderComment) | ||
{ | ||
var diagnostic = Diagnostic.Create(Rule, Location.Create(context.Tree, TextSpan.FromBounds(0, 0))); | ||
context.ReportDiagnostic(diagnostic); | ||
} | ||
} | ||
} |
2 changes: 1 addition & 1 deletion
2
Biwen.AutoClassGen.Gen/SourceGenAnalyzer.cs → .../DiagnosticAnalyzers/SourceGenAnalyzer.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
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,6 @@ | ||
// Licensed to the {Product} under one or more agreements. | ||
// The {Product} licenses this file to you under the {Copyright} license. | ||
// See the LICENSE file in the project root for more information.13456789 | ||
// 1234 {Product} {File} | ||
// {Date} {Title} {Author} | ||
|
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