private void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
        {
            var tree = context.Tree;
            var root = tree.GetRoot(context.CancellationToken);

            // don't process empty files
            if (root.FullSpan.IsEmpty)
            {
                return;
            }

            if (!context.Options.TryGetEditorConfigOption(CodeStyleOptions.FileHeaderTemplate, tree, out string fileHeaderTemplate) ||
                string.IsNullOrEmpty(fileHeaderTemplate))
            {
                return;
            }

            var fileHeader = FileHeaderHelper.ParseFileHeader(root);

            if (fileHeader.IsMissing)
            {
                context.ReportDiagnostic(Diagnostic.Create(MissingHeaderDescriptor, fileHeader.GetLocation(tree)));
                return;
            }

            var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(tree.FilePath));

            if (!CompareCopyrightText(expectedFileHeader, fileHeader.CopyrightText))
            {
                context.ReportDiagnostic(Diagnostic.Create(InvalidHeaderDescriptor, fileHeader.GetLocation(tree)));
                return;
            }
        }
Example #2
0
        private async Task <SyntaxNode> GetTransformedSyntaxRootAsync(Document document, CancellationToken cancellationToken)
        {
            var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);

            var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            if (!document.Project.AnalyzerOptions.TryGetEditorConfigOption(CodeStyleOptions2.FileHeaderTemplate, tree, out string fileHeaderTemplate) ||
                string.IsNullOrEmpty(fileHeaderTemplate))
            {
                // This exception would show up as a gold bar, but as indicated we do not believe this is reachable.
                throw ExceptionUtilities.Unreachable;
            }

            var expectedFileHeader = fileHeaderTemplate.Replace("{fileName}", Path.GetFileName(document.FilePath));

            var        fileHeader = FileHeaderHelper.ParseFileHeader(root);
            SyntaxNode newSyntaxRoot;

            if (fileHeader.IsMissing)
            {
                newSyntaxRoot = AddHeader(document, root, expectedFileHeader);
            }
            else
            {
                newSyntaxRoot = ReplaceHeader(document, root, expectedFileHeader);
            }

            return(newSyntaxRoot);
        }