Checking the Name of the File You are Analyzing
There are times when writing an analyzer that you may also want to get information about the file that contains some code you are analyzing. This information is available from Roslyn in the SyntaxTree
and provides access to things like the file encoding and the file name.
Lets say we wanted to create an analyzer that ensured all of the compilable files in our solution had file names that started with an uppercase letter. To do this, we would first register a SyntaxTreeAction
:
context.RegisterSyntaxTreeAction((syntaxTreeContext) =>
{
});
Inside that action, we will get the file path and ensure it is not null. It could be null for a few reasons, mainly when dynamically compiling snippets of code, so we will just guard against that:
var filePath = syntaxTreeContext.Tree.FilePath;
if (filePath == null)
return;
Next, we can use the System.IO.Path class to just get the filename and check if the first character is a lowercase letter. If it is a lowercase letter, then we will raise a diagnostic:
var fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
if (Char.IsLower(fileName.ToCharArray()[0]))
syntaxTreeContext.ReportDiagnostic(Diagnostic.Create(Rule,
Location.Create(syntaxTreeContext.Tree, TextSpan.FromBounds(0, 0)), fileName));
So, at the end, our diagnostic looks like this:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxTreeAction((syntaxTreeContext) =>
{
var filePath = syntaxTreeContext.Tree.FilePath;
if (filePath == null)
return;
var fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
if (Char.IsLower(fileName.ToCharArray()[0]))
syntaxTreeContext.ReportDiagnostic(Diagnostic.Create(Rule,
Location.Create(syntaxTreeContext.Tree, TextSpan.FromBounds(0, 0)), fileName));
});
}
Those are the basics for accessing file information from an analyzer. If you want to see an example of an analyzer that looks at the encoding of the file, you can look at SA1412StoreFilesAsUtf8 in the StyleCopAnalyzers GitHub project.