Can the analyzer verify that the namespaces match the file location correctly

Namespaces are traditionally named in a C # solution, so that they correspond to the default namespace for the project and the name of any subdirectories for the containing file.

For example, a file named Haddock.cs is located in a directory called Fish , and the default namespace (on the first tab of the project properties in VS) is Lakes , then the file should contain something like

 namespace Lakes.Fish { public class Haddock { } } 

The StyleCop analyzer project contains a good rule confirming that the class name matches the file name.

Is there a way to write a rule that validates a namespace name?

+6
source share
1 answer

You can access the file path from SyntaxTreeAction using Tree.FilePath off << 22>.

Once you have a path, you can analyze this and compare it with the name of all the NamesSpaceDeclarationSyntax node NamesSpaceDeclarationSyntax in the tree.

Unfortunately, I don't think there is a way to get the default namespace for a project at the moment.

Here is a brief sample that I put together and does what it can do so far. Handling / comparing the namespace path is rudimentary, and there is probably a better way to do this, but this should get you started.

 public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction((compilationSyntax) => { compilationSyntax.RegisterSyntaxTreeAction((syntaxTreeContext) => { var semModel = compilationSyntax.Compilation.GetSemanticModel(syntaxTreeContext.Tree); var filePath = syntaxTreeContext.Tree.FilePath; if (filePath == null) return; var namespaceNodes = syntaxTreeContext.Tree.GetRoot().DescendantNodes().OfType<NamespaceDeclarationSyntax>(); var parentDirectory = System.IO.Path.GetDirectoryName(filePath); // This will only work on windows and is not very robust. var parentDirectoryWithDots = parentDirectory.Replace("\\", ".").ToLower(); foreach (var ns in namespaceNodes) { var symbolInfo = semModel.GetDeclaredSymbol(ns) as INamespaceSymbol; var name = symbolInfo.ToDisplayString(); if (!parentDirectoryWithDots.EndsWith(name.ToLower().Trim())) { syntaxTreeContext.ReportDiagnostic(Diagnostic.Create( Rule, ns.Name.GetLocation(), parentDirectoryWithDots)); } } }); }); } 
+5
source

All Articles