首页 > 解决方案 > 如何编写仅在差异代码或新添加的代码上运行的 C# 分析器?

问题描述

我有一定数量的 C# 项目。其中一些是从 TFS\AzureDevOps 克隆的,一些是从 Git 克隆的。对于这些项目,我正在编写一个自定义 C# 分析器。现在我需要检测我在分析器中设计的规则是否被新添加的代码所违反。这个想法是只对新添加的代码运行静态代码分析。所以基本上,它更多的是静态差异代码分析,其中差异产生待处理的更改。

为简单起见,当您在 Visual Studio 中创建分析器项目时,您可以从以下代码开始:

// This method has been registered as a symbol action against 'SymbolKind.NamedType'
private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
    var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;

    // Find just those named type symbols with names containing lowercase letters.
    if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower))
    {
        // For all such symbols, produce a diagnostic.
        var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);

        // Report the diagnostic
        context.ReportDiagnostic(diagnostic);
    }
}

我需要做这样的事情:

// This method has been registered as a symbol action against 'SymbolKind.NamedType'
private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
    // Before creating a diagnostic and reporting it, I want to detect
    // whether the symbol under question is from newly added code or not
    if (IsNewCode(context))
    {
        var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;

        // Find just those named type symbols with names containing lowercase letters.
        if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower))
        {
            // For all such symbols, produce a diagnostic.
            var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name);

            // Report the diagnostic
            context.ReportDiagnostic(diagnostic);
        }
    }
}

我如何在IsNewCode()这里实现该方法?

标签: c#diffvisual-studio-extensionsstatic-code-analysis

解决方案


推荐阅读