private static List < ImportStatement > canonicalizeImports ( Multimap < String , ImportStatement > importsByNamespace ) { List < ImportStatement > canonicalImports = new ArrayList <> ( ) ; for ( String namespace : importsByNamespace . keySet ( ) ) { Collection < ImportStatement > allImports = importsByNamespace . get ( namespace ) ; // Find the strongest primitive across all existing imports. Every emitted import for this // namespace will use this primitive. This makes the logic simpler and cannot change runtime // behavior, but may produce spurious changes when multiple aliasing imports of differing // strength exist (which are already in violation of the style guide). ImportPrimitive strongestPrimitive = allImports . stream ( ) . map ( ImportStatement :: primitive ) . reduce ( ImportPrimitive . WEAKEST , ImportPrimitive :: stronger ) ; // Emit each aliasing import separately, as deduplicating them would require code references // to be rewritten. boolean hasAliasing = false ; for ( ImportStatement stmt : Iterables . filter ( allImports , ImportStatement :: isAliasing ) ) { canonicalImports . add ( stmt . upgrade ( strongestPrimitive ) ) ; hasAliasing = true ; } // Emit a single destructuring import with a non-empty pattern, merged from the existing // destructuring imports. boolean hasDestructuring = false ; ImmutableList < Node > destructuringNodes = allImports . stream ( ) . filter ( ImportStatement :: isDestructuring ) . flatMap ( i -> i . nodes ( ) . stream ( ) ) . collect ( toImmutableList ( ) ) ; ImmutableList < DestructuringBinding > destructures = allImports . stream ( ) . filter ( ImportStatement :: isDestructuring ) . flatMap ( i -> i . destructures ( ) . stream ( ) ) . distinct ( ) . sorted ( ) . collect ( toImmutableList ( ) ) ; if ( ! destructures . isEmpty ( ) ) { canonicalImports . add ( ImportStatement . of ( destructuringNodes , strongestPrimitive , namespace , /* alias= */ null , destructures ) ) ; hasDestructuring = true ; } // Emit a standalone import unless an aliasing or destructuring one already exists. if ( ! hasAliasing && ! hasDestructuring ) { ImmutableList < Node > standaloneNodes = allImports . stream ( ) . filter ( ImportStatement :: isStandalone ) . flatMap ( i -> i . nodes ( ) . stream ( ) ) . collect ( toImmutableList ( ) ) ; canonicalImports . add ( ImportStatement . of ( standaloneNodes , strongestPrimitive , namespace , /* alias= */ null , /* destructures= */ null ) ) ; } } // Sorting by natural order yields the correct result due to the implementation of // ImportStatement#compareTo. Collections . sort ( canonicalImports ) ; return canonicalImports ; }
Canonicalizes a list of import statements by deduplicating and merging imports for the same namespace and sorting the result .