public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var project = context.Document.Project; TextDocument publicSurfaceAreaDocument = GetPublicSurfaceAreaDocument(project); if (publicSurfaceAreaDocument == null) { return; } var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); foreach (var diagnostic in context.Diagnostics) { var location = diagnostic.Location; var symbol = FindDeclaration(root, location, semanticModel, context.CancellationToken); if (symbol != null) { var minimalSymbolName = symbol.ToMinimalDisplayString(semanticModel, location.SourceSpan.Start, DeclarePublicAPIAnalyzer.ShortSymbolNameFormat); var publicSurfaceAreaSymbolName = DeclarePublicAPIAnalyzer.GetPublicApiName(symbol); context.RegisterCodeFix( new AdditionalDocumentChangeAction( $"Add {minimalSymbolName} to public API", c => GetFix(publicSurfaceAreaDocument, publicSurfaceAreaSymbolName, c)), diagnostic); } } }
protected override async Task <Solution> GetChangedSolutionAsync(CancellationToken cancellationToken) { var updatedPublicSurfaceAreaText = new List <KeyValuePair <DocumentId, SourceText> >(); foreach (var pair in _diagnosticsToFix) { var project = pair.Key; var diagnostics = pair.Value; var publicSurfaceAreaAdditionalDocument = GetPublicSurfaceAreaDocument(project); if (publicSurfaceAreaAdditionalDocument == null) { continue; } var sourceText = await publicSurfaceAreaAdditionalDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var groupedDiagnostics = diagnostics .Where(d => d.Location.IsInSource) .GroupBy(d => d.Location.SourceTree); var newSymbolNames = new List <string>(); foreach (var grouping in groupedDiagnostics) { var document = project.GetDocument(grouping.Key); if (document == null) { continue; } var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in grouping) { var location = diagnostic.Location; var symbol = FindDeclaration(root, location, semanticModel, cancellationToken); if (symbol != null) { var publicSurfaceAreaSymbolName = DeclarePublicAPIAnalyzer.GetPublicApiName(symbol); if (symbol != null) { newSymbolNames.Add(publicSurfaceAreaSymbolName); } } } } var newSourceText = AddSymbolNamesToSourceText(sourceText, newSymbolNames); updatedPublicSurfaceAreaText.Add(new KeyValuePair <DocumentId, SourceText>(publicSurfaceAreaAdditionalDocument.Id, newSourceText)); } var newSolution = _solution; foreach (var pair in updatedPublicSurfaceAreaText) { newSolution = newSolution.WithAdditionalDocumentText(pair.Key, pair.Value); } return(newSolution); }