Skip to content
Nikita Skvortsov edited this page Nov 1, 2021 · 12 revisions

Table of Contents

Project level settings
Module level settings
IDEA project files post processing

Project level settings

Project level settings are an extension to idea.project domain object:

idea {
  project {
    settings {
      runConfigurations { }
      copyright { }
       // other project level settings
      }
    }
  }

Following top level elements are available in idea.project.settings

  • compiler - Java compiler settings
  • groovyCompiler - Groovy compiler settings
  • codeStyle - narrow set of code style settings
  • copyright - settings for copyright plugin
  • runConfigurations - container for run configuration settings
  • doNotDetectFrameworks - explicitly turn off some framework detection.
  • taskTriggers - triggers to execute a Gradle task on specific event
  • delegateActions - configure run/build/execute test delegation (IDEA or Gradle)
  • ideArtifacts - configure IDEA artifacts settings
  • encodings - configure project encoding settings

compiler

Following properties are available for compiler configuration object

  • String resourcePatterns
  • Integer processHeapSize - in megabytes
  • Boolean autoShowFirstErrorInEditor
  • Boolean displayNotificationPopup
  • Boolean clearOutputDirectory
  • Boolean addNotNullAssertions
  • Boolean enableAutomake
  • Boolean parallelCompilation
  • Boolean rebuildModuleOnDependencyChange

Javac settings of IDEA compiler

Allows to customize javac used by IDEA to compile, e.g.

idea.project.settings {
  compiler {
    javac {
      javacAdditionalOptions "-Xmaxwarns 123 -Xdoclint"
      moduleJavacAdditionalOptions = ['some' : '-aaa',
                                      'some.main' : '-bbb',
                                      'some.test' : '-ccc',
                                      'some.core' : '-ddd']
    }
  }
}

Following settings are available:

  • Boolean preferTargetJDKCompiler - use compiler of JDK, matching target jdk of a module (if available)
  • String javacAdditionalOptions - additional command line options string
  • Boolean generateDebugInfo - generate debug information
  • Boolean generateDeprecationWarnings - show warnings information
  • Boolean generateNoWarnings - suppress all warnings
  • Map moduleJavacAdditionalOptions - a map of module-specific javac parameters (module name to javac parameters string)

groovyCompiler

Following properties are available for groovyCompiler configuration object

  • excludes - allows to exclude some resources from compilation explicitly.

Sample usage for groovyCompiler

groovyCompiler {
  excludes {
    file("/path/to/file") // exclude single file
    dir("/path/to/dir", includeSubdirectories = false) // exclude a directory (with recursion flag)
  }
}

copyright

Configure copyright headers, best illustrated by following sample:

