Sort and remove (unused) using statements Roslyn script/code?

后端 未结 5 631
旧时难觅i
旧时难觅i 2020-12-31 09:34

Sort and remove (unused) using statements Roslyn script/code? I\'m looking for some .NET/Roslyn (compiler as service) code that can run through a project and sort and remov

5条回答
  •  旧时难觅i
    2020-12-31 10:01

    Roslyn CTP September 2012 provides a GetUnusedImportDirectives() method, which is of great use here.

    By modifying the OrganizeSolution sample project Matt referenced you can achieve both sorting and removing of (unused) using directives. An (outdated) version of this project can be found here: http://go.microsoft.com/fwlink/?LinkId=263977. It is outdated because document.GetUpdatedDocument() does not exist anymore,

    var document = newSolution.GetDocument(documentId);
    var transformation = document.OrganizeImports();
    var newDocument = transformation.GetUpdatedDocument();
    

    can be simplified to

    var document = newSolution.GetDocument(documentId);
    var newDocument = document.OrganizeImports();
    

    Adding newDocument = RemoveUnusedImportDirectives(newDocument); and providing the following method will do the trick.

    private static IDocument RemoveUnusedImportDirectives(IDocument document)
    {
        var root = document.GetSyntaxRoot();
        var semanticModel = document.GetSemanticModel();
    
        // An IDocument can refer to both a CSharp as well as a VisualBasic source file.
        // Therefore we need to distinguish those cases and provide appropriate casts.  
        // Since the question was tagged c# only the CSharp way is provided.
        switch (document.LanguageServices.Language)
        {
            case LanguageNames.CSharp:
                var oldUsings = ((CompilationUnitSyntax)root).Usings;
                var unusedUsings = ((SemanticModel)semanticModel).GetUnusedImportDirectives();
                var newUsings = Syntax.List(oldUsings.Where(item => !unusedUsings.Contains(item)));
                root = ((CompilationUnitSyntax)root).WithUsings(newUsings);
                document = document.UpdateSyntaxRoot(root);
                break;
    
            case LanguageNames.VisualBasic:
                // TODO
                break;
        }
        return document;
    }
    

提交回复
热议问题