Gradle のビルドスクリプトで IDEA による読み込みかどうか判定する

blog1.mammb.com


システムプロパティによる判定

val idea = System.getProperty("idea.active") == "true" ||
           System.getProperty("idea.sync.active") == "true"

if (idea) {
    // 
}
  • IDEA から Gradle タスク実行時には idea.active が設定される
  • IDEA から Gradle ビルドスクリプトからプロジェクトがリロードされた場合に idea.sync.active が設定される


オプションの設定箇所

"idea.active" は以下で設定されている。

package org.jetbrains.plugins.gradle.service.execution;

public class GradleExecutionHelper {

  private static void addIdeaParameters(@NotNull ArrayList<String> arguments) {
    arguments.add("-Didea.active=true");
    arguments.add("-Didea.version=" + getIdeaVersion());
  }

  private static void setupOperationArguments(
    @NotNull LongRunningOperation operation,
    @NotNull GradleExecutionSettings settings
  ) {
    var arguments = new ArrayList<String>();
    addSettingsArguments(arguments, settings);
    var testTaskPatterns = extractTestTaskPatterns(arguments);
    var path = renderInitScript(testTaskPatterns);
    if (path != null) {
      ContainerUtil.addAll(arguments, GradleConstants.INIT_SCRIPT_CMD_OPTION, path);
    }
    addIdeaParameters(arguments);
    operation.withArguments(arguments);
  }

}

"idea.sync.active" は以下で設定されている。

package org.jetbrains.plugins.gradle.service.project;

public class GradleProjectResolver implements ExternalSystemProjectResolver<GradleExecutionSettings> {

  private static void configureExecutionArgumentsAndVmOptions(@NotNull GradleExecutionSettings executionSettings,
                                                              @NotNull DefaultProjectResolverContext resolverCtx,
                                                              boolean isBuildSrcProject) {
    executionSettings.withArgument("-Didea.sync.active=true");
    if (resolverCtx.isResolveModulePerSourceSet()) {
      executionSettings.withArgument("-Didea.resolveSourceSetDependencies=true");
    }
    if (!isBuildSrcProject) {
      for (GradleBuildParticipant buildParticipant : executionSettings.getExecutionWorkspace().getBuildParticipants()) {
        executionSettings.withArguments(GradleConstants.INCLUDE_BUILD_CMD_OPTION, buildParticipant.getProjectPath());
      }
    }

    GradleImportCustomizer importCustomizer = GradleImportCustomizer.get();
    GradleProjectResolverUtil.createProjectResolvers(resolverCtx).forEachOrdered(extension -> {
      if (importCustomizer == null || importCustomizer.useExtraJvmArgs()) {
        // collect extra JVM arguments provided by gradle project resolver extensions
        ParametersList parametersList = new ParametersList();
        for (Pair<String, String> jvmArg : extension.getExtraJvmArgs()) {
          parametersList.addProperty(jvmArg.first, jvmArg.second);
        }
        executionSettings.withVmOptions(parametersList.getParameters());
      }
      // collect extra command-line arguments
      executionSettings.withArguments(extension.getExtraCommandLineArgs());
    });
  }
}