copyright {
  useDefault = "MyDefaultCopyright" // copyright profile to use by default
  profiles {                        // container for named profiles
    MyDefaultCopyright {                      // name of a profile
      notice = "My License text Here"         // license text, usually multi line
      keyword = "keywords"                
    }
    UnusedLicense {
      notice = "Another license text"
    }
}

runConfigurations

Container for run configurations. Following run configuration types are supported:

  • Application - Run a java application (by main)
  • Remote - Remote debug session
  • JUnit - Run a Unit test
  • TestNG - Run a TestNG test
  • GradleTask - Execute a Gradle task

using runConfigurations a named run configuration can be created, or default settings can be updated

runConfigurations {
  "MyApp"(Application) {                       // Create new run configuration "MyApp" that will run class foo.App
    mainClass = 'foo.App'
    moduleName = getProject().idea.module.name
  }

  defaults(JUnit) {
    vmParameters = "-Xmx2g -DmyKey=myVal"       // default parameters for all JUnit run configurations
  }

  "Run Test Method"(TestNG) {
    method "my.test.ClassName#methodName"
    moduleName idea.module.name
  }
}

Shorten Command Line settings

shortenCommandLine property controls command line shortening settings for a run configuration. Values:

  • NONE
  • MANIFEST
  • CLASSPATH_FILE
  • ARGS_FILE

Applicable to JUnit, TestNG and Application run configurations

import static org.jetbrains.gradle.ext.ShortenCommandLine.*;
runConfigurations {
  "MyTest"(Junit) {
    className = "org.sample.MyTestClass"
    shortenCommandLine = MANIFEST
  }
}

Application

  • String mainClass - class to run
  • String workingDirectory - working directory
  • String jvmArgs - jvm arguments string
  • String moduleName - name of Idea module to collect runtime classpath
  • String programParameters - program arguments string
  • Map<String, String> envs - environment variables map

JUnit

  • packageName, directory, pattern, className, method, category - String defining a test to run. If multiple properties are set, fist not null is used
  • String repeat - number of repeats ("untilStop", "untilFailure" or positive integer)
  • String workingDirectory - working directory
  • String vmParameters - jvm arguments string for tests
  • Boolean passParentEnvs - if pass parent process environment, defaults to true
  • String moduleName - name of Idea module containing tests
  • Map<String, String> envs - environment values

TestNG

  • packageName, className, method, group, suite, pattern - String defining a test to run. If multiple properties are set, fist not null is used
  • String workingDirectory - working directory
  • String vmParameters - jvm arguments string for tests
  • Boolean passParentEnvs - if pass parent process environment, defaults to true
  • String moduleName - name of Idea module containing tests
  • Map<String, String> envs - environment values

Remote

  • RemoteTransport transport - remote transport, defaults to RemoteTransport.SOCKET
  • RemoteMode mode - remote mode, defaults to RemoteMode.ATTACH
  • String host
  • Integer port
  • String sharedMemoryAddress

Gradle

  • org.gradle.api.Task task - Gradle task to be executed

doNotDetectFrameworks

Top level method accepting list of frameworks' ids

idea.settings {
  doNotDetectFrameworks("android", "web")
}

Gradle tasks triggers settings

Intellij IDEA allows to build tasks to multiple phases. Now this binding can be stored in gradle script.

idea.project.settings {
  taskTriggers {
    afterSync tasks.getByName("projects"), tasks.getByName("tasks")
  }
}

Available phases:

  • beforeSync - before each Gradle project sync. Will NOT be executed on initial import
  • afterSync - after each Gradle project sync. Will BE executed after initial import,
  • beforeBuild - before project build
  • afterBuild - after project build
  • beforeRebuild - before project re-build
  • afterRebuild - after project re-build

Delegating Run/Build and Test actions

This allows to activate delegation of Run/Build or Test actions to Gradle.

import static org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.CHOOSE_PER_TEST

idea.project.settings {
  delegateActions {
    delegateBuildRunToGradle = true // Delegate Run/Build to Gradle
    testRunner = CHOOSE_PER_TEST    // Test execution: PLATFORM, GRADLE or CHOOSE_PER_TEST
  }
}

IdeArtifacts

Allows specifying IDEA artifacts.

Sample

idea.project.settings {
  ideArtifacts {
    ArtifactName {
      archive("main.jar") {                 // pack stuff into archive
        moduleOutput(idea.module.name)      // module production classes
        dir("META-INF") {
          file("Mainfest.MF")               // file(..) arguments will be resolved according to Project.files(..)
        }
      }
      directory("lib") {                    // "directory" and "archive" can be nested
        libraryFiles(configurations.myCfg)  // will collect idea libraries from dependencies of a configuration
      }
    }
  }
}

also, artifacts can be built by Gradle task of type org.jetbrains.gradle.ext.BuildIdeArtifact

task buildMyArtifact(type: org.jetbrains.gradle.ext.BuildIdeArtifact) {
  artifact = idea.project.settings.ideArtifacts.ArtifactName
  outputDirectory = file("Custom output")   // optional, default output dir is "build/ide-artifacts/<artifact_name>"
}

Idea Artifacts DSL elements

Each artifact can be configured with following methods

  • directory(String name, Closure config) - create a directory with name, configure directory content with config
  • archive(String name, Closure config) - create a zip/jar with name, configure archive content with config
  • libraryFiles(Configuration configuration) - copy library classes of dependencies in configuration
  • moduleOutput(String moduleName) - copy production module output
  • moduleTestOutput(String moduleName) - copy test module ouput
  • moduleSrc(String moduleName) - copy module sources
  • artifact(String artifactName) - insert content of other ide artifact
  • file(Object... files) - copy files. Each argument is resolved according to project.files
  • directoryContent(Object... dirs) - copy directory contents. Each argument is resolved according to project.files
  • extractedDirectory(Object... archivePaths) - extract archives content. Each argument is resolved according to project.files

Encoding settings

Configures project encoding settings:

  • Project encodings
  • BOM policy
  • Encodings of .properties files
  • Supporting of transparent native-to-ascii conversion
  • Manual encoding mappings

Example of encoding assignment:

import org.jetbrains.gradle.ext.EncodingConfiguration.BomPolicy

idea {
  project {
    settings {
      encodings {
        encoding = 'windows-1251'
        bomPolicy = BomPolicy.WITH_NO_BOM
        properties {
          encoding = '<System Default>'
          transparentNativeToAsciiConversion = false
        }
        mapping['../sample-gradle-free/module'] = 'windows-1251'
        mapping['module'] = 'windows-1251'
        mapping['module2/src/main/java'] = 'windows-1251'
      }
    }
  }
}

<System Default> is string constant means that will be used system default encoding settings.

Also there are three kinds of BOM politics:

  • WITH_BOM
  • WITH_NO_BOM
  • WITH_BOM_ON_WINDOWS

Module level settings

Following top level elements are available in idea.module.settings

  • packagePrefix allows configuring package prefixes for module source directories
  • facets allows configuring module facets

Package prefix

Allows to configure package prefixes for source directories.

For example, we have a set of three source sets:

sourceSets {
  main.java.srcDirs = []
  main.java.srcDirs += "src"
  main.java.srcDirs += "src/main/java"
  main.java.srcDirs += "../other-root/src/main/java"
}

We can associate package prefixes for this source sets by packagePrefix map:

idea {
  module {
    settings {
      packagePrefix["src"] = "org.example"
      packagePrefix["src/main/java"] = "org.example"
      packagePrefix["../other-root/src/main/java"] = "org.example"
    }
  }
}

facets

Only SpringFacet is available

SpringFacet

Allows to configure Spring context files

idea {
  module {
    settings {
      facets {
        spring(SpringFacet) {
          contexts {
            p1 {
              file = 'spring_parent.xml' // path to xml file
            }
            
            p2 {
              file = 'spring_child.xml'
              parent = 'p1'             // name of the parent context
            }
          }
        }
      }
    }
  }
}

IDEA project files post processing

This section describes advanced functionality. Use it only as your last resort. A callback can be used to post process an IDEA project file after the sync process has finished. To achieve this, if any callbacks are registered using APIs described below, a special task processIdeaSettings will be called after import. It will perform the callbacks providing file paths or content to be updated. For iml files to exist and be modifiable, Generate *.iml files... checkbox must be set to true in Gradle settings (File | Settings | Build, Execution, Deployment | Build Tools | Gradle)

Project level files (.idea directory)

  • withIDEADir(callback) - callback will receive file pointing to .idea directory

  • withIDEAFileXml(relativeFilePath, callback) - callback will receive instance of XmlProvider pointing to an xml file with relativeFilePath relative to .idea directory

    idea.project.settings {
        withIDEADir { File dir ->
          println("Callback 1 executed with: " + dir.absolutePath)         
        }
        
        withIDEAFileXml("vcs.xml") { XmlProvider p ->
          p.asNode().component
          .find { it.@name == 'VcsDirectoryMappings' }
          .mapping.@vcs = 'Git'
        }
    

    }

Module level files (*.iml)

  • withModuleFile(callback) / withModuleXml(callback) - callback to process parent module files for gradle project (rarely needed)
  • withModuleFile(sourceSet, callback) / withModuleXml(sourceSet, callback) - callback to process module file for specific source set (main, test, etc.). ...File version callback will receive module file, ...Xml callback will receive instance of XmlProvider