Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkstyle CustomImportOrder more than 3 definable groups?

Tags:

checkstyle

My company's Java import order standard would require more than the three definable groups that I see in checkstle, which are STANDARD_JAVA_PACKAGE, THIRD_PARTY_PACKAGE, and SPECIAL_IMPORTS. My question has two parts:

  1. Is there a way to define more custom regular expressions, or use regexes directly in the VALUE for customImportOrderRules?

  2. Can I do this at all, since com.our_company is supposed to come after all the other com. imports.

The import rules are approximately

  1. Static imports
  2. java.*
  3. javax.*
  4. com.* EXCEPT our company
  5. nthing.*
  6. org.*
  7. pthing.*
  8. com.mycompany.*
  9. anything else

Since we also enforce blank lines between groups, I can't combine 5, 6, and 7 into one and depend on sort order to keep things clean. Worst case is that we already have this defined in Intellij and just have to remember to auto-order imports every time.

like image 681
Peter L. Avatar asked Nov 17 '22 07:11

Peter L.


1 Answers

Answering your questions:

  1. According to this ticket it looks like there is no way to achieve what you need using just CustomImportOrder. Instead you should use ImportOrder, complete example below.
  2. It is possible using ImportOrder

This should work for your case:

<module name="ImportOrder">
    <property name="option" value="top"/>
    <property name="groups" value="/^java\./,javax,/^com\.(?!mycompany)/,nthing.org,pthing,com.mycompany"/>
    <property name="ordered" value="true"/>
    <property name="separated" value="true"/>
    <property name="separatedStaticGroups" value="true"/>
    <property name="sortStaticImportsAlphabetically" value="true"/>
</module>

Small clarification. Inside the groups property there are two groups /^com\.(?!mycompany)/ and com.mycompany, first one is the regexp that use negative look-ahead, second one is just common prefix string for the import.

like image 123
Dmytro Akhonin Avatar answered Dec 15 '22 02:12

Dmytro Akhonin