2

I want to add a custom warning/error to IntelliJ that triggers if my Java project contains imports to a certain package.

I have looked into Search Templates/Replace Templates, but whenever I try to type code with an "import", it gives me an "Unexpected Token" error and refuses to be created.

This is fine:

"class MyCLass {}" causes no errors, and Ok button is selectable

This is not:

"import System.out; class MyClass {}" causes an "Unexpected token" popup, and Ok button is greyed out

I also can't find examples of search templates that match on import statements. The closest thing I can find is an example in the above link where a "use static imports" checkbox is available that will make the replacement's output contain a static import.

Do search templates just not support matching on import statements for some reason, and if so why? Is there another way to do what I want to do?

Thanks in advance.

My IntelliJ version is 2022.2

Quaris
  • 361
  • 2
  • 9

2 Answers2

2

Structural search for imports/packages is not supported yet - https://youtrack.jetbrains.com/issue/IDEA-285199 .

As a workaround you can try using the following template:

<searchConfiguration name="Unnamed" text="$Type$" recursive="true" type="JAVA" pattern_context="default" search_injected="false">
  <constraint name="__context__" within="" contains="" />
  <constraint name="Type" regexp="javafx\..*" within="" contains="" />
</searchConfiguration>

Use the Import Template from Clipboard action under the tool button in the Structural Search dialog:

enter image description here

Egor Klepikov
  • 3,386
  • 5
  • 19
  • 34
1

I think "illegal package dependencies" inspection is what you are looking for. It can be found under "Settings/Editor/Inspections/JVM languages/Illegal package dependencies". You can create a custom scope for all the dependencies that you don't want in your project and apply them to the predefined "All" scope. Example

  • 1
    Yes, this solution worked. Having an "All" scope, though, also creates the custom errors inside the package in question (it is inside my project). I had to create another scope that was everything except the undesired package to apply the rule to. – Quaris Aug 11 '22 at 02:48