Last active
April 27, 2018 08:31
-
-
Save bogdanbujdea/089fcf0040d524baee84e14bb04820b4 to your computer and use it in GitHub Desktop.
Register, grab usings, sort them, create diagnostic reports
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
| public override void Initialize(AnalysisContext context) | |
| { | |
| context.RegisterSyntaxTreeAction(AnalyzeTree); | |
| } | |
| private void AnalyzeTree(SyntaxTreeAnalysisContext obj) | |
| { | |
| var fileName = obj.Tree.FilePath.Split('\\').Last(); | |
| var syntaxNode = obj.Tree.GetRoot(); | |
| var descendantNodes = syntaxNode.DescendantNodes(); | |
| var usings = descendantNodes.OfType<UsingDirectiveSyntax>().ToList(); | |
| if (usings.Count == 0) | |
| return; | |
| var sortedUsings = usings.OrderBy(o => new string(o.Name.ToString().TakeWhile(c => c != '.').ToArray())) | |
| .ThenBy(o => o.Name.ToString().Length) | |
| .ToList(); | |
| for (var index = 0; index < usings.Count; index++) | |
| { | |
| var usingDirectiveSyntax = usings[index]; | |
| if (usingDirectiveSyntax.ToString() != sortedUsings[index].ToString()) | |
| { | |
| var diagnostic = Diagnostic.Create(Rule, sortedUsings[index].GetLocation(), fileName); | |
| obj.ReportDiagnostic(diagnostic); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment