Search code examples
gradleintellij-ideaannotation-processing

IntelliJ enables annotation processing every time the gradle project is refreshed


I am building and running my project using IntelliJ IDEA and not Gradle.

In Build, Execution, Deployment > Compiler > Annotation Processors, I have two profiles: Default and Gradle Imported. I disabled annotation processing for both profiles. Whenever I build and run my project, it works as expected and the annotation processor does not run. However, any time the Gradle project refreshes, i.e. a dependency changed, IntelliJ re-enables annotation processing for the 'Gradle Imported' profile, so I have to manually disable it again.

Is there any way to persist the setting through Gradle refreshes? I want the annotation processor to run when doing a Gradle build but not when building locally using IntelliJ. I noticed .idea/compiler.xml gets regenerated every time I refresh the Gradle project, which seems to be what changes enabled from false to true. Is there a way to force 'enabled' to be false in this file? Thanks.

I tried to add this to my build script with 'enabled' set to false, https://dzone.com/articles/gradle-goodness-enable-compiler-annotation-process, but it didn't seem to work since this changes the IntelliJ project file and not compiler.xml.


Solution

  • I was able to find a workaround. Posting it here in case anyone else wonders across this. I updated by build.gradle file to have the following, which deletes all annotation processing settings from compiler.xml whenever a Gradle sync is done.

    task disableAnnotationProcessorInIntelliJ {
    
            def isIntelliJ = System.getProperty('idea.active') == 'true'
            if(isIntelliJ) {
                File compilerXmlFile = new File("./.idea/compiler.xml")
                Node compilerXml = new groovy.xml.XmlParser().parse(compilerXmlFile)
                Node compilerConfiguration = compilerXml.component.find { it.@name == "CompilerConfiguration" } as Node
                NodeList annotationProcessing = compilerConfiguration.annotationProcessing
                for (int i = 0; i < annotationProcessing.size(); i++) {
                    compilerConfiguration.remove(annotationProcessing.get(i) as Node)
                }
    
                StringWriter stringWriter = new StringWriter();
                groovy.xml.XmlNodePrinter nodePrinter = new groovy.xml.XmlNodePrinter(new PrintWriter(stringWriter))
                nodePrinter.setPreserveWhitespace(true)
                nodePrinter.print(compilerXml)
                compilerXmlFile.text = stringWriter.toString()
            }
    }
    
    idea {
        project {
            settings {
                taskTriggers {
                    afterSync tasks.getByName("disableAnnotationProcessorInIntelliJ")
                }
            }
        }
    }