Created
April 27, 2018 08:38
-
-
Save bogdanbujdea/054e4cef20d566081e8b0f90e79efc39 to your computer and use it in GitHub Desktop.
UsingsAnalyzerCodeFixProvider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| private static async Task<Document> GetTransformedDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) | |
| { | |
| try | |
| { | |
| SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | |
| var usings = root.DescendantNodes().OfType<UsingDirectiveSyntax>().ToList(); | |
| var orderedUsings = usings.OrderBy(o => new string(o.Name.ToString().TakeWhile(c => c != '.').ToArray())) | |
| .ThenBy(o => o.Name.ToString().Length) | |
| .ToList(); | |
| var documentEditor = await DocumentEditor.CreateAsync(document, cancellationToken); | |
| for (var index = 0; index < usings.Count; index++) | |
| { | |
| var usingStatement = usings[index]; | |
| var usingDirectiveSyntax = orderedUsings[index]; | |
| if (index > 0) | |
| { | |
| var currentNamespace = GetAssemblyNameFromNamespace(orderedUsings[index]); | |
| var lastNamespace = GetAssemblyNameFromNamespace(orderedUsings[index - 1]); | |
| if (currentNamespace != lastNamespace) //add a new line between usings from different assemblies | |
| { | |
| usingDirectiveSyntax = | |
| usingDirectiveSyntax.WithLeadingTrivia( | |
| SyntaxTriviaList.Create(SyntaxFactory.CarriageReturnLineFeed)); | |
| } | |
| } | |
| documentEditor.ReplaceNode(usingStatement, usingDirectiveSyntax); | |
| } | |
| return documentEditor.GetChangedDocument(); | |
| } | |
| catch (Exception e) | |
| { | |
| Console.WriteLine(e); | |
| return document; | |
| } | |
| } | |
| private static string GetAssemblyNameFromNamespace(UsingDirectiveSyntax usingDirective) | |
| { | |
| return new string(usingDirective.ToString().Split(' ')[1].TakeWhile(c => c != '.').ToArray()).Trim(';'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment