From 951faea231339167a5dff089a3d1d790723aa6fb Mon Sep 17 00:00:00 2001
From: UNV
Date: Fri, 9 Aug 2024 10:59:13 +0300
Subject: [PATCH 01/16] Code reformat using IJ4 code style (part 1).
---
.../service/GradleBuildClasspathManager.java | 172 +--
.../service/GradleInstallationManager.java | 823 +++++------
.../GradleExternalTaskConfigurationType.java | 14 +-
.../GradleRuntimeConfigurationProducer.java | 6 +-
.../AbstractProjectImportErrorHandler.java | 234 ++-
.../BaseGradleProjectResolverExtension.java | 1256 +++++++++--------
.../BaseProjectImportErrorHandler.java | 189 +--
.../project/DistributionFactoryExt.java | 320 +++--
.../project/GradleAutoImportAware.java | 59 +-
.../project/GradleExecutionHelper.java | 837 +++++------
.../service/project/GradleNotification.java | 40 +-
.../GradleNotificationContributor.java | 8 +-
.../project/GradleProjectResolver.java | 757 +++++-----
.../project/GradleProjectResolverUtil.java | 35 +-
.../project/GradleStartupActivity.java | 117 +-
.../gradle/service/project/OutputWrapper.java | 92 +-
...BuildClasspathModuleGradleDataService.java | 208 ++-
.../data/ExternalProjectDataService.java | 315 +++--
.../data/ExternalProjectSerializer.java | 343 ++---
.../resolve/GradleArtifactsContributor.java | 94 +-
.../resolve/GradleBuildScriptContributor.java | 6 +-
.../resolve/GradleCommonClassNames.java | 126 +-
.../GradleConfigurationsContributor.java | 72 +-
...nfigurationsNonCodeMembersContributor.java | 111 +-
.../GradleDependenciesContributor.java | 89 +-
.../GradleIdeaPluginScriptContributor.java | 6 +-
.../resolve/GradleImplicitContributor.java | 326 +++--
...dleMavenArtifactRepositoryContributor.java | 43 +-
.../GradleMavenDeployerContributor.java | 43 +-
.../GradleMethodContextContributor.java | 32 +-
.../GradleRepositoriesContributor.java | 11 +-
.../service/resolve/GradleResolverUtil.java | 373 ++---
.../resolve/GradleRootContributor.java | 66 +-
.../resolve/GradleScriptContributor.java | 90 +-
.../GradleSettingsScriptContributor.java | 45 +-
.../resolve/GradleSimpleContributor.java | 52 +-
.../resolve/GradleSourceSetsContributor.java | 170 +--
.../resolve/GradleTaskContributor.java | 192 +--
.../GradleUnresolvedReferenceFilter.java | 20 +-
...medDomainObjectCollectionTypeEnhancer.java | 99 +-
.../resolve/dsl/GradleDslAnnotator.java | 51 +-
.../dsl/GradleDslAnnotatorFactory.java | 20 +-
.../service/settings/GradleConfigLocator.java | 81 +-
.../service/settings/GradleConfigurable.java | 58 +-
.../GradleProjectSettingsControl.java | 817 +++++------
.../settings/GradleSystemSettingsControl.java | 229 +--
.../settings/ImportFromGradleControl.java | 59 +-
.../service/task/GradleTaskManager.java | 176 ++-
.../task/GradleTaskManagerExtension.java | 24 +-
49 files changed, 4850 insertions(+), 4556 deletions(-)
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleBuildClasspathManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleBuildClasspathManager.java
index 27b802b..2d9a97e 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleBuildClasspathManager.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleBuildClasspathManager.java
@@ -33,97 +33,103 @@
@ServiceAPI(ComponentScope.PROJECT)
@ServiceImpl
public class GradleBuildClasspathManager {
- @Nonnull
- private final Project myProject;
-
- @Nonnull
- private volatile List allFilesCache;
-
- @Nonnull
- private final AtomicReference /*module build classpath*/>> myClasspathMap =
- new AtomicReference<>(new HashMap<>());
-
- @Inject
- public GradleBuildClasspathManager(@Nonnull Project project) {
- myProject = project;
- allFilesCache = new ArrayList<>();
- }
-
- @Nonnull
- public static GradleBuildClasspathManager getInstance(@Nonnull Project project) {
- return ServiceManager.getService(project, GradleBuildClasspathManager.class);
- }
-
- public void reload() {
- ExternalSystemManager, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
- assert manager != null;
- AbstractExternalSystemLocalSettings localSettings = manager.getLocalSettingsProvider().apply(myProject);
-
- Map /*module build classpath*/> map = new HashMap<>();
-
- for (final ExternalProjectBuildClasspathPojo projectBuildClasspathPojo : localSettings.getProjectBuildClasspath().values()) {
- final List projectBuildClasspath = new ArrayList<>();
- for (String path : projectBuildClasspathPojo.getProjectBuildClasspath()) {
- final VirtualFile virtualFile = ExternalSystemUtil.findLocalFileByPath(path);
- ContainerUtil.addIfNotNull(projectBuildClasspath,
- virtualFile == null || virtualFile.isDirectory() ? virtualFile : ArchiveVfsUtil.getJarRootForLocalFile(
- virtualFile));
- }
-
- for (final ExternalModuleBuildClasspathPojo moduleBuildClasspathPojo : projectBuildClasspathPojo.getModulesBuildClasspath()
- .values()) {
- final List moduleBuildClasspath = ContainerUtil.newArrayList(projectBuildClasspath);
- for (String path : moduleBuildClasspathPojo.getEntries()) {
- final VirtualFile virtualFile = ExternalSystemUtil.findLocalFileByPath(path);
- ContainerUtil.addIfNotNull(moduleBuildClasspath,
- virtualFile == null || virtualFile.isDirectory() ? virtualFile : ArchiveVfsUtil.getJarRootForLocalFile(
- virtualFile));
- }
+ @Nonnull
+ private final Project myProject;
+
+ @Nonnull
+ private volatile List allFilesCache;
- map.put(moduleBuildClasspathPojo.getPath(), moduleBuildClasspath);
- }
+ @Nonnull
+ private final AtomicReference /*module build classpath*/>> myClasspathMap =
+ new AtomicReference<>(new HashMap<>());
+
+ @Inject
+ public GradleBuildClasspathManager(@Nonnull Project project) {
+ myProject = project;
+ allFilesCache = new ArrayList<>();
}
- myClasspathMap.set(map);
+ @Nonnull
+ public static GradleBuildClasspathManager getInstance(@Nonnull Project project) {
+ return ServiceManager.getService(project, GradleBuildClasspathManager.class);
+ }
+
+ public void reload() {
+ ExternalSystemManager, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
+ assert manager != null;
+ AbstractExternalSystemLocalSettings localSettings = manager.getLocalSettingsProvider().apply(myProject);
+
+ Map /*module build classpath*/> map = new HashMap<>();
+
+ for (final ExternalProjectBuildClasspathPojo projectBuildClasspathPojo : localSettings.getProjectBuildClasspath().values()) {
+ final List projectBuildClasspath = new ArrayList<>();
+ for (String path : projectBuildClasspathPojo.getProjectBuildClasspath()) {
+ final VirtualFile virtualFile = ExternalSystemUtil.findLocalFileByPath(path);
+ ContainerUtil.addIfNotNull(
+ projectBuildClasspath,
+ virtualFile == null || virtualFile.isDirectory()
+ ? virtualFile
+ : ArchiveVfsUtil.getJarRootForLocalFile(virtualFile)
+ );
+ }
+
+ for (final ExternalModuleBuildClasspathPojo moduleBuildClasspathPojo : projectBuildClasspathPojo.getModulesBuildClasspath()
+ .values()) {
+ final List moduleBuildClasspath = ContainerUtil.newArrayList(projectBuildClasspath);
+ for (String path : moduleBuildClasspathPojo.getEntries()) {
+ final VirtualFile virtualFile = ExternalSystemUtil.findLocalFileByPath(path);
+ ContainerUtil.addIfNotNull(
+ moduleBuildClasspath,
+ virtualFile == null || virtualFile.isDirectory()
+ ? virtualFile
+ : ArchiveVfsUtil.getJarRootForLocalFile(virtualFile)
+ );
+ }
+
+ map.put(moduleBuildClasspathPojo.getPath(), moduleBuildClasspath);
+ }
+ }
+
+ myClasspathMap.set(map);
- Set set = new LinkedHashSet<>();
- for (List virtualFiles : myClasspathMap.get().values()) {
- set.addAll(virtualFiles);
+ Set set = new LinkedHashSet<>();
+ for (List virtualFiles : myClasspathMap.get().values()) {
+ set.addAll(virtualFiles);
+ }
+ allFilesCache = ContainerUtil.newArrayList(set);
+ for (PsiElementFinder finder : PsiElementFinder.EP_NAME.getExtensions(myProject)) {
+ if (finder instanceof GradleClassFinder gradleClassFinder) {
+ gradleClassFinder.clearCache();
+ break;
+ }
+ }
}
- allFilesCache = ContainerUtil.newArrayList(set);
- for (PsiElementFinder finder : PsiElementFinder.EP_NAME.getExtensions(myProject)) {
- if (finder instanceof GradleClassFinder) {
- ((GradleClassFinder)finder).clearCache();
- break;
- }
+
+ @Nonnull
+ public List getAllClasspathEntries() {
+ checkRootsValidity(allFilesCache);
+ return allFilesCache;
}
- }
-
- @Nonnull
- public List getAllClasspathEntries() {
- checkRootsValidity(allFilesCache);
- return allFilesCache;
- }
-
- @Nonnull
- public List getModuleClasspathEntries(@Nonnull String externalModulePath) {
- checkRootsValidity(myClasspathMap.get().get(externalModulePath));
- List virtualFiles = myClasspathMap.get().get(externalModulePath);
- return virtualFiles == null ? Collections.emptyList() : virtualFiles;
- }
-
- private void checkRootsValidity(@Nullable List virtualFiles) {
- if (virtualFiles == null) {
- return;
+
+ @Nonnull
+ public List getModuleClasspathEntries(@Nonnull String externalModulePath) {
+ checkRootsValidity(myClasspathMap.get().get(externalModulePath));
+ List virtualFiles = myClasspathMap.get().get(externalModulePath);
+ return virtualFiles == null ? Collections.emptyList() : virtualFiles;
}
- if (!virtualFiles.isEmpty()) {
- for (VirtualFile file : virtualFiles) {
- if (!file.isValid()) {
- reload();
- break;
+ private void checkRootsValidity(@Nullable List virtualFiles) {
+ if (virtualFiles == null) {
+ return;
+ }
+
+ if (!virtualFiles.isEmpty()) {
+ for (VirtualFile file : virtualFiles) {
+ if (!file.isValid()) {
+ reload();
+ break;
+ }
+ }
}
- }
}
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java
index 6b24104..3e2c2dd 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java
@@ -53,446 +53,459 @@
@ServiceImpl
@Singleton
public class GradleInstallationManager {
+ public static final Pattern GRADLE_JAR_FILE_PATTERN;
+ public static final Pattern ANY_GRADLE_JAR_FILE_PATTERN;
+ public static final Pattern ANT_JAR_PATTERN = Pattern.compile("ant(-(.*))?\\.jar");
+ public static final Pattern IVY_JAR_PATTERN = Pattern.compile("ivy(-(.*))?\\.jar");
+
+ private static final String[] GRADLE_START_FILE_NAMES;
+ @NonNls
+ private static final String GRADLE_ENV_PROPERTY_NAME;
+
+ static {
+ // Init static data with ability to redefine it locally.
+ GRADLE_JAR_FILE_PATTERN = Pattern.compile("gradle-(core-)?(\\d.*)\\.jar");
+ ANY_GRADLE_JAR_FILE_PATTERN = Pattern.compile("gradle-(.*)\\.jar");
+ GRADLE_START_FILE_NAMES = "gradle:gradle.cmd:gradle.sh".split(":");
+ GRADLE_ENV_PROPERTY_NAME = "GRADLE_HOME";
+ }
+
+ @Nullable
+ private Ref myCachedGradleHomeFromPath;
+
+ /**
+ * Allows to get file handles for the gradle binaries to use.
+ *
+ * @param gradleHome gradle sdk home
+ * @return file handles for the gradle binaries; null
if gradle is not discovered
+ */
+ @Nullable
+ public Collection getAllLibraries(@Nullable File gradleHome) {
+
+ if (gradleHome == null || !gradleHome.isDirectory()) {
+ return null;
+ }
- public static final Pattern GRADLE_JAR_FILE_PATTERN;
- public static final Pattern ANY_GRADLE_JAR_FILE_PATTERN;
- public static final Pattern ANT_JAR_PATTERN = Pattern.compile("ant(-(.*))?\\.jar");
- public static final Pattern IVY_JAR_PATTERN = Pattern.compile("ivy(-(.*))?\\.jar");
-
- private static final String[] GRADLE_START_FILE_NAMES;
- @NonNls
- private static final String GRADLE_ENV_PROPERTY_NAME;
-
- static {
- // Init static data with ability to redefine it locally.
- GRADLE_JAR_FILE_PATTERN = Pattern.compile("gradle-(core-)?(\\d.*)\\.jar");
- ANY_GRADLE_JAR_FILE_PATTERN = Pattern.compile("gradle-(.*)\\.jar");
- GRADLE_START_FILE_NAMES = "gradle:gradle.cmd:gradle.sh".split(":");
- GRADLE_ENV_PROPERTY_NAME = "GRADLE_HOME";
- }
-
- @Nullable
- private Ref myCachedGradleHomeFromPath;
-
- /**
- * Allows to get file handles for the gradle binaries to use.
- *
- * @param gradleHome gradle sdk home
- * @return file handles for the gradle binaries; null
if gradle is not discovered
- */
- @Nullable
- public Collection getAllLibraries(@Nullable File gradleHome) {
-
- if (gradleHome == null || !gradleHome.isDirectory()) {
- return null;
- }
-
- List result = new ArrayList<>();
+ List result = new ArrayList<>();
- File libs = new File(gradleHome, "lib");
- File[] files = libs.listFiles();
- if (files != null) {
- for (File file : files) {
- if (file.getName().endsWith(".jar")) {
- result.add(file);
+ File libs = new File(gradleHome, "lib");
+ File[] files = libs.listFiles();
+ if (files != null) {
+ for (File file : files) {
+ if (file.getName().endsWith(".jar")) {
+ result.add(file);
+ }
+ }
}
- }
- }
- File plugins = new File(libs, "plugins");
- files = plugins.listFiles();
- if (files != null) {
- for (File file : files) {
- if (file.getName().endsWith(".jar")) {
- result.add(file);
+ File plugins = new File(libs, "plugins");
+ files = plugins.listFiles();
+ if (files != null) {
+ for (File file : files) {
+ if (file.getName().endsWith(".jar")) {
+ result.add(file);
+ }
+ }
}
- }
- }
- return result.isEmpty() ? null : result;
- }
-
- @Nullable
- public File getGradleHome(@Nullable Project project, @Nonnull String linkedProjectPath) {
- return doGetGradleHome(project, linkedProjectPath);
- }
-
- /**
- * Tries to return file handle that points to the gradle installation home.
- *
- * @param project target project (if any)
- * @param linkedProjectPath path to the target linked project config
- * @return file handle that points to the gradle installation home (if any)
- */
- @Nullable
- private File doGetGradleHome(@Nullable Project project, @Nonnull String linkedProjectPath) {
- if (project == null) {
- return null;
- }
- GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedProjectPath);
- if (settings == null || settings.getDistributionType() == null) {
- return null;
- }
- return getGradleHome(settings.getDistributionType(), linkedProjectPath, settings.getGradleHome());
- }
-
- @Nullable
- public File getGradleHome(@Nonnull DistributionType distributionType, @Nonnull String linkedProjectPath, @Nullable String gradleHome) {
- File candidate = null;
- switch (distributionType) {
- case LOCAL:
- if (gradleHome != null) {
- candidate = new File(gradleHome);
- }
- break;
- case DEFAULT_WRAPPED:
- WrapperConfiguration wrapperConfiguration = GradleUtil.getWrapperConfiguration(linkedProjectPath);
- candidate = getWrappedGradleHome(linkedProjectPath, wrapperConfiguration);
- break;
- case WRAPPED:
- // not supported yet
- break;
- case BUNDLED:
- WrapperConfiguration bundledWrapperSettings = new WrapperConfiguration();
- DistributionLocator distributionLocator = new DistributionLocator();
- bundledWrapperSettings.setDistribution(distributionLocator.getDistributionFor(GradleVersion.current()));
- candidate = getWrappedGradleHome(linkedProjectPath, bundledWrapperSettings);
- break;
+ return result.isEmpty() ? null : result;
}
- File result = null;
- if (candidate != null) {
- result = isGradleSdkHome(candidate) ? candidate : null;
+ @Nullable
+ public File getGradleHome(@Nullable Project project, @Nonnull String linkedProjectPath) {
+ return doGetGradleHome(project, linkedProjectPath);
}
- if (result != null) {
- return result;
- }
- return getAutodetectedGradleHome();
- }
-
- /**
- * Tries to deduce gradle location from current environment.
- *
- * @return gradle home deduced from the current environment (if any); null
otherwise
- */
- @Nullable
- public File getAutodetectedGradleHome() {
- File result = getGradleHomeFromPath();
- return result == null ? getGradleHomeFromEnvProperty() : result;
- }
-
- /**
- * Tries to return gradle home that is defined as a dependency to the given module.
- *
- * @param module target module
- * @return file handle that points to the gradle installation home defined as a dependency of the given module (if any)
- */
- @Nullable
- public VirtualFile getGradleHome(@Nullable Module module) {
- if (module == null) {
- return null;
- }
- final VirtualFile[] roots = OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots();
- if (roots == null) {
- return null;
- }
- for (VirtualFile root : roots) {
- if (root != null && isGradleSdkHome(root)) {
- return root;
- }
- }
- return null;
- }
-
- /**
- * Tries to return gradle home defined as a dependency of the given module; falls back to the project-wide settings otherwise.
- *
- * @param module target module that can have gradle home as a dependency
- * @param project target project which gradle home setting should be used if module-specific gradle location is not defined
- * @return gradle home derived from the settings of the given entities (if any); null
otherwise
- */
- @Nullable
- public VirtualFile getGradleHome(@Nullable Module module, @Nullable Project project, @Nonnull String linkedProjectPath) {
- final VirtualFile result = getGradleHome(module);
- if (result != null) {
- return result;
- }
+ /**
+ * Tries to return file handle that points to the gradle installation home.
+ *
+ * @param project target project (if any)
+ * @param linkedProjectPath path to the target linked project config
+ * @return file handle that points to the gradle installation home (if any)
+ */
+ @Nullable
+ private File doGetGradleHome(@Nullable Project project, @Nonnull String linkedProjectPath) {
+ if (project == null) {
+ return null;
+ }
+ GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedProjectPath);
+ if (settings == null || settings.getDistributionType() == null) {
+ return null;
+ }
+ return getGradleHome(settings.getDistributionType(), linkedProjectPath, settings.getGradleHome());
+ }
+
+ @Nullable
+ public File getGradleHome(@Nonnull DistributionType distributionType, @Nonnull String linkedProjectPath, @Nullable String gradleHome) {
+ File candidate = null;
+ switch (distributionType) {
+ case LOCAL:
+ if (gradleHome != null) {
+ candidate = new File(gradleHome);
+ }
+ break;
+ case DEFAULT_WRAPPED:
+ WrapperConfiguration wrapperConfiguration = GradleUtil.getWrapperConfiguration(linkedProjectPath);
+ candidate = getWrappedGradleHome(linkedProjectPath, wrapperConfiguration);
+ break;
+ case WRAPPED:
+ // not supported yet
+ break;
+ case BUNDLED:
+ WrapperConfiguration bundledWrapperSettings = new WrapperConfiguration();
+ DistributionLocator distributionLocator = new DistributionLocator();
+ bundledWrapperSettings.setDistribution(distributionLocator.getDistributionFor(GradleVersion.current()));
+ candidate = getWrappedGradleHome(linkedProjectPath, bundledWrapperSettings);
+ break;
+ }
- final File home = getGradleHome(project, linkedProjectPath);
- return home == null ? null : LocalFileSystem.getInstance().refreshAndFindFileByIoFile(home);
- }
-
- /**
- * Tries to discover gradle installation path from the configured system path
- *
- * @return file handle for the gradle directory if it's possible to deduce from the system path; null
otherwise
- */
- @Nullable
- public File getGradleHomeFromPath() {
- Ref ref = myCachedGradleHomeFromPath;
- if (ref != null) {
- return ref.get();
- }
- String path = System.getenv("PATH");
- if (path == null) {
- return null;
- }
- for (String pathEntry : path.split(File.pathSeparator)) {
- File dir = new File(pathEntry);
- if (!dir.isDirectory()) {
- continue;
- }
- for (String fileName : GRADLE_START_FILE_NAMES) {
- File startFile = new File(dir, fileName);
- if (startFile.isFile()) {
- File candidate = dir.getParentFile();
- if (isGradleSdkHome(candidate)) {
- myCachedGradleHomeFromPath = new Ref(candidate);
- return candidate;
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Tries to discover gradle installation via environment property.
- *
- * @return file handle for the gradle directory deduced from the system property (if any)
- */
- @Nullable
- public File getGradleHomeFromEnvProperty() {
- String path = System.getenv(GRADLE_ENV_PROPERTY_NAME);
- if (path == null) {
- return null;
- }
- File candidate = new File(path);
- return isGradleSdkHome(candidate) ? candidate : null;
- }
-
- /**
- * Does the same job as {@link #isGradleSdkHome(File)} for the given virtual file.
- *
- * @param file gradle installation home candidate
- * @return true
if given file points to the gradle installation; false
otherwise
- */
- public boolean isGradleSdkHome(@Nullable VirtualFile file) {
- if (file == null) {
- return false;
- }
- return isGradleSdkHome(new File(file.getPath()));
- }
-
- /**
- * Allows to answer if given virtual file points to the gradle installation root.
- *
- * @param file gradle installation root candidate
- * @return true
if we consider that given file actually points to the gradle installation root;
- * false
otherwise
- */
- public boolean isGradleSdkHome(@Nullable File file) {
- if (file == null) {
- return false;
- }
- final File libs = new File(file, "lib");
- if (!libs.isDirectory()) {
- if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
- GradleLog.LOG.info(String.format(
- "Gradle sdk check failed for the path '%s'. Reason: it doesn't have a child directory named 'lib'", file.getAbsolutePath()
- ));
- }
- return false;
- }
+ File result = null;
+ if (candidate != null) {
+ result = isGradleSdkHome(candidate) ? candidate : null;
+ }
- final boolean found = isGradleSdk(libs.listFiles());
- if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
- GradleLog.LOG.info(String.format("Gradle home check %s for the path '%s'", found ? "passed" : "failed", file.getAbsolutePath()));
- }
- return found;
- }
-
- /**
- * Allows to answer if given virtual file points to the gradle installation root.
- *
- * @param file gradle installation root candidate
- * @return true
if we consider that given file actually points to the gradle installation root;
- * false
otherwise
- */
- public boolean isGradleSdkHome(String gradleHomePath) {
- return isGradleSdkHome(new File(gradleHomePath));
- }
-
- /**
- * Allows to answer if given files contain the one from gradle installation.
- *
- * @param files files to process
- * @return true
if one of the given files is from the gradle installation; false
otherwise
- */
- public boolean isGradleSdk(@Nullable VirtualFile... files) {
- if (files == null) {
- return false;
- }
- File[] arg = new File[files.length];
- for (int i = 0; i < files.length; i++) {
- arg[i] = new File(files[i].getPath());
+ if (result != null) {
+ return result;
+ }
+ return getAutodetectedGradleHome();
+ }
+
+ /**
+ * Tries to deduce gradle location from current environment.
+ *
+ * @return gradle home deduced from the current environment (if any); null
otherwise
+ */
+ @Nullable
+ public File getAutodetectedGradleHome() {
+ File result = getGradleHomeFromPath();
+ return result == null ? getGradleHomeFromEnvProperty() : result;
+ }
+
+ /**
+ * Tries to return gradle home that is defined as a dependency to the given module.
+ *
+ * @param module target module
+ * @return file handle that points to the gradle installation home defined as a dependency of the given module (if any)
+ */
+ @Nullable
+ public VirtualFile getGradleHome(@Nullable Module module) {
+ if (module == null) {
+ return null;
+ }
+ final VirtualFile[] roots = OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots();
+ if (roots == null) {
+ return null;
+ }
+ for (VirtualFile root : roots) {
+ if (root != null && isGradleSdkHome(root)) {
+ return root;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Tries to return gradle home defined as a dependency of the given module; falls back to the project-wide settings otherwise.
+ *
+ * @param module target module that can have gradle home as a dependency
+ * @param project target project which gradle home setting should be used if module-specific gradle location is not defined
+ * @return gradle home derived from the settings of the given entities (if any); null
otherwise
+ */
+ @Nullable
+ public VirtualFile getGradleHome(@Nullable Module module, @Nullable Project project, @Nonnull String linkedProjectPath) {
+ final VirtualFile result = getGradleHome(module);
+ if (result != null) {
+ return result;
+ }
+
+ final File home = getGradleHome(project, linkedProjectPath);
+ return home == null ? null : LocalFileSystem.getInstance().refreshAndFindFileByIoFile(home);
}
- return isGradleSdk(arg);
- }
- private boolean isGradleSdk(@Nullable File... files) {
- return findGradleJar(files) != null;
- }
+ /**
+ * Tries to discover gradle installation path from the configured system path
+ *
+ * @return file handle for the gradle directory if it's possible to deduce from the system path; null
otherwise
+ */
+ @Nullable
+ public File getGradleHomeFromPath() {
+ Ref ref = myCachedGradleHomeFromPath;
+ if (ref != null) {
+ return ref.get();
+ }
+ String path = System.getenv("PATH");
+ if (path == null) {
+ return null;
+ }
+ for (String pathEntry : path.split(File.pathSeparator)) {
+ File dir = new File(pathEntry);
+ if (!dir.isDirectory()) {
+ continue;
+ }
+ for (String fileName : GRADLE_START_FILE_NAMES) {
+ File startFile = new File(dir, fileName);
+ if (startFile.isFile()) {
+ File candidate = dir.getParentFile();
+ if (isGradleSdkHome(candidate)) {
+ myCachedGradleHomeFromPath = new Ref(candidate);
+ return candidate;
+ }
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Tries to discover gradle installation via environment property.
+ *
+ * @return file handle for the gradle directory deduced from the system property (if any)
+ */
+ @Nullable
+ public File getGradleHomeFromEnvProperty() {
+ String path = System.getenv(GRADLE_ENV_PROPERTY_NAME);
+ if (path == null) {
+ return null;
+ }
+ File candidate = new File(path);
+ return isGradleSdkHome(candidate) ? candidate : null;
+ }
+
+ /**
+ * Does the same job as {@link #isGradleSdkHome(File)} for the given virtual file.
+ *
+ * @param file gradle installation home candidate
+ * @return true
if given file points to the gradle installation; false
otherwise
+ */
+ public boolean isGradleSdkHome(@Nullable VirtualFile file) {
+ return file != null && isGradleSdkHome(new File(file.getPath()));
+ }
+
+ /**
+ * Allows to answer if given virtual file points to the gradle installation root.
+ *
+ * @param file gradle installation root candidate
+ * @return true
if we consider that given file actually points to the gradle installation root;
+ * false
otherwise
+ */
+ public boolean isGradleSdkHome(@Nullable File file) {
+ if (file == null) {
+ return false;
+ }
+ final File libs = new File(file, "lib");
+ if (!libs.isDirectory()) {
+ if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
+ GradleLog.LOG.info(String.format(
+ "Gradle sdk check failed for the path '%s'. Reason: it doesn't have a child directory named 'lib'",
+ file.getAbsolutePath()
+ ));
+ }
+ return false;
+ }
- @Nullable
- private File findGradleJar(@Nullable File... files) {
- if (files == null) {
- return null;
- }
- for (File file : files) {
- if (GRADLE_JAR_FILE_PATTERN.matcher(file.getName()).matches()) {
- return file;
- }
+ final boolean found = isGradleSdk(libs.listFiles());
+ if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
+ GradleLog.LOG.info(String.format(
+ "Gradle home check %s for the path '%s'",
+ found ? "passed" : "failed",
+ file.getAbsolutePath()
+ ));
+ }
+ return found;
+ }
+
+ /**
+ * Allows to answer if given virtual file points to the gradle installation root.
+ *
+ * @param file gradle installation root candidate
+ * @return true
if we consider that given file actually points to the gradle installation root;
+ * false
otherwise
+ */
+ public boolean isGradleSdkHome(String gradleHomePath) {
+ return isGradleSdkHome(new File(gradleHomePath));
+ }
+
+ /**
+ * Allows to answer if given files contain the one from gradle installation.
+ *
+ * @param files files to process
+ * @return true
if one of the given files is from the gradle installation; false
otherwise
+ */
+ public boolean isGradleSdk(@Nullable VirtualFile... files) {
+ if (files == null) {
+ return false;
+ }
+ File[] arg = new File[files.length];
+ for (int i = 0; i < files.length; i++) {
+ arg[i] = new File(files[i].getPath());
+ }
+ return isGradleSdk(arg);
}
- if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
- StringBuilder filesInfo = new StringBuilder();
- for (File file : files) {
- filesInfo.append(file.getAbsolutePath()).append(';');
- }
- if (filesInfo.length() > 0) {
- filesInfo.setLength(filesInfo.length() - 1);
- }
- GradleLog.LOG.info(String.format(
- "Gradle sdk check fails. Reason: no one of the given files matches gradle jar pattern (%s). Files: %s",
- GRADLE_JAR_FILE_PATTERN.toString(), filesInfo
- ));
+ private boolean isGradleSdk(@Nullable File... files) {
+ return findGradleJar(files) != null;
}
- return null;
- }
-
- /**
- * Allows to ask for the classpath roots of the classes that are additionally provided by the gradle integration (e.g. gradle class
- * files, bundled groovy-all jar etc).
- *
- * @param project target project to use for gradle home retrieval
- * @return classpath roots of the classes that are additionally provided by the gradle integration (if any);
- * null
otherwise
- */
- @Nullable
- public List getClassRoots(@Nullable Project project) {
- List files = getClassRoots(project, null);
- if (files == null) return null;
- final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
- return ContainerUtil.mapNotNull(files, new Function() {
- @Override
- public VirtualFile apply(File file) {
- final VirtualFile virtualFile = localFileSystem.refreshAndFindFileByIoFile(file);
- return virtualFile != null ? ArchiveVfsUtil.getArchiveRootForLocalFile(virtualFile) : null;
- }
- });
- }
-
- @Nullable
- public List getClassRoots(@Nullable Project project, @Nullable String rootProjectPath) {
- if (project == null) return null;
-
- if (rootProjectPath == null) {
- for (Module module : ModuleManager.getInstance(project).getModules()) {
- rootProjectPath = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY);
- List result = findGradleSdkClasspath(project, rootProjectPath);
- if (!result.isEmpty()) return result;
- }
- }
- else {
- return findGradleSdkClasspath(project, rootProjectPath);
+ @Nullable
+ private File findGradleJar(@Nullable File... files) {
+ if (files == null) {
+ return null;
+ }
+ for (File file : files) {
+ if (GRADLE_JAR_FILE_PATTERN.matcher(file.getName()).matches()) {
+ return file;
+ }
+ }
+
+ if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
+ StringBuilder filesInfo = new StringBuilder();
+ for (File file : files) {
+ filesInfo.append(file.getAbsolutePath()).append(';');
+ }
+ if (filesInfo.length() > 0) {
+ filesInfo.setLength(filesInfo.length() - 1);
+ }
+ GradleLog.LOG.info(String.format(
+ "Gradle sdk check fails. Reason: no one of the given files matches gradle jar pattern (%s). Files: %s",
+ GRADLE_JAR_FILE_PATTERN.toString(), filesInfo
+ ));
+ }
+
+ return null;
+ }
+
+ /**
+ * Allows to ask for the classpath roots of the classes that are additionally provided by the gradle integration (e.g. gradle class
+ * files, bundled groovy-all jar etc).
+ *
+ * @param project target project to use for gradle home retrieval
+ * @return classpath roots of the classes that are additionally provided by the gradle integration (if any);
+ * null
otherwise
+ */
+ @Nullable
+ public List getClassRoots(@Nullable Project project) {
+ List files = getClassRoots(project, null);
+ if (files == null) {
+ return null;
+ }
+ final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
+ return ContainerUtil.mapNotNull(files, new Function() {
+ @Override
+ public VirtualFile apply(File file) {
+ final VirtualFile virtualFile = localFileSystem.refreshAndFindFileByIoFile(file);
+ return virtualFile != null ? ArchiveVfsUtil.getArchiveRootForLocalFile(virtualFile) : null;
+ }
+ });
+ }
+
+ @Nullable
+ public List getClassRoots(@Nullable Project project, @Nullable String rootProjectPath) {
+ if (project == null) {
+ return null;
+ }
+
+ if (rootProjectPath == null) {
+ for (Module module : ModuleManager.getInstance(project).getModules()) {
+ rootProjectPath = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY);
+ List result = findGradleSdkClasspath(project, rootProjectPath);
+ if (!result.isEmpty()) {
+ return result;
+ }
+ }
+ }
+ else {
+ return findGradleSdkClasspath(project, rootProjectPath);
+ }
+
+ return null;
}
- return null;
- }
+ private List findGradleSdkClasspath(Project project, String rootProjectPath) {
+ List result = new ArrayList();
- private List findGradleSdkClasspath(Project project, String rootProjectPath) {
- List result = new ArrayList();
+ if (StringUtil.isEmpty(rootProjectPath)) {
+ return result;
+ }
- if (StringUtil.isEmpty(rootProjectPath)) return result;
+ File gradleHome = getGradleHome(project, rootProjectPath);
- File gradleHome = getGradleHome(project, rootProjectPath);
+ if (gradleHome == null || !gradleHome.isDirectory()) {
+ return result;
+ }
- if (gradleHome == null || !gradleHome.isDirectory()) {
- return result;
- }
+ final Collection libraries = getAllLibraries(gradleHome);
+ if (libraries == null) {
+ return result;
+ }
- final Collection libraries = getAllLibraries(gradleHome);
- if (libraries == null) {
- return result;
- }
+ for (File file : libraries) {
+ if (isGradleBuildClasspathLibrary(file)) {
+ ContainerUtil.addIfNotNull(result, file);
+ }
+ }
- for (File file : libraries) {
- if (isGradleBuildClasspathLibrary(file)) {
- ContainerUtil.addIfNotNull(result, file);
- }
- }
+ File src = new File(gradleHome, "src");
+ if (src.isDirectory()) {
+ if (new File(src, "org").isDirectory()) {
+ addRoots(result, src);
+ }
+ else {
+ addRoots(result, src.listFiles());
+ }
+ }
- File src = new File(gradleHome, "src");
- if (src.isDirectory()) {
- if (new File(src, "org").isDirectory()) {
- addRoots(result, src);
- }
- else {
- addRoots(result, src.listFiles());
- }
+ return result;
}
- return result;
- }
-
- private boolean isGradleBuildClasspathLibrary(File file) {
- String fileName = file.getName();
- return ANY_GRADLE_JAR_FILE_PATTERN.matcher(fileName).matches()
- || ANT_JAR_PATTERN.matcher(fileName).matches()
- || IVY_JAR_PATTERN.matcher(fileName).matches()
- || GroovyConfigUtils.matchesGroovyAll(fileName);
- }
-
- private void addRoots(@Nonnull List result, @Nullable File... files) {
- if (files == null) return;
- for (File file : files) {
- if (file == null || !file.isDirectory()) continue;
- result.add(0, file);
+ private boolean isGradleBuildClasspathLibrary(File file) {
+ String fileName = file.getName();
+ return ANY_GRADLE_JAR_FILE_PATTERN.matcher(fileName).matches()
+ || ANT_JAR_PATTERN.matcher(fileName).matches()
+ || IVY_JAR_PATTERN.matcher(fileName).matches()
+ || GroovyConfigUtils.matchesGroovyAll(fileName);
}
- }
- private File getWrappedGradleHome(String linkedProjectPath, @Nullable final WrapperConfiguration wrapperConfiguration) {
- if (wrapperConfiguration == null) {
- return null;
+ private void addRoots(@Nonnull List result, @Nullable File... files) {
+ if (files == null) {
+ return;
+ }
+ for (File file : files) {
+ if (file == null || !file.isDirectory()) {
+ continue;
+ }
+ result.add(0, file);
+ }
}
- File gradleSystemDir;
- if (Wrapper.PathBase.PROJECT.name().equals(wrapperConfiguration.getDistributionBase())) {
- gradleSystemDir = new File(linkedProjectPath, ".gradle");
- }
- else {
- gradleSystemDir = StartParameter.DEFAULT_GRADLE_USER_HOME;
- }
- if (!gradleSystemDir.isDirectory()) {
- return null;
- }
+ private File getWrappedGradleHome(String linkedProjectPath, @Nullable final WrapperConfiguration wrapperConfiguration) {
+ if (wrapperConfiguration == null) {
+ return null;
+ }
+ File gradleSystemDir;
- PathAssembler.LocalDistribution localDistribution =
- new PathAssembler(gradleSystemDir, new File(linkedProjectPath)).getDistribution(wrapperConfiguration);
+ if (Wrapper.PathBase.PROJECT.name().equals(wrapperConfiguration.getDistributionBase())) {
+ gradleSystemDir = new File(linkedProjectPath, ".gradle");
+ }
+ else {
+ gradleSystemDir = StartParameter.DEFAULT_GRADLE_USER_HOME;
+ }
+ if (!gradleSystemDir.isDirectory()) {
+ return null;
+ }
- if (localDistribution.getDistributionDir() == null) {
- return null;
- }
+ PathAssembler.LocalDistribution localDistribution =
+ new PathAssembler(gradleSystemDir, new File(linkedProjectPath)).getDistribution(wrapperConfiguration);
+
+ if (localDistribution.getDistributionDir() == null) {
+ return null;
+ }
- File[] distFiles = localDistribution.getDistributionDir().listFiles(new FileFilter() {
- @Override
- public boolean accept(File f) {
- return f.isDirectory() && StringUtil.startsWith(f.getName(), "gradle-");
- }
- });
+ File[] distFiles = localDistribution.getDistributionDir().listFiles(new FileFilter() {
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() && StringUtil.startsWith(f.getName(), "gradle-");
+ }
+ });
- return distFiles == null || distFiles.length == 0 ? null : distFiles[0];
- }
+ return distFiles == null || distFiles.length == 0 ? null : distFiles[0];
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleExternalTaskConfigurationType.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleExternalTaskConfigurationType.java
index fb816cc..b4d3946 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleExternalTaskConfigurationType.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleExternalTaskConfigurationType.java
@@ -27,12 +27,12 @@
*/
@ExtensionImpl
public class GradleExternalTaskConfigurationType extends AbstractExternalSystemTaskConfigurationType {
- @Nonnull
- public static GradleExternalTaskConfigurationType getInstance() {
- return EP_NAME.findExtensionOrFail(GradleExternalTaskConfigurationType.class);
- }
+ @Nonnull
+ public static GradleExternalTaskConfigurationType getInstance() {
+ return EP_NAME.findExtensionOrFail(GradleExternalTaskConfigurationType.class);
+ }
- public GradleExternalTaskConfigurationType() {
- super(GradleConstants.SYSTEM_ID);
- }
+ public GradleExternalTaskConfigurationType() {
+ super(GradleConstants.SYSTEM_ID);
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleRuntimeConfigurationProducer.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleRuntimeConfigurationProducer.java
index ff59a37..6d25620 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleRuntimeConfigurationProducer.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/execution/GradleRuntimeConfigurationProducer.java
@@ -24,7 +24,7 @@
*/
@ExtensionImpl
public class GradleRuntimeConfigurationProducer extends AbstractExternalSystemRuntimeConfigurationProducer {
- public GradleRuntimeConfigurationProducer() {
- super(GradleExternalTaskConfigurationType.getInstance());
- }
+ public GradleRuntimeConfigurationProducer() {
+ super(GradleExternalTaskConfigurationType.getInstance());
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/AbstractProjectImportErrorHandler.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/AbstractProjectImportErrorHandler.java
index 0cdacf7..94ba688 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/AbstractProjectImportErrorHandler.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/AbstractProjectImportErrorHandler.java
@@ -29,129 +29,113 @@
* @author Vladislav.Soroka
* @since 10/16/13
*/
-public abstract class AbstractProjectImportErrorHandler
-{
- public static final String OPEN_GRADLE_SETTINGS = "Please fix the project's Gradle settings.";
- public static final String SET_UP_HTTP_PROXY = "If you are behind an HTTP proxy, please configure the proxy settings either in IDE or Gradle.";
- public static final String UNEXPECTED_ERROR_FILE_BUG = "This is an unexpected error. Please file a bug containing the idea.log file.";
- public static final String FIX_GRADLE_VERSION = "Please point to a supported Gradle version in the project's Gradle settings or in the project's" +
- " Gradle wrapper (if applicable.)";
-
- public static final Pattern UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN;
- public static final Pattern MISSING_METHOD_PATTERN;
- public static final Pattern ERROR_LOCATION_PATTERN;
- private static final Pattern ERROR_IN_FILE_PATTERN;
-
- static
- {
- UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN = Pattern.compile("Gradle version .* is required.*");
- MISSING_METHOD_PATTERN = Pattern.compile("org.gradle.api.internal.MissingMethodException: Could not find method (.*?) .*");
- ERROR_LOCATION_PATTERN = Pattern.compile("Build file '(.*)' line: ([\\d]+)");
- ERROR_IN_FILE_PATTERN = Pattern.compile("Build file '(.*)'");
- }
-
- public static final String EMPTY_LINE = "\n\n";
-
- @Nullable
- public abstract ExternalSystemException getUserFriendlyError(@Nonnull Throwable error, @Nonnull String projectPath,
- @Nullable String buildFilePath);
-
- @Nonnull
- public Pair getRootCauseAndLocation(@Nonnull Throwable error)
- {
- Throwable rootCause = error;
- String location = null;
- while(true)
- {
- if(location == null)
- {
- location = getLocationFrom(rootCause);
- }
- if(rootCause.getCause() == null || rootCause.getCause().getMessage() == null)
- {
- break;
- }
- rootCause = rootCause.getCause();
- }
- //noinspection ConstantConditions
- return Pair.create(rootCause, location);
- }
-
- @Nullable
- public String getLocationFrom(@Nonnull Throwable error)
- {
- String errorToString = error.toString();
- if(errorToString.contains("LocationAwareException"))
- {
- // LocationAwareException is never passed, but converted into a PlaceholderException that has the toString value of the original
- // LocationAwareException.
- String location = error.getMessage();
- if(location != null && location.startsWith("Build file '"))
- {
- // Only the first line contains the location of the error. Discard the rest.
- String[] lines = StringUtil.splitByLines(location);
- return lines.length > 0 ? lines[0] : null;
- }
- }
- return null;
- }
-
- @Nonnull
- public ExternalSystemException createUserFriendlyError(@Nonnull String msg, @Nullable String location, @Nonnull String... quickFixes)
- {
- String newMsg = msg;
- if(!newMsg.isEmpty() && Character.isLowerCase(newMsg.charAt(0)))
- {
- // Message starts with lower case letter. Sentences should start with uppercase.
- newMsg = "Cause: " + newMsg;
- }
-
- if(!StringUtil.isEmpty(location))
- {
- Pair pair = getErrorLocation(location);
- if(pair != null)
- {
- return new LocationAwareExternalSystemException(newMsg, pair.first, pair.getSecond(), quickFixes);
- }
- }
- return new ExternalSystemException(newMsg, null, quickFixes);
- }
-
-
- @Nullable
- private static Pair getErrorLocation(@Nonnull String location)
- {
- Matcher matcher = ERROR_LOCATION_PATTERN.matcher(location);
- if(matcher.matches())
- {
- String filePath = matcher.group(1);
- int line = -1;
- try
- {
- line = Integer.parseInt(matcher.group(2));
- }
- catch(NumberFormatException e)
- {
- // ignored.
- }
- return Pair.create(filePath, line);
- }
-
- matcher = ERROR_IN_FILE_PATTERN.matcher(location);
- if(matcher.matches())
- {
- String filePath = matcher.group(1);
- return Pair.create(filePath, -1);
- }
- return null;
- }
-
-
- @Nullable
- public String parseMissingMethod(@Nonnull String rootCauseText)
- {
- Matcher matcher = MISSING_METHOD_PATTERN.matcher(rootCauseText);
- return matcher.find() ? matcher.group(1) : null;
- }
+public abstract class AbstractProjectImportErrorHandler {
+ public static final String OPEN_GRADLE_SETTINGS = "Please fix the project's Gradle settings.";
+ public static final String SET_UP_HTTP_PROXY =
+ "If you are behind an HTTP proxy, please configure the proxy settings either in IDE or Gradle.";
+ public static final String UNEXPECTED_ERROR_FILE_BUG = "This is an unexpected error. Please file a bug containing the idea.log file.";
+ public static final String FIX_GRADLE_VERSION =
+ "Please point to a supported Gradle version in the project's Gradle settings or in the project's" +
+ " Gradle wrapper (if applicable.)";
+
+ public static final Pattern UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN;
+ public static final Pattern MISSING_METHOD_PATTERN;
+ public static final Pattern ERROR_LOCATION_PATTERN;
+ private static final Pattern ERROR_IN_FILE_PATTERN;
+
+ static {
+ UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN = Pattern.compile("Gradle version .* is required.*");
+ MISSING_METHOD_PATTERN = Pattern.compile("org.gradle.api.internal.MissingMethodException: Could not find method (.*?) .*");
+ ERROR_LOCATION_PATTERN = Pattern.compile("Build file '(.*)' line: ([\\d]+)");
+ ERROR_IN_FILE_PATTERN = Pattern.compile("Build file '(.*)'");
+ }
+
+ public static final String EMPTY_LINE = "\n\n";
+
+ @Nullable
+ public abstract ExternalSystemException getUserFriendlyError(
+ @Nonnull Throwable error, @Nonnull String projectPath,
+ @Nullable String buildFilePath
+ );
+
+ @Nonnull
+ public Pair getRootCauseAndLocation(@Nonnull Throwable error) {
+ Throwable rootCause = error;
+ String location = null;
+ while (true) {
+ if (location == null) {
+ location = getLocationFrom(rootCause);
+ }
+ if (rootCause.getCause() == null || rootCause.getCause().getMessage() == null) {
+ break;
+ }
+ rootCause = rootCause.getCause();
+ }
+ //noinspection ConstantConditions
+ return Pair.create(rootCause, location);
+ }
+
+ @Nullable
+ public String getLocationFrom(@Nonnull Throwable error) {
+ String errorToString = error.toString();
+ if (errorToString.contains("LocationAwareException")) {
+ // LocationAwareException is never passed, but converted into a PlaceholderException that has the toString value of the original
+ // LocationAwareException.
+ String location = error.getMessage();
+ if (location != null && location.startsWith("Build file '")) {
+ // Only the first line contains the location of the error. Discard the rest.
+ String[] lines = StringUtil.splitByLines(location);
+ return lines.length > 0 ? lines[0] : null;
+ }
+ }
+ return null;
+ }
+
+ @Nonnull
+ public ExternalSystemException createUserFriendlyError(@Nonnull String msg, @Nullable String location, @Nonnull String... quickFixes) {
+ String newMsg = msg;
+ if (!newMsg.isEmpty() && Character.isLowerCase(newMsg.charAt(0))) {
+ // Message starts with lower case letter. Sentences should start with uppercase.
+ newMsg = "Cause: " + newMsg;
+ }
+
+ if (!StringUtil.isEmpty(location)) {
+ Pair pair = getErrorLocation(location);
+ if (pair != null) {
+ return new LocationAwareExternalSystemException(newMsg, pair.first, pair.getSecond(), quickFixes);
+ }
+ }
+ return new ExternalSystemException(newMsg, null, quickFixes);
+ }
+
+
+ @Nullable
+ private static Pair getErrorLocation(@Nonnull String location) {
+ Matcher matcher = ERROR_LOCATION_PATTERN.matcher(location);
+ if (matcher.matches()) {
+ String filePath = matcher.group(1);
+ int line = -1;
+ try {
+ line = Integer.parseInt(matcher.group(2));
+ }
+ catch (NumberFormatException e) {
+ // ignored.
+ }
+ return Pair.create(filePath, line);
+ }
+
+ matcher = ERROR_IN_FILE_PATTERN.matcher(location);
+ if (matcher.matches()) {
+ String filePath = matcher.group(1);
+ return Pair.create(filePath, -1);
+ }
+ return null;
+ }
+
+
+ @Nullable
+ public String parseMissingMethod(@Nonnull String rootCauseText) {
+ Matcher matcher = MISSING_METHOD_PATTERN.matcher(rootCauseText);
+ return matcher.find() ? matcher.group(1) : null;
+ }
}
-
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java
index 550473b..04154bb 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java
@@ -84,664 +84,714 @@
*/
@ExtensionImpl(order = "last")
public class BaseGradleProjectResolverExtension implements GradleProjectResolverExtension {
- private static final Logger LOG = Logger.getInstance(BaseGradleProjectResolverExtension.class);
-
- @Nonnull
- @NonNls
- private static final String UNRESOLVED_DEPENDENCY_PREFIX = "unresolved dependency - ";
- private static final String MAIN_SOURCE_SET = "main";
- private static final String TEST_SOURCE_SET = "test";
-
- @Nonnull
- private ProjectResolverContext resolverCtx;
- @Nonnull
- private final BaseProjectImportErrorHandler myErrorHandler = new BaseProjectImportErrorHandler();
-
- @Override
- public void setProjectResolverContext(@Nonnull ProjectResolverContext projectResolverContext) {
- resolverCtx = projectResolverContext;
- }
-
- @Override
- public void setNext(@Nonnull GradleProjectResolverExtension next) {
- // should be the last extension in the chain
- }
-
- @Nullable
- @Override
- public GradleProjectResolverExtension getNext() {
- return null;
- }
-
- @Nonnull
- @Override
- public ProjectData createProject() {
- final String projectDirPath = resolverCtx.getProjectPath();
- final IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
- return new ProjectData(GradleConstants.SYSTEM_ID, ideaProject.getName(), projectDirPath, projectDirPath);
- }
-
- @Nonnull
- @Override
- public JavaProjectData createJavaProjectData() {
- final String projectDirPath = resolverCtx.getProjectPath();
- final IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
-
- // Gradle API doesn't expose gradleProject compile output path yet.
- JavaProjectData javaProjectData = new JavaProjectData(GradleConstants.SYSTEM_ID, projectDirPath + "/build/classes");
- javaProjectData.setJdkVersion(ideaProject.getJdkName());
-
- LanguageLevel languageLevel = StringUtil.parseEnum(ideaProject.getLanguageLevel().getLevel(), null, LanguageLevel.class);
- if (languageLevel != null) {
- javaProjectData.setLanguageLevel(languageLevel);
- }
- else {
- javaProjectData.setLanguageLevel(ideaProject.getLanguageLevel().getLevel());
- }
- return javaProjectData;
- }
-
- @Override
- public void populateProjectExtraModels(@Nonnull IdeaProject gradleProject, @Nonnull DataNode ideProject) {
- final ExternalProject externalProject = resolverCtx.getExtraProject(ExternalProject.class);
- if (externalProject != null) {
- ideProject.createChild(ExternalProjectDataService.KEY, externalProject);
- }
- }
-
- @Nonnull
- @Override
- public ModuleData createModule(@Nonnull IdeaModule gradleModule, @Nonnull ProjectData projectData) {
- final String moduleName = gradleModule.getName();
- if (moduleName == null) {
- throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
- }
+ private static final Logger LOG = Logger.getInstance(BaseGradleProjectResolverExtension.class);
- final String moduleConfigPath = getModuleConfigPath(gradleModule, projectData.getLinkedExternalProjectPath());
+ @Nonnull
+ @NonNls
+ private static final String UNRESOLVED_DEPENDENCY_PREFIX = "unresolved dependency - ";
+ private static final String MAIN_SOURCE_SET = "main";
+ private static final String TEST_SOURCE_SET = "test";
- if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
- LOG.info(String.format("Creating module data ('%s') with the external config path: '%s'", gradleModule.getGradleProject().getPath(),
- moduleConfigPath));
- }
-
- String gradlePath = gradleModule.getGradleProject().getPath();
- String moduleId = StringUtil.isEmpty(gradlePath) || ":".equals(gradlePath) ? moduleName : gradlePath;
- ModuleData moduleData = new ModuleData(moduleId, GradleConstants.SYSTEM_ID, moduleName, moduleConfigPath, moduleConfigPath);
+ @Nonnull
+ private ProjectResolverContext resolverCtx;
+ @Nonnull
+ private final BaseProjectImportErrorHandler myErrorHandler = new BaseProjectImportErrorHandler();
- final ModuleExtendedModel moduleExtendedModel = resolverCtx.getExtraProject(gradleModule, ModuleExtendedModel.class);
- if (moduleExtendedModel != null) {
- moduleData.setGroup(moduleExtendedModel.getGroup());
- moduleData.setVersion(moduleExtendedModel.getVersion());
- moduleData.setArtifacts(moduleExtendedModel.getArtifacts());
- }
- return moduleData;
- }
-
- @Override
- public void populateModuleExtraModels(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) {
- final BuildScriptClasspathModel buildScriptClasspathModel = resolverCtx.getExtraProject(gradleModule, BuildScriptClasspathModel.class);
- final List classpathEntries;
- if (buildScriptClasspathModel != null) {
- classpathEntries = ContainerUtil.map(buildScriptClasspathModel.getClasspath(),
- model -> new BuildScriptClasspathData.ClasspathEntry(model.getClasses(),
- model.getSources(),
- model.getJavadoc()));
+ @Override
+ public void setProjectResolverContext(@Nonnull ProjectResolverContext projectResolverContext) {
+ resolverCtx = projectResolverContext;
}
- else {
- classpathEntries = ContainerUtil.emptyList();
+
+ @Override
+ public void setNext(@Nonnull GradleProjectResolverExtension next) {
+ // should be the last extension in the chain
}
- BuildScriptClasspathData buildScriptClasspathData = new BuildScriptClasspathData(GradleConstants.SYSTEM_ID, classpathEntries);
- ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData);
- }
-
- @Override
- public void populateModuleContentRoots(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) {
- DomainObjectSet extends IdeaContentRoot> contentRoots;
- ModuleExtendedModel moduleExtendedModel = resolverCtx.getExtraProject(gradleModule, ModuleExtendedModel.class);
- if (moduleExtendedModel != null) {
- contentRoots = moduleExtendedModel.getContentRoots();
+
+ @Nullable
+ @Override
+ public GradleProjectResolverExtension getNext() {
+ return null;
}
- else {
- contentRoots = gradleModule.getContentRoots();
+
+ @Nonnull
+ @Override
+ public ProjectData createProject() {
+ final String projectDirPath = resolverCtx.getProjectPath();
+ final IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
+ return new ProjectData(GradleConstants.SYSTEM_ID, ideaProject.getName(), projectDirPath, projectDirPath);
}
- if (contentRoots == null) {
- return;
+ @Nonnull
+ @Override
+ public JavaProjectData createJavaProjectData() {
+ final String projectDirPath = resolverCtx.getProjectPath();
+ final IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
+
+ // Gradle API doesn't expose gradleProject compile output path yet.
+ JavaProjectData javaProjectData = new JavaProjectData(GradleConstants.SYSTEM_ID, projectDirPath + "/build/classes");
+ javaProjectData.setJdkVersion(ideaProject.getJdkName());
+
+ LanguageLevel languageLevel = StringUtil.parseEnum(ideaProject.getLanguageLevel().getLevel(), null, LanguageLevel.class);
+ if (languageLevel != null) {
+ javaProjectData.setLanguageLevel(languageLevel);
+ }
+ else {
+ javaProjectData.setLanguageLevel(ideaProject.getLanguageLevel().getLevel());
+ }
+ return javaProjectData;
}
- for (IdeaContentRoot gradleContentRoot : contentRoots) {
- if (gradleContentRoot == null) {
- continue;
- }
-
- File rootDirectory = gradleContentRoot.getRootDirectory();
- if (rootDirectory == null) {
- continue;
- }
-
- ContentRootData ideContentRoot = new ContentRootData(GradleConstants.SYSTEM_ID, rootDirectory.getAbsolutePath());
- ideModule.getData().setModuleDirPath(ideContentRoot.getRootPath());
- populateContentRoot(ideContentRoot, ExternalSystemSourceType.SOURCE, gradleContentRoot.getSourceDirectories());
- populateContentRoot(ideContentRoot, ExternalSystemSourceType.TEST, gradleContentRoot.getTestDirectories());
-
- if (gradleContentRoot instanceof ExtIdeaContentRoot) {
- ExtIdeaContentRoot extIdeaContentRoot = (ExtIdeaContentRoot)gradleContentRoot;
- populateContentRoot(ideContentRoot, ExternalSystemSourceType.RESOURCE, extIdeaContentRoot.getResourceDirectories());
- populateContentRoot(ideContentRoot, ExternalSystemSourceType.TEST_RESOURCE, extIdeaContentRoot.getTestResourceDirectories());
- }
-
- Set excluded = gradleContentRoot.getExcludeDirectories();
- if (excluded != null) {
- for (File file : excluded) {
- ideContentRoot.storePath(ExternalSystemSourceType.EXCLUDED, file.getAbsolutePath());
- }
- }
- ideModule.createChild(ProjectKeys.CONTENT_ROOT, ideContentRoot);
+
+ @Override
+ public void populateProjectExtraModels(@Nonnull IdeaProject gradleProject, @Nonnull DataNode ideProject) {
+ final ExternalProject externalProject = resolverCtx.getExtraProject(ExternalProject.class);
+ if (externalProject != null) {
+ ideProject.createChild(ExternalProjectDataService.KEY, externalProject);
+ }
}
- }
+ @Nonnull
+ @Override
+ public ModuleData createModule(@Nonnull IdeaModule gradleModule, @Nonnull ProjectData projectData) {
+ final String moduleName = gradleModule.getName();
+ if (moduleName == null) {
+ throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
+ }
- @Override
- public void populateModuleCompileOutputSettings(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) {
- IdeaCompilerOutput moduleCompilerOutput = gradleModule.getCompilerOutput();
+ final String moduleConfigPath = getModuleConfigPath(gradleModule, projectData.getLinkedExternalProjectPath());
- File sourceCompileOutputPath = null;
- File testCompileOutputPath = null;
- File resourceCompileOutputPath;
- File testResourceCompileOutputPath;
- boolean inheritOutputDirs = false;
+ if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
+ LOG.info(String.format(
+ "Creating module data ('%s') with the external config path: '%s'",
+ gradleModule.getGradleProject().getPath(),
+ moduleConfigPath
+ ));
+ }
- ModuleData moduleData = ideModule.getData();
- if (moduleCompilerOutput != null) {
- sourceCompileOutputPath = moduleCompilerOutput.getOutputDir();
- testCompileOutputPath = moduleCompilerOutput.getTestOutputDir();
- inheritOutputDirs = moduleCompilerOutput.getInheritOutputDirs();
- }
+ String gradlePath = gradleModule.getGradleProject().getPath();
+ String moduleId = StringUtil.isEmpty(gradlePath) || ":".equals(gradlePath) ? moduleName : gradlePath;
+ ModuleData moduleData = new ModuleData(moduleId, GradleConstants.SYSTEM_ID, moduleName, moduleConfigPath, moduleConfigPath);
- ExternalProject externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject.class);
- if (externalProject != null) {
- externalProject = new DefaultExternalProject(externalProject);
+ final ModuleExtendedModel moduleExtendedModel = resolverCtx.getExtraProject(gradleModule, ModuleExtendedModel.class);
+ if (moduleExtendedModel != null) {
+ moduleData.setGroup(moduleExtendedModel.getGroup());
+ moduleData.setVersion(moduleExtendedModel.getVersion());
+ moduleData.setArtifacts(moduleExtendedModel.getArtifacts());
+ }
+ return moduleData;
+ }
+
+ @Override
+ public void populateModuleExtraModels(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) {
+ final BuildScriptClasspathModel buildScriptClasspathModel =
+ resolverCtx.getExtraProject(gradleModule, BuildScriptClasspathModel.class);
+ final List classpathEntries;
+ if (buildScriptClasspathModel != null) {
+ classpathEntries = ContainerUtil.map(
+ buildScriptClasspathModel.getClasspath(),
+ model -> new BuildScriptClasspathData.ClasspathEntry(
+ model.getClasses(),
+ model.getSources(),
+ model.getJavadoc()
+ )
+ );
+ }
+ else {
+ classpathEntries = ContainerUtil.emptyList();
+ }
+ BuildScriptClasspathData buildScriptClasspathData = new BuildScriptClasspathData(GradleConstants.SYSTEM_ID, classpathEntries);
+ ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData);
}
- if (!inheritOutputDirs && (sourceCompileOutputPath == null || testCompileOutputPath == null)) {
- sourceCompileOutputPath = getCompileOutputPath(externalProject, MAIN_SOURCE_SET, ExternalSystemSourceType.SOURCE);
- resourceCompileOutputPath = getCompileOutputPath(externalProject, MAIN_SOURCE_SET, ExternalSystemSourceType.RESOURCE);
- testCompileOutputPath = getCompileOutputPath(externalProject, TEST_SOURCE_SET, ExternalSystemSourceType.TEST);
- testResourceCompileOutputPath = getCompileOutputPath(externalProject, TEST_SOURCE_SET, ExternalSystemSourceType.TEST_RESOURCE);
- }
- else {
- resourceCompileOutputPath = sourceCompileOutputPath;
- testResourceCompileOutputPath = testCompileOutputPath;
-
- if (externalProject != null) {
- final ExternalSourceSet mainSourceSet = externalProject.getSourceSets().get(MAIN_SOURCE_SET);
- if (mainSourceSet != null) {
- final ExternalSourceDirectorySet resourceDirectories = mainSourceSet.getSources().get(ExternalSystemSourceType.RESOURCE);
- if (resourceDirectories instanceof DefaultExternalSourceDirectorySet) {
- ((DefaultExternalSourceDirectorySet)resourceDirectories).setOutputDir(sourceCompileOutputPath);
- }
- }
- final ExternalSourceSet testSourceSet = externalProject.getSourceSets().get(TEST_SOURCE_SET);
- if (testSourceSet != null) {
- final ExternalSourceDirectorySet testResourceDirectories = testSourceSet.getSources().get(ExternalSystemSourceType
- .TEST_RESOURCE);
- if (testResourceDirectories instanceof DefaultExternalSourceDirectorySet) {
- ((DefaultExternalSourceDirectorySet)testResourceDirectories).setOutputDir(testCompileOutputPath);
- }
- }
-
- final DataNode projectDataNode = ExternalSystemApiUtil.findParent(ideModule, ProjectKeys.PROJECT);
- assert projectDataNode != null;
- projectDataNode.createOrReplaceChild(ExternalProjectDataService.KEY, externalProject);
- }
- }
+ @Override
+ public void populateModuleContentRoots(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) {
+ DomainObjectSet extends IdeaContentRoot> contentRoots;
+ ModuleExtendedModel moduleExtendedModel = resolverCtx.getExtraProject(gradleModule, ModuleExtendedModel.class);
+ if (moduleExtendedModel != null) {
+ contentRoots = moduleExtendedModel.getContentRoots();
+ }
+ else {
+ contentRoots = gradleModule.getContentRoots();
+ }
- if (sourceCompileOutputPath != null) {
- moduleData.setCompileOutputPath(ExternalSystemSourceType.SOURCE, sourceCompileOutputPath.getAbsolutePath());
- }
- if (resourceCompileOutputPath != null) {
- moduleData.setCompileOutputPath(ExternalSystemSourceType.RESOURCE, resourceCompileOutputPath.getAbsolutePath());
- }
- if (testCompileOutputPath != null) {
- moduleData.setCompileOutputPath(ExternalSystemSourceType.TEST, testCompileOutputPath.getAbsolutePath());
- }
- if (testResourceCompileOutputPath != null) {
- moduleData.setCompileOutputPath(ExternalSystemSourceType.TEST_RESOURCE, testResourceCompileOutputPath.getAbsolutePath());
+ if (contentRoots == null) {
+ return;
+ }
+ for (IdeaContentRoot gradleContentRoot : contentRoots) {
+ if (gradleContentRoot == null) {
+ continue;
+ }
+
+ File rootDirectory = gradleContentRoot.getRootDirectory();
+ if (rootDirectory == null) {
+ continue;
+ }
+
+ ContentRootData ideContentRoot = new ContentRootData(GradleConstants.SYSTEM_ID, rootDirectory.getAbsolutePath());
+ ideModule.getData().setModuleDirPath(ideContentRoot.getRootPath());
+ populateContentRoot(ideContentRoot, ExternalSystemSourceType.SOURCE, gradleContentRoot.getSourceDirectories());
+ populateContentRoot(ideContentRoot, ExternalSystemSourceType.TEST, gradleContentRoot.getTestDirectories());
+
+ if (gradleContentRoot instanceof ExtIdeaContentRoot) {
+ ExtIdeaContentRoot extIdeaContentRoot = (ExtIdeaContentRoot)gradleContentRoot;
+ populateContentRoot(ideContentRoot, ExternalSystemSourceType.RESOURCE, extIdeaContentRoot.getResourceDirectories());
+ populateContentRoot(
+ ideContentRoot,
+ ExternalSystemSourceType.TEST_RESOURCE,
+ extIdeaContentRoot.getTestResourceDirectories()
+ );
+ }
+
+ Set excluded = gradleContentRoot.getExcludeDirectories();
+ if (excluded != null) {
+ for (File file : excluded) {
+ ideContentRoot.storePath(ExternalSystemSourceType.EXCLUDED, file.getAbsolutePath());
+ }
+ }
+ ideModule.createChild(ProjectKeys.CONTENT_ROOT, ideContentRoot);
+ }
}
- moduleData.setInheritProjectCompileOutputPath(inheritOutputDirs || sourceCompileOutputPath == null);
- }
- @Nullable
- private static File getCompileOutputPath(@Nullable ExternalProject externalProject,
- @Nonnull String sourceSetName,
- @Nonnull ExternalSystemSourceType sourceType) {
- if (externalProject == null) {
- return null;
- }
- final ExternalSourceSet sourceSet = externalProject.getSourceSets().get(sourceSetName);
- if (sourceSet == null) {
- return null;
- }
+ @Override
+ public void populateModuleCompileOutputSettings(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) {
+ IdeaCompilerOutput moduleCompilerOutput = gradleModule.getCompilerOutput();
- final ExternalSourceDirectorySet directorySet = sourceSet.getSources().get(sourceType);
- return directorySet != null ? directorySet.getOutputDir() : null;
- }
+ File sourceCompileOutputPath = null;
+ File testCompileOutputPath = null;
+ File resourceCompileOutputPath;
+ File testResourceCompileOutputPath;
+ boolean inheritOutputDirs = false;
- @Override
- public void populateModuleDependencies(@Nonnull IdeaModule gradleModule,
- @Nonnull DataNode ideModule,
- @Nonnull DataNode ideProject) {
- final List extends IdeaDependency> dependencies = gradleModule.getDependencies().getAll();
+ ModuleData moduleData = ideModule.getData();
+ if (moduleCompilerOutput != null) {
+ sourceCompileOutputPath = moduleCompilerOutput.getOutputDir();
+ testCompileOutputPath = moduleCompilerOutput.getTestOutputDir();
+ inheritOutputDirs = moduleCompilerOutput.getInheritOutputDirs();
+ }
- if (dependencies == null) {
- return;
- }
+ ExternalProject externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject.class);
+ if (externalProject != null) {
+ externalProject = new DefaultExternalProject(externalProject);
+ }
- for (IdeaDependency dependency : dependencies) {
- if (dependency == null) {
- continue;
- }
- DependencyScope scope = parseScope(dependency.getScope());
-
- if (dependency instanceof IdeaModuleDependency) {
- ModuleDependencyData d = buildDependency(ideModule, (IdeaModuleDependency)dependency, ideProject);
- d.setExported(dependency.getExported());
- if (scope != null) {
- d.setScope(scope);
- }
- ideModule.createChild(ProjectKeys.MODULE_DEPENDENCY, d);
- }
- else if (dependency instanceof IdeaSingleEntryLibraryDependency) {
- LibraryDependencyData d = buildDependency(gradleModule, ideModule, (IdeaSingleEntryLibraryDependency)dependency, ideProject);
- d.setExported(dependency.getExported());
- if (scope != null) {
- d.setScope(scope);
- }
- ideModule.createChild(ProjectKeys.LIBRARY_DEPENDENCY, d);
- }
- }
- }
-
- @Nonnull
- @Override
- public Collection populateModuleTasks(@Nonnull IdeaModule gradleModule,
- @Nonnull DataNode ideModule,
- @Nonnull DataNode ideProject) throws IllegalArgumentException, IllegalStateException {
-
- final Collection tasks = ContainerUtil.newArrayList();
- final String moduleConfigPath = ideModule.getData().getLinkedExternalProjectPath();
-
- for (GradleTask task : gradleModule.getGradleProject().getTasks()) {
- String taskName = task.getName();
- if (taskName == null || taskName.trim().isEmpty() || isIdeaTask(taskName)) {
- continue;
- }
- TaskData taskData = new TaskData(GradleConstants.SYSTEM_ID, taskName, moduleConfigPath, task.getDescription());
- ideModule.createChild(ProjectKeys.TASK, taskData);
- tasks.add(taskData);
- }
+ if (!inheritOutputDirs && (sourceCompileOutputPath == null || testCompileOutputPath == null)) {
+ sourceCompileOutputPath = getCompileOutputPath(externalProject, MAIN_SOURCE_SET, ExternalSystemSourceType.SOURCE);
+ resourceCompileOutputPath = getCompileOutputPath(externalProject, MAIN_SOURCE_SET, ExternalSystemSourceType.RESOURCE);
+ testCompileOutputPath = getCompileOutputPath(externalProject, TEST_SOURCE_SET, ExternalSystemSourceType.TEST);
+ testResourceCompileOutputPath = getCompileOutputPath(externalProject, TEST_SOURCE_SET, ExternalSystemSourceType.TEST_RESOURCE);
+ }
+ else {
+ resourceCompileOutputPath = sourceCompileOutputPath;
+ testResourceCompileOutputPath = testCompileOutputPath;
+
+ if (externalProject != null) {
+ final ExternalSourceSet mainSourceSet = externalProject.getSourceSets().get(MAIN_SOURCE_SET);
+ if (mainSourceSet != null) {
+ final ExternalSourceDirectorySet resourceDirectories =
+ mainSourceSet.getSources().get(ExternalSystemSourceType.RESOURCE);
+ if (resourceDirectories instanceof DefaultExternalSourceDirectorySet resourceDirSet) {
+ resourceDirSet.setOutputDir(sourceCompileOutputPath);
+ }
+ }
+ final ExternalSourceSet testSourceSet = externalProject.getSourceSets().get(TEST_SOURCE_SET);
+ if (testSourceSet != null) {
+ final ExternalSourceDirectorySet testResourceDirectories = testSourceSet.getSources().get(ExternalSystemSourceType
+ .TEST_RESOURCE);
+ if (testResourceDirectories instanceof DefaultExternalSourceDirectorySet testResourceDirSet) {
+ testResourceDirSet.setOutputDir(testCompileOutputPath);
+ }
+ }
+
+ final DataNode projectDataNode = ExternalSystemApiUtil.findParent(ideModule, ProjectKeys.PROJECT);
+ assert projectDataNode != null;
+ projectDataNode.createOrReplaceChild(ExternalProjectDataService.KEY, externalProject);
+ }
+ }
- return tasks;
- }
-
- @Nonnull
- @Override
- public Collection filterRootProjectTasks(@Nonnull List allTasks) {
- return allTasks;
- }
-
- @Nonnull
- @Override
- public Set getExtraProjectModelClasses() {
- return ContainerUtil.set(GradleBuild.class, ExternalProject.class, ModuleExtendedModel.class, BuildScriptClasspathModel.class);
- }
-
- @Nonnull
- @Override
- public Set getToolingExtensionsClasses() {
- return ContainerUtil.set(ExternalProject.class,
- // gradle-tooling-extension-api jar
- ProjectImportAction.class,
- // gradle-tooling-extension-impl jar
- ModelBuildScriptClasspathBuilderImpl.class, GsonBuilder.class);
- }
-
- @Nonnull
- @Override
- public List> getExtraJvmArgs() {
- if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) {
- final List> extraJvmArgs = ContainerUtil.newArrayList();
- final HttpProxyManager httpConfigurable = HttpProxyManager.getInstance();
-
- List proxyExceptions = httpConfigurable.getProxyExceptions();
- if (!proxyExceptions.isEmpty()) {
- extraJvmArgs.add(Pair.create("http.nonProxyHosts", consulo.util.lang.StringUtil.join(proxyExceptions, StringUtil.TRIMMER, "|")));
- }
-
- for (Pair pair : httpConfigurable.getJvmProperties(false, null)) {
- extraJvmArgs.add(Pair.create(pair.getFirst(), pair.getSecond()));
- }
-
- return extraJvmArgs;
+ if (sourceCompileOutputPath != null) {
+ moduleData.setCompileOutputPath(ExternalSystemSourceType.SOURCE, sourceCompileOutputPath.getAbsolutePath());
+ }
+ if (resourceCompileOutputPath != null) {
+ moduleData.setCompileOutputPath(ExternalSystemSourceType.RESOURCE, resourceCompileOutputPath.getAbsolutePath());
+ }
+ if (testCompileOutputPath != null) {
+ moduleData.setCompileOutputPath(ExternalSystemSourceType.TEST, testCompileOutputPath.getAbsolutePath());
+ }
+ if (testResourceCompileOutputPath != null) {
+ moduleData.setCompileOutputPath(ExternalSystemSourceType.TEST_RESOURCE, testResourceCompileOutputPath.getAbsolutePath());
+ }
+
+ moduleData.setInheritProjectCompileOutputPath(inheritOutputDirs || sourceCompileOutputPath == null);
}
- return Collections.emptyList();
- }
-
- @Nonnull
- @Override
- public List getExtraCommandLineArgs() {
- return Collections.emptyList();
- }
-
- @Nonnull
- @Override
- public ExternalSystemException getUserFriendlyError(@Nonnull Throwable error,
- @Nonnull String projectPath,
- @Nullable String buildFilePath) {
- return myErrorHandler.getUserFriendlyError(error, projectPath, buildFilePath);
- }
-
- @Override
- public void preImportCheck() {
- }
-
- @Override
- public void enhanceTaskProcessing(@Nonnull List taskNames,
- @Nullable String debuggerSetup,
- @Nonnull Consumer initScriptConsumer) {
- if (!StringUtil.isEmpty(debuggerSetup)) {
- final String[] lines = {
- "gradle.taskGraph.beforeTask { Task task ->",
- " if (task instanceof JavaForkOptions) {",
- " task.jvmArgs '" + debuggerSetup.trim() + '\'',
- " }" + "}",
- };
- final String script = StringUtil.join(lines, SystemProperties.getLineSeparator());
- initScriptConsumer.accept(script);
+
+ @Nullable
+ private static File getCompileOutputPath(
+ @Nullable ExternalProject externalProject,
+ @Nonnull String sourceSetName,
+ @Nonnull ExternalSystemSourceType sourceType
+ ) {
+ if (externalProject == null) {
+ return null;
+ }
+ final ExternalSourceSet sourceSet = externalProject.getSourceSets().get(sourceSetName);
+ if (sourceSet == null) {
+ return null;
+ }
+
+ final ExternalSourceDirectorySet directorySet = sourceSet.getSources().get(sourceType);
+ return directorySet != null ? directorySet.getOutputDir() : null;
}
- }
- @Override
- public void enhanceRemoteProcessing(@Nonnull SimpleJavaParameters parameters) throws ExecutionException {
- PathsList classPath = parameters.getClassPath();
+ @Override
+ public void populateModuleDependencies(
+ @Nonnull IdeaModule gradleModule,
+ @Nonnull DataNode ideModule,
+ @Nonnull DataNode ideProject
+ ) {
+ final List extends IdeaDependency> dependencies = gradleModule.getDependencies().getAll();
- // Gradle i18n bundle.
- ExternalSystemApiUtil.addBundle(classPath, GradleBundle.PATH_TO_BUNDLE, GradleBundle.class);
+ if (dependencies == null) {
+ return;
+ }
- // Gradle tool jars.
- String toolingApiPath = PathManager.getJarPathForClass(ProjectConnection.class);
- if (toolingApiPath == null) {
- LOG.warn(GradleBundle.message("gradle.generic.text.error.jar.not.found"));
- throw new ExecutionException("Can't find gradle libraries");
- }
- File gradleJarsDir = new File(toolingApiPath).getParentFile();
- String[] gradleJars = gradleJarsDir.list(new FilenameFilter() {
- @Override
- public boolean accept(@Nonnull File dir, @Nonnull String name) {
- return name.endsWith(".jar");
- }
- });
- if (gradleJars == null) {
- LOG.warn(GradleBundle.message("gradle.generic.text.error.jar.not.found"));
- throw new ExecutionException("Can't find gradle libraries at " + gradleJarsDir.getAbsolutePath());
- }
- for (String jar : gradleJars) {
- classPath.add(new File(gradleJarsDir, jar).getAbsolutePath());
+ for (IdeaDependency dependency : dependencies) {
+ if (dependency == null) {
+ continue;
+ }
+ DependencyScope scope = parseScope(dependency.getScope());
+
+ if (dependency instanceof IdeaModuleDependency) {
+ ModuleDependencyData d = buildDependency(ideModule, (IdeaModuleDependency)dependency, ideProject);
+ d.setExported(dependency.getExported());
+ if (scope != null) {
+ d.setScope(scope);
+ }
+ ideModule.createChild(ProjectKeys.MODULE_DEPENDENCY, d);
+ }
+ else if (dependency instanceof IdeaSingleEntryLibraryDependency singleEntryLibraryDependency) {
+ LibraryDependencyData d =
+ buildDependency(gradleModule, ideModule, singleEntryLibraryDependency, ideProject);
+ d.setExported(dependency.getExported());
+ if (scope != null) {
+ d.setScope(scope);
+ }
+ ideModule.createChild(ProjectKeys.LIBRARY_DEPENDENCY, d);
+ }
+ }
}
- List additionalEntries = ContainerUtilRt.newArrayList();
- ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GroovyObject.class));
- ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GsonBuilder.class));
- ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ExternalProject.class));
- ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ProjectImportAction.class));
- ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(Init.class));
- for (String entry : additionalEntries) {
- classPath.add(entry);
- }
- }
-
- @Override
- public void enhanceLocalProcessing(@Nonnull List urls) {
- }
-
- @Nonnull
- private String getModuleConfigPath(@Nonnull IdeaModule gradleModule, @Nonnull String rootProjectPath) {
- GradleBuild build = resolverCtx.getExtraProject(gradleModule, GradleBuild.class);
- if (build != null) {
- String gradlePath = gradleModule.getGradleProject().getPath();
- File moduleDirPath = getModuleDirPath(build, gradlePath);
- if (moduleDirPath == null) {
- throw new IllegalStateException(String.format("Unable to find root directory for module '%s'", gradleModule.getName()));
- }
- try {
- return ExternalSystemApiUtil.toCanonicalPath(moduleDirPath.getCanonicalPath());
- }
- catch (IOException e) {
- LOG.warn("construction of the canonical path for the module fails", e);
- }
- }
+ @Nonnull
+ @Override
+ public Collection populateModuleTasks(
+ @Nonnull IdeaModule gradleModule,
+ @Nonnull DataNode ideModule,
+ @Nonnull DataNode ideProject
+ ) throws IllegalArgumentException, IllegalStateException {
+
+ final Collection tasks = ContainerUtil.newArrayList();
+ final String moduleConfigPath = ideModule.getData().getLinkedExternalProjectPath();
+
+ for (GradleTask task : gradleModule.getGradleProject().getTasks()) {
+ String taskName = task.getName();
+ if (taskName == null || taskName.trim().isEmpty() || isIdeaTask(taskName)) {
+ continue;
+ }
+ TaskData taskData = new TaskData(GradleConstants.SYSTEM_ID, taskName, moduleConfigPath, task.getDescription());
+ ideModule.createChild(ProjectKeys.TASK, taskData);
+ tasks.add(taskData);
+ }
- return GradleUtil.getConfigPath(gradleModule.getGradleProject(), rootProjectPath);
- }
-
- /**
- * Returns the physical path of the module's root directory (the path in the file system.)
- *
- * It is important to note that Gradle has its own "logical" path that may or may not be equal to the physical path of a Gradle project.
- * For example, the sub-project at ${projectRootDir}/apps/app will have the Gradle path :apps:app. Gradle also allows mapping physical
- * paths to a different logical path. For example, in settings.gradle:
- *
- * include ':app'
- * project(':app').projectDir = new File(rootDir, 'apps/app')
- *
- * In this example, sub-project at ${projectRootDir}/apps/app will have the Gradle path :app.
- *
- *
- * @param build contains information about the root Gradle project and its sub-projects. Such information includes the physical path of
- * the root Gradle project and its sub-projects.
- * @param path the Gradle "logical" path. This path uses colon as separator, and may or may not be equal to the physical path of a
- * Gradle project.
- * @return the physical path of the module's root directory.
- */
- @Nullable
- static File getModuleDirPath(@Nonnull GradleBuild build, @Nonnull String path) {
- for (BasicGradleProject project : build.getProjects()) {
- if (project.getPath().equals(path)) {
- return project.getProjectDirectory();
- }
- }
- return null;
- }
-
- /**
- * Stores information about given directories at the given content root
- *
- * @param contentRoot target paths info holder
- * @param type type of data located at the given directories
- * @param dirs directories which paths should be stored at the given content root
- * @throws IllegalArgumentException if specified by {@link ContentRootData#storePath(ExternalSystemSourceType, String)}
- */
- private static void populateContentRoot(@Nonnull ContentRootData contentRoot,
- @Nonnull ExternalSystemSourceType type,
- @Nullable Iterable extends IdeaSourceDirectory> dirs) throws IllegalArgumentException {
- if (dirs == null) {
- return;
- }
- for (IdeaSourceDirectory dir : dirs) {
- contentRoot.storePath(type, dir.getDirectory().getAbsolutePath());
+ return tasks;
+ }
+
+ @Nonnull
+ @Override
+ public Collection filterRootProjectTasks(@Nonnull List allTasks) {
+ return allTasks;
+ }
+
+ @Nonnull
+ @Override
+ public Set getExtraProjectModelClasses() {
+ return ContainerUtil.set(
+ GradleBuild.class,
+ ExternalProject.class,
+ ModuleExtendedModel.class,
+ BuildScriptClasspathModel.class
+ );
+ }
+
+ @Nonnull
+ @Override
+ public Set getToolingExtensionsClasses() {
+ return ContainerUtil.set(ExternalProject.class,
+ // gradle-tooling-extension-api jar
+ ProjectImportAction.class,
+ // gradle-tooling-extension-impl jar
+ ModelBuildScriptClasspathBuilderImpl.class, GsonBuilder.class
+ );
+ }
+
+ @Nonnull
+ @Override
+ public List> getExtraJvmArgs() {
+ if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) {
+ final List> extraJvmArgs = ContainerUtil.newArrayList();
+ final HttpProxyManager httpConfigurable = HttpProxyManager.getInstance();
+
+ List proxyExceptions = httpConfigurable.getProxyExceptions();
+ if (!proxyExceptions.isEmpty()) {
+ extraJvmArgs.add(Pair.create(
+ "http.nonProxyHosts",
+ consulo.util.lang.StringUtil.join(proxyExceptions, StringUtil.TRIMMER, "|")
+ ));
+ }
+
+ for (Pair pair : httpConfigurable.getJvmProperties(false, null)) {
+ extraJvmArgs.add(Pair.create(pair.getFirst(), pair.getSecond()));
+ }
+
+ return extraJvmArgs;
+ }
+ return Collections.emptyList();
+ }
+
+ @Nonnull
+ @Override
+ public List getExtraCommandLineArgs() {
+ return Collections.emptyList();
+ }
+
+ @Nonnull
+ @Override
+ public ExternalSystemException getUserFriendlyError(
+ @Nonnull Throwable error,
+ @Nonnull String projectPath,
+ @Nullable String buildFilePath
+ ) {
+ return myErrorHandler.getUserFriendlyError(error, projectPath, buildFilePath);
+ }
+
+ @Override
+ public void preImportCheck() {
+ }
+
+ @Override
+ public void enhanceTaskProcessing(
+ @Nonnull List taskNames,
+ @Nullable String debuggerSetup,
+ @Nonnull Consumer initScriptConsumer
+ ) {
+ if (!StringUtil.isEmpty(debuggerSetup)) {
+ final String[] lines = {
+ "gradle.taskGraph.beforeTask { Task task ->",
+ " if (task instanceof JavaForkOptions) {",
+ " task.jvmArgs '" + debuggerSetup.trim() + '\'',
+ " }" + "}",
+ };
+ final String script = StringUtil.join(lines, SystemProperties.getLineSeparator());
+ initScriptConsumer.accept(script);
+ }
}
- }
- @Nullable
- private static DependencyScope parseScope(@Nullable IdeaDependencyScope scope) {
- if (scope == null) {
- return null;
- }
- String scopeAsString = scope.getScope();
- if (scopeAsString == null) {
- return null;
- }
- for (DependencyScope dependencyScope : DependencyScope.values()) {
- if (scopeAsString.equalsIgnoreCase(dependencyScope.toString())) {
- return dependencyScope;
- }
- }
- return null;
- }
-
- @Nonnull
- private static ModuleDependencyData buildDependency(@Nonnull DataNode ownerModule,
- @Nonnull IdeaModuleDependency dependency,
- @Nonnull DataNode ideProject) throws IllegalStateException {
- String moduleName = dependency.getTargetModuleName();
- if (moduleName == null) {
- throw new IllegalStateException(String.format(
- "Can't parse gradle module dependency '%s'. Reason: referenced module name is undefined "
- + "(module: '%s') ",
- dependency,
- moduleName));
- }
+ @Override
+ public void enhanceRemoteProcessing(@Nonnull SimpleJavaParameters parameters) throws ExecutionException {
+ PathsList classPath = parameters.getClassPath();
- Set registeredModuleNames = ContainerUtil.newHashSet();
- Collection> modulesDataNode = ExternalSystemApiUtil.getChildren(ideProject, ProjectKeys.MODULE);
- for (DataNode moduleDataNode : modulesDataNode) {
- String name = moduleDataNode.getData().getExternalName();
- registeredModuleNames.add(name);
- if (name.equals(moduleName)) {
- return new ModuleDependencyData(ownerModule.getData(), moduleDataNode.getData());
- }
- }
- throw new IllegalStateException(String.format(
- "Can't parse gradle module dependency '%s'. Reason: no module with such name (%s) is found. "
- + "Registered modules: %s",
- dependency,
- moduleName,
- registeredModuleNames));
- }
-
- @Nonnull
- private LibraryDependencyData buildDependency(@Nonnull IdeaModule gradleModule,
- @Nonnull DataNode ownerModule,
- @Nonnull IdeaSingleEntryLibraryDependency dependency,
- @Nonnull DataNode ideProject) throws IllegalStateException {
- File binaryPath = dependency.getFile();
- if (binaryPath == null) {
- throw new IllegalStateException(String.format("Can't parse external library dependency '%s'. Reason: it doesn't specify path to the " +
- "binaries", dependency));
- }
+ // Gradle i18n bundle.
+ ExternalSystemApiUtil.addBundle(classPath, GradleBundle.PATH_TO_BUNDLE, GradleBundle.class);
- String libraryName;
- final GradleModuleVersion moduleVersion = dependency.getGradleModuleVersion();
- LibraryLevel level;
-
- // Gradle API doesn't explicitly provide information about unresolved libraries (http://issues.gradle.org/browse/GRADLE-1995).
- // That's why we use this dirty hack here.
- boolean unresolved = binaryPath.getPath().startsWith(UNRESOLVED_DEPENDENCY_PREFIX);
-
- if (moduleVersion == null) {
- // use module library level if the dependency does not originate from a remote repository.
- level = LibraryLevel.MODULE;
-
- if (binaryPath.isFile()) {
- libraryName = FileUtil.getNameWithoutExtension(binaryPath);
- }
- else {
- libraryName = FileUtil.sanitizeFileName(binaryPath.getPath());
- }
-
- if (unresolved) {
- // Gradle uses names like 'unresolved dependency - commons-collections commons-collections 3.2' for unresolved dependencies.
- libraryName = binaryPath.getName().substring(UNRESOLVED_DEPENDENCY_PREFIX.length());
- int i = libraryName.indexOf(' ');
- if (i >= 0) {
- i = CharArrayUtil.shiftForward(libraryName, i + 1, " ");
- }
-
- if (i >= 0 && i < libraryName.length()) {
- int dependencyNameIndex = i;
- i = libraryName.indexOf(' ', dependencyNameIndex);
- if (i > 0) {
- libraryName = String.format("%s-%s", libraryName.substring(dependencyNameIndex, i), libraryName.substring(i + 1));
- }
- }
- }
- }
- else {
- level = LibraryLevel.PROJECT;
- libraryName = String.format("%s:%s:%s", moduleVersion.getGroup(), moduleVersion.getName(), moduleVersion.getVersion());
- }
+ // Gradle tool jars.
+ String toolingApiPath = PathManager.getJarPathForClass(ProjectConnection.class);
+ if (toolingApiPath == null) {
+ LOG.warn(GradleBundle.message("gradle.generic.text.error.jar.not.found"));
+ throw new ExecutionException("Can't find gradle libraries");
+ }
+ File gradleJarsDir = new File(toolingApiPath).getParentFile();
+ String[] gradleJars = gradleJarsDir.list(new FilenameFilter() {
+ @Override
+ public boolean accept(@Nonnull File dir, @Nonnull String name) {
+ return name.endsWith(".jar");
+ }
+ });
+ if (gradleJars == null) {
+ LOG.warn(GradleBundle.message("gradle.generic.text.error.jar.not.found"));
+ throw new ExecutionException("Can't find gradle libraries at " + gradleJarsDir.getAbsolutePath());
+ }
+ for (String jar : gradleJars) {
+ classPath.add(new File(gradleJarsDir, jar).getAbsolutePath());
+ }
- final LibraryData library = new LibraryData(GradleConstants.SYSTEM_ID, libraryName, unresolved);
- if (!unresolved) {
- library.addPath(LibraryPathType.BINARY, binaryPath.getAbsolutePath());
+ List additionalEntries = ContainerUtilRt.newArrayList();
+ ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GroovyObject.class));
+ ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GsonBuilder.class));
+ ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ExternalProject.class));
+ ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ProjectImportAction.class));
+ ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(Init.class));
+ for (String entry : additionalEntries) {
+ classPath.add(entry);
+ }
}
- File sourcePath = dependency.getSource();
- if (!unresolved && sourcePath != null) {
- library.addPath(LibraryPathType.SOURCE, sourcePath.getAbsolutePath());
- }
+ @Override
+ public void enhanceLocalProcessing(@Nonnull List urls) {
+ }
+
+ @Nonnull
+ private String getModuleConfigPath(@Nonnull IdeaModule gradleModule, @Nonnull String rootProjectPath) {
+ GradleBuild build = resolverCtx.getExtraProject(gradleModule, GradleBuild.class);
+ if (build != null) {
+ String gradlePath = gradleModule.getGradleProject().getPath();
+ File moduleDirPath = getModuleDirPath(build, gradlePath);
+ if (moduleDirPath == null) {
+ throw new IllegalStateException(String.format("Unable to find root directory for module '%s'", gradleModule.getName()));
+ }
+ try {
+ return ExternalSystemApiUtil.toCanonicalPath(moduleDirPath.getCanonicalPath());
+ }
+ catch (IOException e) {
+ LOG.warn("construction of the canonical path for the module fails", e);
+ }
+ }
- if (!unresolved && sourcePath == null) {
- attachGradleSdkSources(gradleModule, libraryName, binaryPath, library);
+ return GradleUtil.getConfigPath(gradleModule.getGradleProject(), rootProjectPath);
+ }
+
+ /**
+ * Returns the physical path of the module's root directory (the path in the file system.)
+ *
+ * It is important to note that Gradle has its own "logical" path that may or may not be equal
+ * to the physical path of a Gradle project.
+ * For example, the sub-project at ${projectRootDir}/apps/app will have the Gradle path :apps:app. Gradle also allows mapping physical
+ * paths to a different logical path. For example, in settings.gradle:
+ *
+ * include ':app'
+ * project(':app').projectDir = new File(rootDir, 'apps/app')
+ *
+ * In this example, sub-project at ${projectRootDir}/apps/app will have the Gradle path :app.
+ *
+ *
+ * @param build contains information about the root Gradle project and its sub-projects. Such information includes the physical path of
+ * the root Gradle project and its sub-projects.
+ * @param path the Gradle "logical" path. This path uses colon as separator, and may or may not be equal to the physical path of a
+ * Gradle project.
+ * @return the physical path of the module's root directory.
+ */
+ @Nullable
+ static File getModuleDirPath(@Nonnull GradleBuild build, @Nonnull String path) {
+ for (BasicGradleProject project : build.getProjects()) {
+ if (project.getPath().equals(path)) {
+ return project.getProjectDirectory();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Stores information about given directories at the given content root
+ *
+ * @param contentRoot target paths info holder
+ * @param type type of data located at the given directories
+ * @param dirs directories which paths should be stored at the given content root
+ * @throws IllegalArgumentException if specified by {@link ContentRootData#storePath(ExternalSystemSourceType, String)}
+ */
+ private static void populateContentRoot(
+ @Nonnull ContentRootData contentRoot,
+ @Nonnull ExternalSystemSourceType type,
+ @Nullable Iterable extends IdeaSourceDirectory> dirs
+ ) throws IllegalArgumentException {
+ if (dirs == null) {
+ return;
+ }
+ for (IdeaSourceDirectory dir : dirs) {
+ contentRoot.storePath(type, dir.getDirectory().getAbsolutePath());
+ }
}
- File javadocPath = dependency.getJavadoc();
- if (!unresolved && javadocPath != null) {
- library.addPath(LibraryPathType.DOC, javadocPath.getAbsolutePath());
- }
+ @Nullable
+ private static DependencyScope parseScope(@Nullable IdeaDependencyScope scope) {
+ if (scope == null) {
+ return null;
+ }
+ String scopeAsString = scope.getScope();
+ if (scopeAsString == null) {
+ return null;
+ }
+ for (DependencyScope dependencyScope : DependencyScope.values()) {
+ if (scopeAsString.equalsIgnoreCase(dependencyScope.toString())) {
+ return dependencyScope;
+ }
+ }
+ return null;
+ }
+
+ @Nonnull
+ private static ModuleDependencyData buildDependency(
+ @Nonnull DataNode ownerModule,
+ @Nonnull IdeaModuleDependency dependency,
+ @Nonnull DataNode ideProject
+ ) throws IllegalStateException {
+ String moduleName = dependency.getTargetModuleName();
+ if (moduleName == null) {
+ throw new IllegalStateException(String.format(
+ "Can't parse gradle module dependency '%s'. Reason: referenced module name is undefined "
+ + "(module: '%s') ",
+ dependency,
+ moduleName
+ ));
+ }
- if (level == LibraryLevel.PROJECT && !GradleProjectResolverUtil.linkProjectLibrary(ideProject, library)) {
- level = LibraryLevel.MODULE;
- }
+ Set registeredModuleNames = ContainerUtil.newHashSet();
+ Collection> modulesDataNode = ExternalSystemApiUtil.getChildren(ideProject, ProjectKeys.MODULE);
+ for (DataNode moduleDataNode : modulesDataNode) {
+ String name = moduleDataNode.getData().getExternalName();
+ registeredModuleNames.add(name);
+ if (name.equals(moduleName)) {
+ return new ModuleDependencyData(ownerModule.getData(), moduleDataNode.getData());
+ }
+ }
+ throw new IllegalStateException(String.format(
+ "Can't parse gradle module dependency '%s'. Reason: no module with such name (%s) is found. "
+ + "Registered modules: %s",
+ dependency,
+ moduleName,
+ registeredModuleNames
+ ));
+ }
+
+ @Nonnull
+ private LibraryDependencyData buildDependency(
+ @Nonnull IdeaModule gradleModule,
+ @Nonnull DataNode ownerModule,
+ @Nonnull IdeaSingleEntryLibraryDependency dependency,
+ @Nonnull DataNode ideProject
+ ) throws IllegalStateException {
+ File binaryPath = dependency.getFile();
+ if (binaryPath == null) {
+ throw new IllegalStateException(String.format(
+ "Can't parse external library dependency '%s'. Reason: it doesn't specify path to the " +
+ "binaries",
+ dependency
+ ));
+ }
- return new LibraryDependencyData(ownerModule.getData(), library, level);
- }
+ String libraryName;
+ final GradleModuleVersion moduleVersion = dependency.getGradleModuleVersion();
+ LibraryLevel level;
+
+ // Gradle API doesn't explicitly provide information about unresolved libraries (http://issues.gradle.org/browse/GRADLE-1995).
+ // That's why we use this dirty hack here.
+ boolean unresolved = binaryPath.getPath().startsWith(UNRESOLVED_DEPENDENCY_PREFIX);
+
+ if (moduleVersion == null) {
+ // use module library level if the dependency does not originate from a remote repository.
+ level = LibraryLevel.MODULE;
+
+ if (binaryPath.isFile()) {
+ libraryName = FileUtil.getNameWithoutExtension(binaryPath);
+ }
+ else {
+ libraryName = FileUtil.sanitizeFileName(binaryPath.getPath());
+ }
+
+ if (unresolved) {
+ // Gradle uses names like 'unresolved dependency - commons-collections commons-collections 3.2'
+ // for unresolved dependencies.
+ libraryName = binaryPath.getName().substring(UNRESOLVED_DEPENDENCY_PREFIX.length());
+ int i = libraryName.indexOf(' ');
+ if (i >= 0) {
+ i = CharArrayUtil.shiftForward(libraryName, i + 1, " ");
+ }
+
+ if (i >= 0 && i < libraryName.length()) {
+ int dependencyNameIndex = i;
+ i = libraryName.indexOf(' ', dependencyNameIndex);
+ if (i > 0) {
+ libraryName =
+ String.format("%s-%s", libraryName.substring(dependencyNameIndex, i), libraryName.substring(i + 1));
+ }
+ }
+ }
+ }
+ else {
+ level = LibraryLevel.PROJECT;
+ libraryName = String.format("%s:%s:%s", moduleVersion.getGroup(), moduleVersion.getName(), moduleVersion.getVersion());
+ }
- private void attachGradleSdkSources(@Nonnull IdeaModule gradleModule,
- @Nonnull final String libName,
- @Nullable final File libFile,
- LibraryData library) {
- if (libFile == null || !libName.startsWith("gradle-")) {
- return;
- }
+ final LibraryData library = new LibraryData(GradleConstants.SYSTEM_ID, libraryName, unresolved);
+ if (!unresolved) {
+ library.addPath(LibraryPathType.BINARY, binaryPath.getAbsolutePath());
+ }
- final BuildScriptClasspathModel buildScriptClasspathModel = resolverCtx.getExtraProject(gradleModule, BuildScriptClasspathModel.class);
- if (buildScriptClasspathModel == null) {
- return;
- }
- final File gradleHomeDir = buildScriptClasspathModel.getGradleHomeDir();
- if (gradleHomeDir == null) {
- return;
- }
+ File sourcePath = dependency.getSource();
+ if (!unresolved && sourcePath != null) {
+ library.addPath(LibraryPathType.SOURCE, sourcePath.getAbsolutePath());
+ }
- if (!FileUtil.isAncestor(gradleHomeDir, libFile, true)) {
- return;
- }
+ if (!unresolved && sourcePath == null) {
+ attachGradleSdkSources(gradleModule, libraryName, binaryPath, library);
+ }
+
+ File javadocPath = dependency.getJavadoc();
+ if (!unresolved && javadocPath != null) {
+ library.addPath(LibraryPathType.DOC, javadocPath.getAbsolutePath());
+ }
- File libOrPluginsFile = libFile.getParentFile();
- if (libOrPluginsFile != null && ("plugins".equals(libOrPluginsFile.getName()))) {
- libOrPluginsFile = libOrPluginsFile.getParentFile();
+ if (level == LibraryLevel.PROJECT && !GradleProjectResolverUtil.linkProjectLibrary(ideProject, library)) {
+ level = LibraryLevel.MODULE;
+ }
+
+ return new LibraryDependencyData(ownerModule.getData(), library, level);
}
- if (libOrPluginsFile != null && "lib".equals(libOrPluginsFile.getName()) && libOrPluginsFile.getParentFile() != null) {
- File srcDir = new File(libOrPluginsFile.getParentFile(), "src");
+ private void attachGradleSdkSources(
+ @Nonnull IdeaModule gradleModule,
+ @Nonnull final String libName,
+ @Nullable final File libFile,
+ LibraryData library
+ ) {
+ if (libFile == null || !libName.startsWith("gradle-")) {
+ return;
+ }
- GradleVersion current = GradleVersion.version(buildScriptClasspathModel.getGradleVersion());
- if (current.compareTo(GradleVersion.version("1.9")) >= 0) {
- int endIndex = libName.indexOf(current.getVersion());
- if (endIndex != -1) {
- String srcDirChild = libName.substring("gradle-".length(), endIndex - 1);
- srcDir = new File(srcDir, srcDirChild);
+ final BuildScriptClasspathModel buildScriptClasspathModel =
+ resolverCtx.getExtraProject(gradleModule, BuildScriptClasspathModel.class);
+ if (buildScriptClasspathModel == null) {
+ return;
+ }
+ final File gradleHomeDir = buildScriptClasspathModel.getGradleHomeDir();
+ if (gradleHomeDir == null) {
+ return;
}
- }
- if (srcDir.isDirectory()) {
- library.addPath(LibraryPathType.SOURCE, srcDir.getAbsolutePath());
- }
+ if (!FileUtil.isAncestor(gradleHomeDir, libFile, true)) {
+ return;
+ }
+
+ File libOrPluginsFile = libFile.getParentFile();
+ if (libOrPluginsFile != null && ("plugins".equals(libOrPluginsFile.getName()))) {
+ libOrPluginsFile = libOrPluginsFile.getParentFile();
+ }
+
+ if (libOrPluginsFile != null && "lib".equals(libOrPluginsFile.getName()) && libOrPluginsFile.getParentFile() != null) {
+ File srcDir = new File(libOrPluginsFile.getParentFile(), "src");
+
+ GradleVersion current = GradleVersion.version(buildScriptClasspathModel.getGradleVersion());
+ if (current.compareTo(GradleVersion.version("1.9")) >= 0) {
+ int endIndex = libName.indexOf(current.getVersion());
+ if (endIndex != -1) {
+ String srcDirChild = libName.substring("gradle-".length(), endIndex - 1);
+ srcDir = new File(srcDir, srcDirChild);
+ }
+ }
+
+ if (srcDir.isDirectory()) {
+ library.addPath(LibraryPathType.SOURCE, srcDir.getAbsolutePath());
+ }
+ }
}
- }
- private static boolean isIdeaTask(final String taskName) {
- return taskName.toLowerCase(Locale.ENGLISH).contains("idea");
- }
+ private static boolean isIdeaTask(final String taskName) {
+ return taskName.toLowerCase(Locale.ENGLISH).contains("idea");
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandler.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandler.java
index 78b75a0..6a734ff 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandler.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandler.java
@@ -33,112 +33,113 @@
* @since 10/16/13
*/
public class BaseProjectImportErrorHandler extends AbstractProjectImportErrorHandler {
+ private static final Logger LOG = Logger.getInstance(BaseProjectImportErrorHandler.class);
+
+ @Nonnull
+ @Override
+ public ExternalSystemException getUserFriendlyError(
+ @Nonnull Throwable error,
+ @Nonnull String projectPath,
+ @Nullable String buildFilePath
+ ) {
+ if (error instanceof ExternalSystemException) {
+ // This is already a user-friendly error.
+ return (ExternalSystemException)error;
+ }
- private static final Logger LOG = Logger.getInstance(BaseProjectImportErrorHandler.class);
-
- @Nonnull
- @Override
- public ExternalSystemException getUserFriendlyError(@Nonnull Throwable error,
- @Nonnull String projectPath,
- @Nullable String buildFilePath) {
- if (error instanceof ExternalSystemException) {
- // This is already a user-friendly error.
- return (ExternalSystemException)error;
- }
-
- LOG.info(String.format("Failed to import Gradle project at '%1$s'", projectPath), error);
-
- Pair rootCauseAndLocation = getRootCauseAndLocation(error);
+ LOG.info(String.format("Failed to import Gradle project at '%1$s'", projectPath), error);
- Throwable rootCause = rootCauseAndLocation.getFirst();
+ Pair rootCauseAndLocation = getRootCauseAndLocation(error);
- String location = rootCauseAndLocation.getSecond();
- if (location == null && !StringUtil.isEmptyOrSpaces(buildFilePath)) {
- location = String.format("Build file: '%1$s'", buildFilePath);
- }
+ Throwable rootCause = rootCauseAndLocation.getFirst();
- if (rootCause instanceof UnsupportedVersionException) {
- String msg = "You are using unsupported version of Gradle.";
- msg += ('\n' + FIX_GRADLE_VERSION);
- // Location of build.gradle is useless for this error. Omitting it.
- return createUserFriendlyError(msg, null);
- }
+ String location = rootCauseAndLocation.getSecond();
+ if (location == null && !StringUtil.isEmptyOrSpaces(buildFilePath)) {
+ location = String.format("Build file: '%1$s'", buildFilePath);
+ }
- final String rootCauseText = rootCause.toString();
- if (StringUtil.startsWith(rootCauseText, "org.gradle.api.internal.MissingMethodException")) {
- String method = parseMissingMethod(rootCauseText);
- String msg = "Build script error, unsupported Gradle DSL method found: '" + method + "'!";
- msg += (EMPTY_LINE + "Possible causes could be: ");
- msg += ('\n' + " - you are using Gradle version where the method is absent ");
- msg += ('\n' + " - you didn't apply Gradle plugin which provides the method");
- msg += ('\n' + " - or there is a mistake in a build script");
- return createUserFriendlyError(msg, location);
- }
+ if (rootCause instanceof UnsupportedVersionException) {
+ String msg = "You are using unsupported version of Gradle.";
+ msg += ('\n' + FIX_GRADLE_VERSION);
+ // Location of build.gradle is useless for this error. Omitting it.
+ return createUserFriendlyError(msg, null);
+ }
- if (rootCause instanceof OutOfMemoryError) {
- // The OutOfMemoryError happens in the Gradle daemon process.
- String originalMessage = rootCause.getMessage();
- String msg = "Out of memory";
- if (originalMessage != null && !originalMessage.isEmpty()) {
- msg = msg + ": " + originalMessage;
- }
- if (msg.endsWith("Java heap space")) {
- msg += ". Configure Gradle memory settings using '-Xmx' JVM option (e.g. '-Xmx2048m'.)";
- }
- else if (!msg.endsWith(".")) {
- msg += ".";
- }
- msg += EMPTY_LINE + OPEN_GRADLE_SETTINGS;
- // Location of build.gradle is useless for this error. Omitting it.
- return createUserFriendlyError(msg, null);
- }
+ final String rootCauseText = rootCause.toString();
+ if (StringUtil.startsWith(rootCauseText, "org.gradle.api.internal.MissingMethodException")) {
+ String method = parseMissingMethod(rootCauseText);
+ String msg = "Build script error, unsupported Gradle DSL method found: '" + method + "'!";
+ msg += (EMPTY_LINE + "Possible causes could be: ");
+ msg += ('\n' + " - you are using Gradle version where the method is absent ");
+ msg += ('\n' + " - you didn't apply Gradle plugin which provides the method");
+ msg += ('\n' + " - or there is a mistake in a build script");
+ return createUserFriendlyError(msg, location);
+ }
- if (rootCause instanceof ClassNotFoundException) {
- String msg = String.format("Unable to load class '%1$s'.", rootCause.getMessage()) + EMPTY_LINE +
- UNEXPECTED_ERROR_FILE_BUG;
- // Location of build.gradle is useless for this error. Omitting it.
- return createUserFriendlyError(msg, null);
- }
+ if (rootCause instanceof OutOfMemoryError) {
+ // The OutOfMemoryError happens in the Gradle daemon process.
+ String originalMessage = rootCause.getMessage();
+ String msg = "Out of memory";
+ if (originalMessage != null && !originalMessage.isEmpty()) {
+ msg = msg + ": " + originalMessage;
+ }
+ if (msg.endsWith("Java heap space")) {
+ msg += ". Configure Gradle memory settings using '-Xmx' JVM option (e.g. '-Xmx2048m'.)";
+ }
+ else if (!msg.endsWith(".")) {
+ msg += ".";
+ }
+ msg += EMPTY_LINE + OPEN_GRADLE_SETTINGS;
+ // Location of build.gradle is useless for this error. Omitting it.
+ return createUserFriendlyError(msg, null);
+ }
- if (rootCause instanceof UnknownHostException) {
- String msg = String.format("Unknown host '%1$s'.", rootCause.getMessage()) +
- EMPTY_LINE + "Please ensure the host name is correct. " +
- SET_UP_HTTP_PROXY;
- // Location of build.gradle is useless for this error. Omitting it.
- return createUserFriendlyError(msg, null);
- }
+ if (rootCause instanceof ClassNotFoundException) {
+ String msg = String.format("Unable to load class '%1$s'.", rootCause.getMessage()) + EMPTY_LINE +
+ UNEXPECTED_ERROR_FILE_BUG;
+ // Location of build.gradle is useless for this error. Omitting it.
+ return createUserFriendlyError(msg, null);
+ }
- if (rootCause instanceof ConnectException) {
- String msg = rootCause.getMessage();
- if (msg != null && msg.contains("timed out")) {
- msg += msg.endsWith(".") ? " " : ". ";
- msg += SET_UP_HTTP_PROXY;
- return createUserFriendlyError(msg, null);
- }
- }
+ if (rootCause instanceof UnknownHostException) {
+ String msg = String.format("Unknown host '%1$s'.", rootCause.getMessage()) +
+ EMPTY_LINE + "Please ensure the host name is correct. " +
+ SET_UP_HTTP_PROXY;
+ // Location of build.gradle is useless for this error. Omitting it.
+ return createUserFriendlyError(msg, null);
+ }
- if (rootCause instanceof RuntimeException) {
- String msg = rootCause.getMessage();
+ if (rootCause instanceof ConnectException) {
+ String msg = rootCause.getMessage();
+ if (msg != null && msg.contains("timed out")) {
+ msg += msg.endsWith(".") ? " " : ". ";
+ msg += SET_UP_HTTP_PROXY;
+ return createUserFriendlyError(msg, null);
+ }
+ }
- if (msg != null && UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN.matcher(msg).matches()) {
- if (!msg.endsWith(".")) {
- msg += ".";
+ if (rootCause instanceof RuntimeException) {
+ String msg = rootCause.getMessage();
+
+ if (msg != null && UNSUPPORTED_GRADLE_VERSION_ERROR_PATTERN.matcher(msg).matches()) {
+ if (!msg.endsWith(".")) {
+ msg += ".";
+ }
+ msg += EMPTY_LINE + OPEN_GRADLE_SETTINGS;
+ // Location of build.gradle is useless for this error. Omitting it.
+ return createUserFriendlyError(msg, null);
+ }
}
- msg += EMPTY_LINE + OPEN_GRADLE_SETTINGS;
- // Location of build.gradle is useless for this error. Omitting it.
- return createUserFriendlyError(msg, null);
- }
- }
- final String errMessage;
- if (rootCause.getMessage() == null) {
- StringWriter writer = new StringWriter();
- rootCause.printStackTrace(new PrintWriter(writer));
- errMessage = writer.toString();
- }
- else {
- errMessage = rootCause.getMessage();
+ final String errMessage;
+ if (rootCause.getMessage() == null) {
+ StringWriter writer = new StringWriter();
+ rootCause.printStackTrace(new PrintWriter(writer));
+ errMessage = writer.toString();
+ }
+ else {
+ errMessage = rootCause.getMessage();
+ }
+ return createUserFriendlyError(errMessage, location);
}
- return createUserFriendlyError(errMessage, location);
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java
index 857ef8f..6bba433 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java
@@ -48,169 +48,209 @@
* @since 8/23/13
*/
public class DistributionFactoryExt extends DistributionFactory {
- public DistributionFactoryExt() {
- super(Time.clock());
- }
-
- /**
- * Returns the default distribution to use for the specified project.
- */
- public Distribution getWrappedDistribution(File propertiesFile) {
- //noinspection UseOfSystemOutOrSystemErr
- WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
- if (wrapper.getDistribution() != null) {
- return new ZippedDistribution(wrapper.getConfiguration(), Time.clock());
+ public DistributionFactoryExt() {
+ super(Time.clock());
}
- return getDownloadedDistribution(GradleVersion.current().getVersion());
- }
-
- private Distribution getDownloadedDistribution(String gradleVersion) {
- URI distUri = new DistributionLocator().getDistributionFor(GradleVersion.version(gradleVersion));
- return getDistribution(distUri);
- }
-
- private static class ProgressReportingDownload implements IDownload {
- private final ProgressLoggerFactory progressLoggerFactory;
+ /**
+ * Returns the default distribution to use for the specified project.
+ */
+ public Distribution getWrappedDistribution(File propertiesFile) {
+ //noinspection UseOfSystemOutOrSystemErr
+ WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile);
+ if (wrapper.getDistribution() != null) {
+ return new ZippedDistribution(wrapper.getConfiguration(), Time.clock());
+ }
- private ProgressReportingDownload(ProgressLoggerFactory progressLoggerFactory) {
- this.progressLoggerFactory = progressLoggerFactory;
+ return getDownloadedDistribution(GradleVersion.current().getVersion());
}
- @Override
- public void download(URI address, File destination) throws Exception {
- ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
- progressLogger.setDescription(String.format("Download %s", address));
- progressLogger.started();
- try {
- new Download(new Logger(false), "Gradle Tooling API", GradleVersion.current().getVersion()).download(address, destination);
- } finally {
- progressLogger.completed();
- }
+ private Distribution getDownloadedDistribution(String gradleVersion) {
+ URI distUri = new DistributionLocator().getDistributionFor(GradleVersion.version(gradleVersion));
+ return getDistribution(distUri);
}
- }
- private static class InstalledDistribution implements Distribution {
- private final File gradleHomeDir;
- private final String displayName;
- private final String locationDisplayName;
+ private static class ProgressReportingDownload implements IDownload {
+ private final ProgressLoggerFactory progressLoggerFactory;
- public InstalledDistribution(File gradleHomeDir, String displayName, String locationDisplayName) {
- this.gradleHomeDir = gradleHomeDir;
- this.displayName = displayName;
- this.locationDisplayName = locationDisplayName;
- }
+ private ProgressReportingDownload(ProgressLoggerFactory progressLoggerFactory) {
+ this.progressLoggerFactory = progressLoggerFactory;
+ }
- @Override
- public String getDisplayName() {
- return displayName;
+ @Override
+ public void download(URI address, File destination) throws Exception {
+ ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
+ progressLogger.setDescription(String.format("Download %s", address));
+ progressLogger.started();
+ try {
+ new Download(
+ new Logger(false),
+ "Gradle Tooling API",
+ GradleVersion.current().getVersion()
+ ).download(address, destination);
+ }
+ finally {
+ progressLogger.completed();
+ }
+ }
}
- @Override
- public ClassPath getToolingImplementationClasspath(ProgressLoggerFactory progressLoggerFactory, InternalBuildProgressListener internalBuildProgressListener, ConnectionParameters connectionParameters, BuildCancellationToken buildCancellationToken) {
- ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
- progressLogger.setDescription("Validate distribution");
- progressLogger.started();
- try {
- return getToolingImpl();
- } finally {
- progressLogger.completed();
- }
- }
+ private static class InstalledDistribution implements Distribution {
+ private final File gradleHomeDir;
+ private final String displayName;
+ private final String locationDisplayName;
- private ClassPath getToolingImpl() {
- if (!gradleHomeDir.exists()) {
- throw new IllegalArgumentException(String.format("The specified %s does not exist.", locationDisplayName));
- }
- if (!gradleHomeDir.isDirectory()) {
- throw new IllegalArgumentException(String.format("The specified %s is not a directory.", locationDisplayName));
- }
- File libDir = new File(gradleHomeDir, "lib");
- if (!libDir.isDirectory()) {
- throw new IllegalArgumentException(String.format("The specified %s does not appear to contain a Gradle distribution.",
- locationDisplayName));
- }
- Set files = new LinkedHashSet();
- //noinspection ConstantConditions
- for (File file : libDir.listFiles()) {
- if (file.getName().endsWith(".jar")) {
- files.add(file);
+ public InstalledDistribution(File gradleHomeDir, String displayName, String locationDisplayName) {
+ this.gradleHomeDir = gradleHomeDir;
+ this.displayName = displayName;
+ this.locationDisplayName = locationDisplayName;
}
- }
- return DefaultClassPath.of(files);
- }
- }
- private static class ZippedDistribution implements Distribution {
- private InstalledDistribution installedDistribution;
- private final WrapperConfiguration wrapperConfiguration;
- private final Clock clock;
+ @Override
+ public String getDisplayName() {
+ return displayName;
+ }
- private ZippedDistribution(WrapperConfiguration wrapperConfiguration, Clock clock) {
- this.wrapperConfiguration = wrapperConfiguration;
- this.clock = clock;
- }
+ @Override
+ public ClassPath getToolingImplementationClasspath(
+ ProgressLoggerFactory progressLoggerFactory,
+ InternalBuildProgressListener internalBuildProgressListener,
+ ConnectionParameters connectionParameters,
+ BuildCancellationToken buildCancellationToken
+ ) {
+ ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
+ progressLogger.setDescription("Validate distribution");
+ progressLogger.started();
+ try {
+ return getToolingImpl();
+ }
+ finally {
+ progressLogger.completed();
+ }
+ }
- @Override
- public String getDisplayName() {
- return String.format("Gradle distribution '%s'", wrapperConfiguration.getDistribution());
+ private ClassPath getToolingImpl() {
+ if (!gradleHomeDir.exists()) {
+ throw new IllegalArgumentException(String.format("The specified %s does not exist.", locationDisplayName));
+ }
+ if (!gradleHomeDir.isDirectory()) {
+ throw new IllegalArgumentException(String.format("The specified %s is not a directory.", locationDisplayName));
+ }
+ File libDir = new File(gradleHomeDir, "lib");
+ if (!libDir.isDirectory()) {
+ throw new IllegalArgumentException(String.format(
+ "The specified %s does not appear to contain a Gradle distribution.",
+ locationDisplayName
+ ));
+ }
+ Set files = new LinkedHashSet();
+ //noinspection ConstantConditions
+ for (File file : libDir.listFiles()) {
+ if (file.getName().endsWith(".jar")) {
+ files.add(file);
+ }
+ }
+ return DefaultClassPath.of(files);
+ }
}
- @Override
- public ClassPath getToolingImplementationClasspath(ProgressLoggerFactory progressLoggerFactory,
- InternalBuildProgressListener progressListener,
- ConnectionParameters connectionParameters,
- BuildCancellationToken cancellationToken) {
- if (installedDistribution == null) {
- final DistributionInstaller installer = new DistributionInstaller(progressLoggerFactory, progressListener, clock);
- File installDir;
- try {
- cancellationToken.addCallback(() -> installer.cancel());
- installDir = installer.install(determineRealUserHomeDir(connectionParameters), determineRootDir(connectionParameters),
- wrapperConfiguration, determineSystemProperties(connectionParameters));
- } catch (CancellationException e) {
- throw new BuildCancelledException(
- String.format("Distribution download cancelled. Using distribution from '%s'.", wrapperConfiguration.getDistribution()), e);
- } catch (FileNotFoundException e) {
- throw new IllegalArgumentException(String.format("The specified %s does not exist.", getDisplayName()), e);
- } catch (Exception e) {
- throw new GradleConnectionException(
- String.format("Could not install Gradle distribution from '%s'.", wrapperConfiguration.getDistribution()), e);
+ private static class ZippedDistribution implements Distribution {
+ private InstalledDistribution installedDistribution;
+ private final WrapperConfiguration wrapperConfiguration;
+ private final Clock clock;
+
+ private ZippedDistribution(WrapperConfiguration wrapperConfiguration, Clock clock) {
+ this.wrapperConfiguration = wrapperConfiguration;
+ this.clock = clock;
}
- installedDistribution = new InstalledDistribution(installDir, getDisplayName(), getDisplayName());
- }
- return installedDistribution.getToolingImplementationClasspath(progressLoggerFactory, progressListener, connectionParameters, cancellationToken);
- }
- private static Map determineSystemProperties(ConnectionParameters connectionParameters) {
- Map systemProperties = new HashMap<>();
+ @Override
+ public String getDisplayName() {
+ return String.format("Gradle distribution '%s'", wrapperConfiguration.getDistribution());
+ }
- for (Map.Entry objectEntry : System.getProperties().entrySet()) {
- systemProperties.put(objectEntry.getKey().toString(),
- objectEntry.getValue() == null ? null : objectEntry.getValue().toString());
- }
+ @Override
+ public ClassPath getToolingImplementationClasspath(
+ ProgressLoggerFactory progressLoggerFactory,
+ InternalBuildProgressListener progressListener,
+ ConnectionParameters connectionParameters,
+ BuildCancellationToken cancellationToken
+ ) {
+ if (installedDistribution == null) {
+ final DistributionInstaller installer = new DistributionInstaller(progressLoggerFactory, progressListener, clock);
+ File installDir;
+ try {
+ cancellationToken.addCallback(() -> installer.cancel());
+ installDir = installer.install(
+ determineRealUserHomeDir(connectionParameters),
+ determineRootDir(connectionParameters),
+ wrapperConfiguration,
+ determineSystemProperties(connectionParameters)
+ );
+ }
+ catch (CancellationException e) {
+ throw new BuildCancelledException(
+ String.format(
+ "Distribution download cancelled. Using distribution from '%s'.",
+ wrapperConfiguration.getDistribution()
+ ),
+ e
+ );
+ }
+ catch (FileNotFoundException e) {
+ throw new IllegalArgumentException(String.format("The specified %s does not exist.", getDisplayName()), e);
+ }
+ catch (Exception e) {
+ throw new GradleConnectionException(
+ String.format("Could not install Gradle distribution from '%s'.", wrapperConfiguration.getDistribution()),
+ e
+ );
+ }
+ installedDistribution = new InstalledDistribution(installDir, getDisplayName(), getDisplayName());
+ }
+ return installedDistribution.getToolingImplementationClasspath(
+ progressLoggerFactory,
+ progressListener,
+ connectionParameters,
+ cancellationToken
+ );
+ }
- systemProperties.putAll(
- SystemPropertiesHandler.getSystemProperties(new File(determineRootDir(connectionParameters), "gradle.properties")));
- systemProperties.putAll(
- SystemPropertiesHandler.getSystemProperties(new File(determineRealUserHomeDir(connectionParameters), "gradle.properties")));
- return systemProperties;
- }
+ private static Map determineSystemProperties(ConnectionParameters connectionParameters) {
+ Map systemProperties = new HashMap<>();
- private static File determineRootDir(ConnectionParameters connectionParameters) {
- return (new BuildLayoutFactory()).getLayoutFor(
- connectionParameters.getProjectDir(),
- connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true).getRootDirectory();
- }
+ for (Map.Entry objectEntry : System.getProperties().entrySet()) {
+ systemProperties.put(
+ objectEntry.getKey().toString(),
+ objectEntry.getValue() == null ? null : objectEntry.getValue().toString()
+ );
+ }
- private static File determineRealUserHomeDir(ConnectionParameters connectionParameters) {
- File distributionBaseDir = connectionParameters.getDistributionBaseDir();
- if (distributionBaseDir != null) {
- return distributionBaseDir;
- } else {
- File userHomeDir = connectionParameters.getGradleUserHomeDir();
- return userHomeDir != null ? userHomeDir : GradleUserHomeLookup.gradleUserHome();
- }
+ systemProperties.putAll(SystemPropertiesHandler.getSystemProperties(
+ new File(determineRootDir(connectionParameters), "gradle.properties")
+ ));
+ systemProperties.putAll(SystemPropertiesHandler.getSystemProperties(
+ new File(determineRealUserHomeDir(connectionParameters), "gradle.properties")
+ ));
+ return systemProperties;
+ }
+
+ private static File determineRootDir(ConnectionParameters connectionParameters) {
+ return (new BuildLayoutFactory()).getLayoutFor(
+ connectionParameters.getProjectDir(),
+ connectionParameters.isSearchUpwards() != null ? connectionParameters.isSearchUpwards() : true
+ ).getRootDirectory();
+ }
+
+ private static File determineRealUserHomeDir(ConnectionParameters connectionParameters) {
+ File distributionBaseDir = connectionParameters.getDistributionBaseDir();
+ if (distributionBaseDir != null) {
+ return distributionBaseDir;
+ }
+ else {
+ File userHomeDir = connectionParameters.getGradleUserHomeDir();
+ return userHomeDir != null ? userHomeDir : GradleUserHomeLookup.gradleUserHome();
+ }
+ }
}
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleAutoImportAware.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleAutoImportAware.java
index ba3c7cb..8083098 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleAutoImportAware.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleAutoImportAware.java
@@ -35,38 +35,37 @@
* @since 6/8/13 3:49 PM
*/
public class GradleAutoImportAware implements ExternalSystemAutoImportAware {
+ @Nullable
+ @Override
+ public String getAffectedExternalProjectPath(@Nonnull String changedFileOrDirPath, @Nonnull Project project) {
+ if (!changedFileOrDirPath.endsWith(GradleConstants.EXTENSION)) {
+ return null;
+ }
- @Nullable
- @Override
- public String getAffectedExternalProjectPath(@Nonnull String changedFileOrDirPath, @Nonnull Project project) {
- if (!changedFileOrDirPath.endsWith(GradleConstants.EXTENSION)) {
- return null;
- }
-
- ExternalSystemManager,?,?,?,?> manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
- assert manager != null;
- AbstractExternalSystemSettings, ?,?> systemSettings = manager.getSettingsProvider().apply(project);
- Collection extends ExternalProjectSettings> projectsSettings = systemSettings.getLinkedProjectsSettings();
- if (projectsSettings.isEmpty()) {
- return null;
- }
- Map rootPaths = new HashMap<>();
- for (ExternalProjectSettings setting : projectsSettings) {
- if(setting != null && setting.getExternalProjectPath() != null) {
- File rootPath = new File(setting.getExternalProjectPath());
- if(rootPath.getParentFile() != null) {
- rootPaths.put(rootPath.getParentFile().getAbsolutePath(), setting.getExternalProjectPath());
+ ExternalSystemManager, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
+ assert manager != null;
+ AbstractExternalSystemSettings, ?, ?> systemSettings = manager.getSettingsProvider().apply(project);
+ Collection extends ExternalProjectSettings> projectsSettings = systemSettings.getLinkedProjectsSettings();
+ if (projectsSettings.isEmpty()) {
+ return null;
+ }
+ Map rootPaths = new HashMap<>();
+ for (ExternalProjectSettings setting : projectsSettings) {
+ if (setting != null && setting.getExternalProjectPath() != null) {
+ File rootPath = new File(setting.getExternalProjectPath());
+ if (rootPath.getParentFile() != null) {
+ rootPaths.put(rootPath.getParentFile().getAbsolutePath(), setting.getExternalProjectPath());
+ }
+ }
}
- }
- }
- for (File f = new File(changedFileOrDirPath).getParentFile(); f != null; f = f.getParentFile()) {
- String dirPath = f.getAbsolutePath();
- String configFilePath = rootPaths.get(dirPath);
- if (rootPaths.containsKey(dirPath)) {
- return configFilePath;
- }
+ for (File f = new File(changedFileOrDirPath).getParentFile(); f != null; f = f.getParentFile()) {
+ String dirPath = f.getAbsolutePath();
+ String configFilePath = rootPaths.get(dirPath);
+ if (rootPaths.containsKey(dirPath)) {
+ return configFilePath;
+ }
+ }
+ return null;
}
- return null;
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java
index 79ecaf3..ebf6545 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java
@@ -58,439 +58,466 @@
* @since 3/14/13 5:11 PM
*/
public class GradleExecutionHelper {
- private static final Logger LOG = Logger.getInstance(GradleExecutionHelper.class);
-
- @SuppressWarnings("MethodMayBeStatic")
- @Nonnull
- public ModelBuilder getModelBuilder(@Nonnull Class modelType,
- @Nonnull final ExternalSystemTaskId id,
- @Nullable GradleExecutionSettings settings,
- @Nonnull ProjectConnection connection,
- @Nonnull ExternalSystemTaskNotificationListener
- listener,
- @Nonnull List extraJvmArgs) {
- ModelBuilder result = connection.model(modelType);
- prepare(result, id, settings, listener, extraJvmArgs, ContainerUtil.newArrayList(), connection);
- return result;
- }
-
- @SuppressWarnings("MethodMayBeStatic")
- @Nonnull
- public BuildLauncher getBuildLauncher(@Nonnull final ExternalSystemTaskId id,
- @Nonnull ProjectConnection connection,
- @Nullable GradleExecutionSettings settings,
- @Nonnull ExternalSystemTaskNotificationListener listener,
- @Nonnull final List vmOptions,
- @Nonnull final List commandLineArgs) {
- BuildLauncher result = connection.newBuild();
- prepare(result, id, settings, listener, vmOptions, commandLineArgs, connection);
- return result;
- }
-
- @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
- public static void prepare(@Nonnull LongRunningOperation operation,
- @Nonnull final ExternalSystemTaskId id,
- @Nullable GradleExecutionSettings settings,
- @Nonnull final ExternalSystemTaskNotificationListener listener,
- @Nonnull List extraJvmArgs,
- @Nonnull List commandLineArgs,
- @Nonnull ProjectConnection connection) {
- prepare(operation, id, settings, listener, extraJvmArgs, commandLineArgs, connection, new OutputWrapper(listener, id, true),
- new OutputWrapper(listener, id, false));
- }
-
-
- @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
- public static void prepare(@Nonnull LongRunningOperation operation,
- @Nonnull final ExternalSystemTaskId id,
- @Nullable GradleExecutionSettings settings,
- @Nonnull final ExternalSystemTaskNotificationListener listener,
- @Nonnull List extraJvmArgs,
- @Nonnull List commandLineArgs,
- @Nonnull ProjectConnection connection,
- @Nonnull final OutputStream standardOutput,
- @Nonnull final OutputStream standardError) {
- if (settings == null) {
- return;
- }
+ private static final Logger LOG = Logger.getInstance(GradleExecutionHelper.class);
+
+ @SuppressWarnings("MethodMayBeStatic")
+ @Nonnull
+ public ModelBuilder getModelBuilder(
+ @Nonnull Class modelType,
+ @Nonnull final ExternalSystemTaskId id,
+ @Nullable GradleExecutionSettings settings,
+ @Nonnull ProjectConnection connection,
+ @Nonnull ExternalSystemTaskNotificationListener listener,
+ @Nonnull List extraJvmArgs
+ ) {
+ ModelBuilder result = connection.model(modelType);
+ prepare(result, id, settings, listener, extraJvmArgs, ContainerUtil.newArrayList(), connection);
+ return result;
+ }
+
+ @SuppressWarnings("MethodMayBeStatic")
+ @Nonnull
+ public BuildLauncher getBuildLauncher(
+ @Nonnull final ExternalSystemTaskId id,
+ @Nonnull ProjectConnection connection,
+ @Nullable GradleExecutionSettings settings,
+ @Nonnull ExternalSystemTaskNotificationListener listener,
+ @Nonnull final List vmOptions,
+ @Nonnull final List commandLineArgs
+ ) {
+ BuildLauncher result = connection.newBuild();
+ prepare(result, id, settings, listener, vmOptions, commandLineArgs, connection);
+ return result;
+ }
+
+ @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
+ public static void prepare(
+ @Nonnull LongRunningOperation operation,
+ @Nonnull final ExternalSystemTaskId id,
+ @Nullable GradleExecutionSettings settings,
+ @Nonnull final ExternalSystemTaskNotificationListener listener,
+ @Nonnull List extraJvmArgs,
+ @Nonnull List commandLineArgs,
+ @Nonnull ProjectConnection connection
+ ) {
+ prepare(
+ operation,
+ id,
+ settings,
+ listener,
+ extraJvmArgs,
+ commandLineArgs,
+ connection,
+ new OutputWrapper(listener, id, true),
+ new OutputWrapper(listener, id, false)
+ );
+ }
+
+
+ @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
+ public static void prepare(
+ @Nonnull LongRunningOperation operation,
+ @Nonnull final ExternalSystemTaskId id,
+ @Nullable GradleExecutionSettings settings,
+ @Nonnull final ExternalSystemTaskNotificationListener listener,
+ @Nonnull List extraJvmArgs,
+ @Nonnull List commandLineArgs,
+ @Nonnull ProjectConnection connection,
+ @Nonnull final OutputStream standardOutput,
+ @Nonnull final OutputStream standardError
+ ) {
+ if (settings == null) {
+ return;
+ }
- Set jvmArgs = new HashSet<>();
+ Set jvmArgs = new HashSet<>();
- String vmOptions = settings.getDaemonVmOptions();
- if (!StringUtil.isEmpty(vmOptions)) {
- CommandLineTokenizer tokenizer = new CommandLineTokenizer(vmOptions);
- while (tokenizer.hasMoreTokens()) {
- String vmOption = tokenizer.nextToken();
- if (!StringUtil.isEmpty(vmOption)) {
- jvmArgs.add(vmOption);
+ String vmOptions = settings.getDaemonVmOptions();
+ if (!StringUtil.isEmpty(vmOptions)) {
+ CommandLineTokenizer tokenizer = new CommandLineTokenizer(vmOptions);
+ while (tokenizer.hasMoreTokens()) {
+ String vmOption = tokenizer.nextToken();
+ if (!StringUtil.isEmpty(vmOption)) {
+ jvmArgs.add(vmOption);
+ }
+ }
}
- }
- }
- jvmArgs.addAll(extraJvmArgs);
+ jvmArgs.addAll(extraJvmArgs);
- if (!jvmArgs.isEmpty()) {
- BuildEnvironment buildEnvironment = getBuildEnvironment(connection);
- Collection merged = buildEnvironment != null ? mergeJvmArgs(buildEnvironment.getJava().getJvmArguments(), jvmArgs) : jvmArgs;
+ if (!jvmArgs.isEmpty()) {
+ BuildEnvironment buildEnvironment = getBuildEnvironment(connection);
+ Collection merged =
+ buildEnvironment != null ? mergeJvmArgs(buildEnvironment.getJava().getJvmArguments(), jvmArgs) : jvmArgs;
- // filter nulls and empty strings
- List filteredArgs = ContainerUtil.mapNotNull(merged, s -> StringUtil.isEmpty(s) ? null : s);
+ // filter nulls and empty strings
+ List filteredArgs = ContainerUtil.mapNotNull(merged, s -> StringUtil.isEmpty(s) ? null : s);
- operation.setJvmArguments(ArrayUtil.toStringArray(filteredArgs));
- }
+ operation.setJvmArguments(ArrayUtil.toStringArray(filteredArgs));
+ }
- if (settings.isOfflineWork()) {
- commandLineArgs.add(GradleConstants.OFFLINE_MODE_CMD_OPTION);
- }
+ if (settings.isOfflineWork()) {
+ commandLineArgs.add(GradleConstants.OFFLINE_MODE_CMD_OPTION);
+ }
- if (!commandLineArgs.isEmpty()) {
- LOG.info("Passing command-line args to Gradle Tooling API: " + commandLineArgs);
- // filter nulls and empty strings
- List filteredArgs = ContainerUtil.mapNotNull(commandLineArgs, s -> StringUtil.isEmpty(s) ? null : s);
+ if (!commandLineArgs.isEmpty()) {
+ LOG.info("Passing command-line args to Gradle Tooling API: " + commandLineArgs);
+ // filter nulls and empty strings
+ List filteredArgs = ContainerUtil.mapNotNull(commandLineArgs, s -> StringUtil.isEmpty(s) ? null : s);
- // TODO remove this replacement when --tests option will become available for tooling API
- replaceTestCommandOptionWithInitScript(filteredArgs);
- operation.withArguments(ArrayUtil.toStringArray(filteredArgs));
- }
+ // TODO remove this replacement when --tests option will become available for tooling API
+ replaceTestCommandOptionWithInitScript(filteredArgs);
+ operation.withArguments(ArrayUtil.toStringArray(filteredArgs));
+ }
- listener.onStart(id);
- final String javaHome = settings.getJavaHome();
- if (javaHome != null && new File(javaHome).isDirectory()) {
- operation.setJavaHome(new File(javaHome));
- }
- operation.addProgressListener(new ProgressListener() {
- @Override
- public void statusChanged(ProgressEvent event) {
- listener.onStatusChange(new ExternalSystemTaskNotificationEvent(id, event.getDescription()));
- }
- });
- operation.setStandardOutput(standardOutput);
- operation.setStandardError(standardError);
- }
-
- public T execute(@Nonnull String projectPath, @Nullable GradleExecutionSettings settings, @Nonnull Function f) {
-
- final String projectDir;
- final File projectPathFile = new File(projectPath);
- if (projectPathFile.isFile() && projectPath.endsWith(GradleConstants.EXTENSION) && projectPathFile.getParent() != null) {
- projectDir = projectPathFile.getParent();
- }
- else {
- projectDir = projectPath;
- }
+ listener.onStart(id);
+ final String javaHome = settings.getJavaHome();
+ if (javaHome != null && new File(javaHome).isDirectory()) {
+ operation.setJavaHome(new File(javaHome));
+ }
+ operation.addProgressListener(
+ (ProgressListener)event -> listener.onStatusChange(new ExternalSystemTaskNotificationEvent(id, event.getDescription()))
+ );
+ operation.setStandardOutput(standardOutput);
+ operation.setStandardError(standardError);
+ }
+
+ public T execute(
+ @Nonnull String projectPath,
+ @Nullable GradleExecutionSettings settings,
+ @Nonnull Function f
+ ) {
+
+ final String projectDir;
+ final File projectPathFile = new File(projectPath);
+ if (projectPathFile.isFile() && projectPath.endsWith(GradleConstants.EXTENSION) && projectPathFile.getParent() != null) {
+ projectDir = projectPathFile.getParent();
+ }
+ else {
+ projectDir = projectPath;
+ }
- String userDir = null;
- if (!GradleEnvironment.ADJUST_USER_DIR) {
- try {
- userDir = System.getProperty("user.dir");
- if (userDir != null) {
- System.setProperty("user.dir", projectDir);
+ String userDir = null;
+ if (!GradleEnvironment.ADJUST_USER_DIR) {
+ try {
+ userDir = System.getProperty("user.dir");
+ if (userDir != null) {
+ System.setProperty("user.dir", projectDir);
+ }
+ }
+ catch (Exception ignore) {
+ }
+ }
+ ProjectConnection connection = getConnection(projectDir, settings);
+ try {
+ return f.apply(connection);
+ }
+ catch (ExternalSystemException e) {
+ throw e;
+ }
+ catch (Throwable e) {
+ LOG.debug("Gradle execution error", e);
+ Throwable rootCause = ExceptionUtil.getRootCause(e);
+ throw new ExternalSystemException(ExceptionUtil.getMessage(rootCause));
+ }
+ finally {
+ try {
+ connection.close();
+ if (userDir != null) {
+ // restore original user.dir property
+ System.setProperty("user.dir", userDir);
+ }
+ }
+ catch (Throwable e) {
+ // ignore
+ }
}
- }
- catch (Exception ignore) {
- }
- }
- ProjectConnection connection = getConnection(projectDir, settings);
- try {
- return f.apply(connection);
- }
- catch (ExternalSystemException e) {
- throw e;
- }
- catch (Throwable e) {
- LOG.debug("Gradle execution error", e);
- Throwable rootCause = ExceptionUtil.getRootCause(e);
- throw new ExternalSystemException(ExceptionUtil.getMessage(rootCause));
- }
- finally {
- try {
- connection.close();
- if (userDir != null) {
- // restore original user.dir property
- System.setProperty("user.dir", userDir);
- }
- }
- catch (Throwable e) {
- // ignore
- }
}
- }
-
- public void ensureInstalledWrapper(@Nonnull ExternalSystemTaskId id,
- @Nonnull String projectPath,
- @Nonnull GradleExecutionSettings settings,
- @Nonnull ExternalSystemTaskNotificationListener listener) {
- if (!settings.getDistributionType().isWrapped()) {
- return;
- }
+ public void ensureInstalledWrapper(
+ @Nonnull ExternalSystemTaskId id,
+ @Nonnull String projectPath,
+ @Nonnull GradleExecutionSettings settings,
+ @Nonnull ExternalSystemTaskNotificationListener listener
+ ) {
+ if (!settings.getDistributionType().isWrapped()) {
+ return;
+ }
- if (settings.getDistributionType() == DistributionType.DEFAULT_WRAPPED && GradleUtil.findDefaultWrapperPropertiesFile(projectPath) != null) {
- return;
- }
+ if (settings.getDistributionType() == DistributionType.DEFAULT_WRAPPED
+ && GradleUtil.findDefaultWrapperPropertiesFile(projectPath) != null) {
+ return;
+ }
- ProjectConnection connection = getConnection(projectPath, settings);
- try {
- try {
- final File tempFile = FileUtil.createTempFile("wrap", ".gradle");
- tempFile.deleteOnExit();
- final File wrapperPropertyFileLocation = FileUtil.createTempFile("wrap", "loc");
- wrapperPropertyFileLocation.deleteOnExit();
- final String[] lines = {
- "gradle.taskGraph.afterTask { Task task ->",
- " if (task instanceof Wrapper) {",
- " def wrapperPropertyFileLocation = task.jarFile.getCanonicalPath() - '.jar' + '.properties'",
- " new File('" +
- StringUtil.escapeBackSlashes(wrapperPropertyFileLocation.getCanonicalPath()) +
- "').write wrapperPropertyFileLocation",
- "}}",
- };
- FileUtil.writeToFile(tempFile, StringUtil.join(lines, SystemProperties.getLineSeparator()));
-
- BuildLauncher launcher = getBuildLauncher(id, connection, settings, listener, ContainerUtil.newArrayList(),
- ContainerUtil.newArrayList(GradleConstants.INIT_SCRIPT_CMD_OPTION,
- tempFile.getAbsolutePath()));
- launcher.forTasks("wrapper");
- launcher.run();
- String wrapperPropertyFile = FileUtil.loadFile(wrapperPropertyFileLocation);
- settings.setWrapperPropertyFile(wrapperPropertyFile);
- }
- catch (IOException e) {
- LOG.warn("Can't update wrapper", e);
- }
- }
- catch (Throwable e) {
- LOG.warn("Can't update wrapper", e);
- }
- finally {
- try {
- connection.close();
- }
- catch (Throwable e) {
- // ignore
- }
- }
- }
-
- private static List mergeJvmArgs(Iterable jvmArgs1, Iterable jvmArgs2) {
- JvmOptions jvmOptions = new JvmOptions(null);
- jvmOptions.setAllJvmArgs(ContainerUtil.concat(jvmArgs1, jvmArgs2));
- return jvmOptions.getAllJvmArgs();
- }
-
- /**
- * Allows to retrieve gradle api connection to use for the given project.
- *
- * @param projectPath target project path
- * @param settings execution settings to use
- * @return connection to use
- * @throws IllegalStateException if it's not possible to create the connection
- */
- @Nonnull
- private static ProjectConnection getConnection(@Nonnull String projectPath, @Nullable GradleExecutionSettings settings) throws
- IllegalStateException {
- File projectDir = new File(projectPath);
- GradleConnector connector = GradleConnector.newConnector();
- int ttl = -1;
-
- if (settings != null) {
- //noinspection EnumSwitchStatementWhichMissesCases
- switch (settings.getDistributionType()) {
- case LOCAL:
- String gradleHome = settings.getGradleHome();
- if (gradleHome != null) {
+ ProjectConnection connection = getConnection(projectPath, settings);
+ try {
try {
- // There were problems with symbolic links processing at the gradle side.
- connector.useInstallation(new File(gradleHome).getCanonicalFile());
+ final File tempFile = FileUtil.createTempFile("wrap", ".gradle");
+ tempFile.deleteOnExit();
+ final File wrapperPropertyFileLocation = FileUtil.createTempFile("wrap", "loc");
+ wrapperPropertyFileLocation.deleteOnExit();
+ final String[] lines = {
+ "gradle.taskGraph.afterTask { Task task ->",
+ " if (task instanceof Wrapper) {",
+ " def wrapperPropertyFileLocation = task.jarFile.getCanonicalPath() - '.jar' + '.properties'",
+ " new File('" +
+ StringUtil.escapeBackSlashes(wrapperPropertyFileLocation.getCanonicalPath()) +
+ "').write wrapperPropertyFileLocation",
+ "}}",
+ };
+ FileUtil.writeToFile(tempFile, StringUtil.join(lines, SystemProperties.getLineSeparator()));
+
+ BuildLauncher launcher = getBuildLauncher(id, connection, settings, listener, ContainerUtil.newArrayList(),
+ ContainerUtil.newArrayList(
+ GradleConstants.INIT_SCRIPT_CMD_OPTION,
+ tempFile.getAbsolutePath()
+ )
+ );
+ launcher.forTasks("wrapper");
+ launcher.run();
+ String wrapperPropertyFile = FileUtil.loadFile(wrapperPropertyFileLocation);
+ settings.setWrapperPropertyFile(wrapperPropertyFile);
}
catch (IOException e) {
- connector.useInstallation(new File(settings.getGradleHome()));
+ LOG.warn("Can't update wrapper", e);
}
- }
- break;
- case WRAPPED:
- if (settings.getWrapperPropertyFile() != null) {
- File propertiesFile = new File(settings.getWrapperPropertyFile());
- if (propertiesFile.exists()) {
- Distribution distribution = new DistributionFactoryExt().getWrappedDistribution
- (propertiesFile);
- try {
- setField(connector, "distribution", distribution);
- }
- catch (Exception e) {
- throw new ExternalSystemException(e);
- }
+ }
+ catch (Throwable e) {
+ LOG.warn("Can't update wrapper", e);
+ }
+ finally {
+ try {
+ connection.close();
}
- }
- break;
- }
-
- // Setup service directory if necessary.
- String serviceDirectory = settings.getServiceDirectory();
- if (serviceDirectory != null) {
- connector.useGradleUserHomeDir(new File(serviceDirectory));
- }
-
- // Setup logging if necessary.
- if (settings.isVerboseProcessing() && connector instanceof DefaultGradleConnector) {
- ((DefaultGradleConnector)connector).setVerboseLogging(true);
- }
- ttl = (int)settings.getRemoteProcessIdleTtlInMs();
+ catch (Throwable e) {
+ // ignore
+ }
+ }
}
- if (ttl > 0 && connector instanceof DefaultGradleConnector) {
- ((DefaultGradleConnector)connector).daemonMaxIdleTime(ttl, TimeUnit.MILLISECONDS);
- }
- connector.forProjectDirectory(projectDir);
- ProjectConnection connection = connector.connect();
- if (connection == null) {
- throw new IllegalStateException(String.format("Can't create connection to the target project via gradle tooling api. Project path: " +
- "'%s'", projectPath));
- }
- return connection;
- }
-
- /**
- * Utility to set field in object if there is no public setter for it.
- * It's not recommended to use this method.
- * FIXME: remove this workaround after gradle API changed
- *
- * @param obj Object to be modified
- * @param fieldName name of object's field
- * @param fieldValue value to be set for field
- * @throws SecurityException
- * @throws NoSuchFieldException
- * @throws IllegalArgumentException
- * @throws IllegalAccessException
- */
- public static void setField(Object obj, String fieldName, Object fieldValue) throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException {
- final Field field = obj.getClass().getDeclaredField(fieldName);
- final boolean isAccessible = field.isAccessible();
- field.setAccessible(true);
- field.set(obj, fieldValue);
- field.setAccessible(isAccessible);
- }
-
- @Nullable
- public static File generateInitScript(boolean isBuildSrcProject, @Nonnull Set toolingExtensionClasses) {
- InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/impl/internal/init/init.gradle_");
- try {
- if (stream == null) {
- LOG.warn("Can't get init script template");
- return null;
- }
- final String toolingExtensionsJarPaths = getToolingExtensionsJarPaths(toolingExtensionClasses);
- String s = FileUtil.loadTextAndClose(stream).replaceFirst(Pattern.quote("${EXTENSIONS_JARS_PATH}"), toolingExtensionsJarPaths);
- if (isBuildSrcProject) {
- String buildSrcDefaultInitScript = getBuildSrcDefaultInitScript();
- if (buildSrcDefaultInitScript == null) {
- return null;
- }
- s += buildSrcDefaultInitScript;
- }
-
- final File tempFile = FileUtil.createTempFile("ijinit", '.' + GradleConstants.EXTENSION, true);
- FileUtil.writeToFile(tempFile, s);
- return tempFile;
- }
- catch (Exception e) {
- LOG.warn("Can't generate IJ gradle init script", e);
- return null;
- }
- finally {
- StreamUtil.closeStream(stream);
- }
- }
-
- @Nullable
- public static String getBuildSrcDefaultInitScript() {
- InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/impl/internal/init/buildSrcInit.gradle_");
- try {
- if (stream == null) {
- return null;
- }
- return FileUtil.loadTextAndClose(stream);
- }
- catch (Exception e) {
- LOG.warn("Can't use IJ gradle init script", e);
- return null;
- }
- finally {
- StreamUtil.closeStream(stream);
- }
- }
+ private static List mergeJvmArgs(Iterable jvmArgs1, Iterable jvmArgs2) {
+ JvmOptions jvmOptions = new JvmOptions(null);
+ jvmOptions.setAllJvmArgs(ContainerUtil.concat(jvmArgs1, jvmArgs2));
+ return jvmOptions.getAllJvmArgs();
+ }
+
+ /**
+ * Allows to retrieve gradle api connection to use for the given project.
+ *
+ * @param projectPath target project path
+ * @param settings execution settings to use
+ * @return connection to use
+ * @throws IllegalStateException if it's not possible to create the connection
+ */
+ @Nonnull
+ private static ProjectConnection getConnection(@Nonnull String projectPath, @Nullable GradleExecutionSettings settings) throws
+ IllegalStateException {
+ File projectDir = new File(projectPath);
+ GradleConnector connector = GradleConnector.newConnector();
+ int ttl = -1;
+
+ if (settings != null) {
+ //noinspection EnumSwitchStatementWhichMissesCases
+ switch (settings.getDistributionType()) {
+ case LOCAL:
+ String gradleHome = settings.getGradleHome();
+ if (gradleHome != null) {
+ try {
+ // There were problems with symbolic links processing at the gradle side.
+ connector.useInstallation(new File(gradleHome).getCanonicalFile());
+ }
+ catch (IOException e) {
+ connector.useInstallation(new File(settings.getGradleHome()));
+ }
+ }
+ break;
+ case WRAPPED:
+ if (settings.getWrapperPropertyFile() != null) {
+ File propertiesFile = new File(settings.getWrapperPropertyFile());
+ if (propertiesFile.exists()) {
+ Distribution distribution = new DistributionFactoryExt().getWrappedDistribution
+ (propertiesFile);
+ try {
+ setField(connector, "distribution", distribution);
+ }
+ catch (Exception e) {
+ throw new ExternalSystemException(e);
+ }
+ }
+ }
+ break;
+ }
+
+ // Setup service directory if necessary.
+ String serviceDirectory = settings.getServiceDirectory();
+ if (serviceDirectory != null) {
+ connector.useGradleUserHomeDir(new File(serviceDirectory));
+ }
- @Nullable
- private static BuildEnvironment getBuildEnvironment(@Nonnull ProjectConnection connection) {
- try {
- return connection.getModel(BuildEnvironment.class);
+ // Setup logging if necessary.
+ if (settings.isVerboseProcessing() && connector instanceof DefaultGradleConnector defaultGradleConnector) {
+ defaultGradleConnector.setVerboseLogging(true);
+ }
+ ttl = (int)settings.getRemoteProcessIdleTtlInMs();
+ }
+
+ if (ttl > 0 && connector instanceof DefaultGradleConnector defaultGradleConnector) {
+ defaultGradleConnector.daemonMaxIdleTime(ttl, TimeUnit.MILLISECONDS);
+ }
+ connector.forProjectDirectory(projectDir);
+ ProjectConnection connection = connector.connect();
+ if (connection == null) {
+ throw new IllegalStateException(String.format(
+ "Can't create connection to the target project via gradle tooling api. Project path: '%s'",
+ projectPath
+ ));
+ }
+ return connection;
+ }
+
+ /**
+ * Utility to set field in object if there is no public setter for it.
+ * It's not recommended to use this method.
+ * FIXME: remove this workaround after gradle API changed
+ *
+ * @param obj Object to be modified
+ * @param fieldName name of object's field
+ * @param fieldValue value to be set for field
+ * @throws SecurityException
+ * @throws NoSuchFieldException
+ * @throws IllegalArgumentException
+ * @throws IllegalAccessException
+ */
+ public static void setField(Object obj, String fieldName, Object fieldValue) throws SecurityException, NoSuchFieldException,
+ IllegalArgumentException, IllegalAccessException {
+ final Field field = obj.getClass().getDeclaredField(fieldName);
+ final boolean isAccessible = field.isAccessible();
+ field.setAccessible(true);
+ field.set(obj, fieldValue);
+ field.setAccessible(isAccessible);
+ }
+
+ @Nullable
+ public static File generateInitScript(boolean isBuildSrcProject, @Nonnull Set toolingExtensionClasses) {
+ InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/impl/internal/init/init.gradle_");
+ try {
+ if (stream == null) {
+ LOG.warn("Can't get init script template");
+ return null;
+ }
+ final String toolingExtensionsJarPaths = getToolingExtensionsJarPaths(toolingExtensionClasses);
+ String s = FileUtil.loadTextAndClose(stream)
+ .replaceFirst(Pattern.quote("${EXTENSIONS_JARS_PATH}"), toolingExtensionsJarPaths);
+ if (isBuildSrcProject) {
+ String buildSrcDefaultInitScript = getBuildSrcDefaultInitScript();
+ if (buildSrcDefaultInitScript == null) {
+ return null;
+ }
+ s += buildSrcDefaultInitScript;
+ }
+
+ final File tempFile = FileUtil.createTempFile("ijinit", '.' + GradleConstants.EXTENSION, true);
+ FileUtil.writeToFile(tempFile, s);
+ return tempFile;
+ }
+ catch (Exception e) {
+ LOG.warn("Can't generate IJ gradle init script", e);
+ return null;
+ }
+ finally {
+ StreamUtil.closeStream(stream);
+ }
}
- catch (Exception e) {
- LOG.warn("can not get BuildEnvironment model", e);
- return null;
+
+ @Nullable
+ public static String getBuildSrcDefaultInitScript() {
+ InputStream stream =
+ Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/impl/internal/init/buildSrcInit.gradle_");
+ try {
+ if (stream == null) {
+ return null;
+ }
+ return FileUtil.loadTextAndClose(stream);
+ }
+ catch (Exception e) {
+ LOG.warn("Can't use IJ gradle init script", e);
+ return null;
+ }
+ finally {
+ StreamUtil.closeStream(stream);
+ }
}
- }
-
- private static void replaceTestCommandOptionWithInitScript(@Nonnull List args) {
- Set testIncludePatterns = ContainerUtil.newLinkedHashSet();
- Iterator it = args.iterator();
- while (it.hasNext()) {
- final String next = it.next();
- if ("--tests".equals(next)) {
- it.remove();
- if (it.hasNext()) {
- testIncludePatterns.add(it.next());
- it.remove();
- }
- }
+
+ @Nullable
+ private static BuildEnvironment getBuildEnvironment(@Nonnull ProjectConnection connection) {
+ try {
+ return connection.getModel(BuildEnvironment.class);
+ }
+ catch (Exception e) {
+ LOG.warn("can not get BuildEnvironment model", e);
+ return null;
+ }
}
- if (!testIncludePatterns.isEmpty()) {
- StringBuilder buf = new StringBuilder();
- buf.append('[');
- for (Iterator iterator = testIncludePatterns.iterator(); iterator.hasNext(); ) {
- String pattern = iterator.next();
- buf.append('\"').append(pattern).append('\"');
- if (iterator.hasNext()) {
- buf.append(',');
- }
- }
- buf.append(']');
-
- InputStream stream =
- Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/impl/internal/init/testFilterInit.gradle_");
- try {
- if (stream == null) {
- LOG.warn("Can't get test filter init script template");
- return;
- }
- String s = FileUtil.loadTextAndClose(stream).replaceFirst(Pattern.quote("${TEST_NAME_INCLUDES}"), buf.toString());
- final File tempFile = FileUtil.createTempFile("ijinit", '.' + GradleConstants.EXTENSION, true);
- FileUtil.writeToFile(tempFile, s);
- ContainerUtil.addAll(args, GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath());
- }
- catch (Exception e) {
- LOG.warn("Can't generate IJ gradle test filter init script", e);
- }
- finally {
- StreamUtil.closeStream(stream);
- }
+
+ private static void replaceTestCommandOptionWithInitScript(@Nonnull List args) {
+ Set testIncludePatterns = ContainerUtil.newLinkedHashSet();
+ Iterator it = args.iterator();
+ while (it.hasNext()) {
+ final String next = it.next();
+ if ("--tests".equals(next)) {
+ it.remove();
+ if (it.hasNext()) {
+ testIncludePatterns.add(it.next());
+ it.remove();
+ }
+ }
+ }
+ if (!testIncludePatterns.isEmpty()) {
+ StringBuilder buf = new StringBuilder();
+ buf.append('[');
+ for (Iterator iterator = testIncludePatterns.iterator(); iterator.hasNext(); ) {
+ String pattern = iterator.next();
+ buf.append('\"').append(pattern).append('\"');
+ if (iterator.hasNext()) {
+ buf.append(',');
+ }
+ }
+ buf.append(']');
+
+ InputStream stream =
+ Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/impl/internal/init/testFilterInit.gradle_");
+ try {
+ if (stream == null) {
+ LOG.warn("Can't get test filter init script template");
+ return;
+ }
+ String s = FileUtil.loadTextAndClose(stream).replaceFirst(Pattern.quote("${TEST_NAME_INCLUDES}"), buf.toString());
+ final File tempFile = FileUtil.createTempFile("ijinit", '.' + GradleConstants.EXTENSION, true);
+ FileUtil.writeToFile(tempFile, s);
+ ContainerUtil.addAll(args, GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath());
+ }
+ catch (Exception e) {
+ LOG.warn("Can't generate IJ gradle test filter init script", e);
+ }
+ finally {
+ StreamUtil.closeStream(stream);
+ }
+ }
}
- }
-
- @Nonnull
- private static String getToolingExtensionsJarPaths(@Nonnull Set toolingExtensionClasses) {
- StringBuilder buf = new StringBuilder();
- buf.append('[');
- for (Iterator it = toolingExtensionClasses.iterator(); it.hasNext(); ) {
- Class> aClass = it.next();
- String jarPath = PathUtil.getCanonicalPath(PathUtil.getJarPathForClass(aClass));
- buf.append('\"').append(jarPath).append('\"');
- if (it.hasNext()) {
- buf.append(',');
- }
+
+ @Nonnull
+ private static String getToolingExtensionsJarPaths(@Nonnull Set toolingExtensionClasses) {
+ StringBuilder buf = new StringBuilder();
+ buf.append('[');
+ for (Iterator it = toolingExtensionClasses.iterator(); it.hasNext(); ) {
+ Class> aClass = it.next();
+ String jarPath = PathUtil.getCanonicalPath(PathUtil.getJarPathForClass(aClass));
+ buf.append('\"').append(jarPath).append('\"');
+ if (it.hasNext()) {
+ buf.append(',');
+ }
+ }
+ buf.append(']');
+ return buf.toString();
}
- buf.append(']');
- return buf.toString();
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotification.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotification.java
index f2e9f3c..3063ede 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotification.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotification.java
@@ -38,27 +38,31 @@
@ServiceImpl
@Singleton
public class GradleNotification {
- public static final NotificationGroup NOTIFICATION_GROUP = NotificationGroup.balloonGroup("Gradle Notification Group");
+ public static final NotificationGroup NOTIFICATION_GROUP = NotificationGroup.balloonGroup("Gradle Notification Group");
- @Nonnull
- private final Project myProject;
+ @Nonnull
+ private final Project myProject;
- @Nonnull
- public static GradleNotification getInstance(@Nonnull Project project) {
- return ServiceManager.getService(project, GradleNotification.class);
- }
+ @Nonnull
+ public static GradleNotification getInstance(@Nonnull Project project) {
+ return ServiceManager.getService(project, GradleNotification.class);
+ }
- @Inject
- public GradleNotification(@Nonnull Project project) {
- myProject = project;
- }
+ @Inject
+ public GradleNotification(@Nonnull Project project) {
+ myProject = project;
+ }
- public void showBalloon(@Nonnull final String title,
- @Nonnull final String message,
- @Nonnull final NotificationType type,
- @Nullable final NotificationListener listener) {
- AppUIUtil.invokeLaterIfProjectAlive(myProject,
- () -> NOTIFICATION_GROUP.createNotification(title, message, type, listener).notify(myProject));
- }
+ public void showBalloon(
+ @Nonnull final String title,
+ @Nonnull final String message,
+ @Nonnull final NotificationType type,
+ @Nullable final NotificationListener listener
+ ) {
+ AppUIUtil.invokeLaterIfProjectAlive(
+ myProject,
+ () -> NOTIFICATION_GROUP.createNotification(title, message, type, listener).notify(myProject)
+ );
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotificationContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotificationContributor.java
index 0b411c5..fd145d1 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotificationContributor.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleNotificationContributor.java
@@ -13,8 +13,8 @@
*/
@ExtensionImpl
public class GradleNotificationContributor implements NotificationGroupContributor {
- @Override
- public void contribute(@Nonnull Consumer consumer) {
- consumer.accept(GradleNotification.NOTIFICATION_GROUP);
- }
+ @Override
+ public void contribute(@Nonnull Consumer consumer) {
+ consumer.accept(GradleNotification.NOTIFICATION_GROUP);
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
index 7f64397..6213026 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
@@ -59,375 +59,390 @@
* @author Denis Zhdanov, Vladislav Soroka
* @since 8/8/11 11:09 AM
*/
-public class GradleProjectResolver implements ExternalSystemProjectResolver
-{
- private static final Logger LOG = Logger.getInstance(GradleProjectResolver.class);
-
- @Nonnull
- private final GradleExecutionHelper myHelper;
- private final GradleLibraryNamesMixer myLibraryNamesMixer = new GradleLibraryNamesMixer();
-
- // This constructor is called by external system API, see AbstractExternalSystemFacadeImpl class constructor.
- @SuppressWarnings("UnusedDeclaration")
- public GradleProjectResolver()
- {
- this(new GradleExecutionHelper());
- }
-
- public GradleProjectResolver(@Nonnull GradleExecutionHelper helper)
- {
- myHelper = helper;
- }
-
- @Nullable
- @Override
- public DataNode resolveProjectInfo(@Nonnull final ExternalSystemTaskId id, @Nonnull final String projectPath,
- final boolean isPreviewMode, @Nullable final GradleExecutionSettings settings, @Nonnull final ExternalSystemTaskNotificationListener
- listener) throws ExternalSystemException, IllegalArgumentException, IllegalStateException
- {
- if(settings != null)
- {
- myHelper.ensureInstalledWrapper(id, projectPath, settings, listener);
- }
-
- final GradleProjectResolverExtension projectResolverChain = createProjectResolverChain(settings);
- final DataNode resultProjectDataNode = myHelper.execute(projectPath, settings, new ProjectConnectionDataNodeFunction(id,
- projectPath, settings, listener, isPreviewMode, projectResolverChain, false));
-
- // auto-discover buildSrc project if needed
- final String buildSrcProjectPath = projectPath + "/buildSrc";
- handleBuildSrcProject(resultProjectDataNode, new ProjectConnectionDataNodeFunction(id, buildSrcProjectPath, settings, listener,
- isPreviewMode, projectResolverChain, true));
- return resultProjectDataNode;
- }
-
- @Override
- public boolean cancelTask(@Nonnull ExternalSystemTaskId id, @Nonnull ExternalSystemTaskNotificationListener listener)
- {
- // TODO implement cancellation using gradle API invocation when it will be ready, see http://issues.gradle.org/browse/GRADLE-1539
- return false;
- }
-
- @Nonnull
- private DataNode doResolveProjectInfo(@Nonnull final ProjectResolverContext resolverCtx,
- @Nonnull final GradleProjectResolverExtension projectResolverChain, boolean isBuildSrcProject) throws IllegalArgumentException,
- IllegalStateException
- {
-
- final ProjectImportAction projectImportAction = new ProjectImportAction(resolverCtx.isPreviewMode());
-
- final List> extraJvmArgs = new ArrayList<>();
- final List commandLineArgs = ContainerUtil.newArrayList();
- final Set toolingExtensionClasses = ContainerUtil.newHashSet();
-
- for(GradleProjectResolverExtension resolverExtension = projectResolverChain; resolverExtension != null; resolverExtension =
- resolverExtension.getNext())
- {
- // inject ProjectResolverContext into gradle project resolver extensions
- resolverExtension.setProjectResolverContext(resolverCtx);
- // pre-import checks
- resolverExtension.preImportCheck();
- // register classes of extra gradle project models required for extensions (e.g. com.android.builder.model.AndroidProject)
- projectImportAction.addExtraProjectModelClasses(resolverExtension.getExtraProjectModelClasses());
- // collect extra JVM arguments provided by gradle project resolver extensions
- extraJvmArgs.addAll(resolverExtension.getExtraJvmArgs());
- // collect extra command-line arguments
- commandLineArgs.addAll(resolverExtension.getExtraCommandLineArgs());
- // collect tooling extensions classes
- toolingExtensionClasses.addAll(resolverExtension.getToolingExtensionsClasses());
- }
-
- final ParametersList parametersList = new ParametersList();
- for(Pair jvmArg : extraJvmArgs)
- {
- parametersList.addProperty(jvmArg.getFirst(), jvmArg.getSecond());
- }
-
-
- BuildActionExecuter buildActionExecutor = resolverCtx.getConnection().action(projectImportAction);
-
- // TODO [vlad] remove the check
- if(!GradleEnvironment.DISABLE_ENHANCED_TOOLING_API)
- {
- File initScript = GradleExecutionHelper.generateInitScript(isBuildSrcProject, toolingExtensionClasses);
- if(initScript != null)
- {
- ContainerUtil.addAll(commandLineArgs, GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
- }
- }
-
- GradleExecutionHelper.prepare(buildActionExecutor, resolverCtx.getExternalSystemTaskId(), resolverCtx.getSettings(),
- resolverCtx.getListener(), parametersList.getParameters(), commandLineArgs, resolverCtx.getConnection());
-
- ProjectImportAction.AllModels allModels;
- try
- {
- allModels = buildActionExecutor.run();
- if(allModels == null)
- {
- throw new IllegalStateException("Unable to get project model for the project: " + resolverCtx.getProjectPath());
- }
- }
- catch(UnsupportedVersionException unsupportedVersionException)
- {
- // Old gradle distribution version used (before ver. 1.8)
- // fallback to use ModelBuilder gradle tooling API
- Class extends IdeaProject> aClass = resolverCtx.isPreviewMode() ? BasicIdeaProject.class : IdeaProject.class;
- ModelBuilder extends IdeaProject> modelBuilder = myHelper.getModelBuilder(aClass, resolverCtx.getExternalSystemTaskId(),
- resolverCtx.getSettings(), resolverCtx.getConnection(), resolverCtx.getListener(), parametersList.getParameters());
-
- final IdeaProject ideaProject = modelBuilder.get();
- allModels = new ProjectImportAction.AllModels(ideaProject);
- }
-
- final BuildEnvironment buildEnvironment = getBuildEnvironment(resolverCtx);
- allModels.setBuildEnvironment(buildEnvironment);
- resolverCtx.setModels(allModels);
-
- // import project data
- ProjectData projectData = projectResolverChain.createProject();
- DataNode projectDataNode = new DataNode(ProjectKeys.PROJECT, projectData, null);
-
- // import java project data
- JavaProjectData javaProjectData = projectResolverChain.createJavaProjectData();
- projectDataNode.createChild(JavaProjectData.KEY, javaProjectData);
-
- IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
-
- projectResolverChain.populateProjectExtraModels(ideaProject, projectDataNode);
-
- DomainObjectSet extends IdeaModule> gradleModules = ideaProject.getModules();
- if(gradleModules == null || gradleModules.isEmpty())
- {
- throw new IllegalStateException("No modules found for the target project: " + ideaProject);
- }
- final Map, IdeaModule>> moduleMap = new HashMap<>();
-
- // import modules data
- for(IdeaModule gradleModule : gradleModules)
- {
- if(gradleModule == null)
- {
- continue;
- }
-
- if(ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING)
- {
- LOG.info(String.format("Importing module data: %s", gradleModule));
- }
-
- final String moduleName = gradleModule.getName();
- if(moduleName == null)
- {
- throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
- }
-
- ModuleData moduleData = projectResolverChain.createModule(gradleModule, projectData);
-
- Pair, IdeaModule> previouslyParsedModule = moduleMap.get(moduleName);
- if(previouslyParsedModule != null)
- {
- throw new IllegalStateException(String.format("Modules with duplicate name (%s) detected: '%s' and '%s'", moduleName, moduleData,
- previouslyParsedModule));
- }
- DataNode moduleDataNode = projectDataNode.createChild(ProjectKeys.MODULE, moduleData);
- moduleMap.put(moduleName, Pair.create(moduleDataNode, gradleModule));
- }
-
- // populate modules nodes
- final List allTasks = ContainerUtil.newArrayList();
- for(final Pair, IdeaModule> pair : moduleMap.values())
- {
- final DataNode moduleDataNode = pair.first;
- final IdeaModule ideaModule = pair.second;
- projectResolverChain.populateModuleExtraModels(ideaModule, moduleDataNode);
- projectResolverChain.populateModuleContentRoots(ideaModule, moduleDataNode);
- projectResolverChain.populateModuleCompileOutputSettings(ideaModule, moduleDataNode);
- projectResolverChain.populateModuleDependencies(ideaModule, moduleDataNode, projectDataNode);
- if(!isBuildSrcProject)
- {
- final Collection moduleTasks = projectResolverChain.populateModuleTasks(ideaModule, moduleDataNode, projectDataNode);
- allTasks.addAll(moduleTasks);
- }
- }
-
- // populate root project tasks
- final Collection rootProjectTaskCandidates = projectResolverChain.filterRootProjectTasks(allTasks);
-
- Set> rootProjectTaskCandidatesMap = new HashSet<>();
- for(final TaskData taskData : rootProjectTaskCandidates)
- {
- rootProjectTaskCandidatesMap.add(Couple.of(taskData.getName(), taskData.getDescription()));
- }
- for(final Couple p : rootProjectTaskCandidatesMap)
- {
- projectDataNode.createChild(ProjectKeys.TASK, new TaskData(GradleConstants.SYSTEM_ID, p.first, projectData.getLinkedExternalProjectPath
- (), p.second));
- }
-
- // ensure unique library names
- Collection> libraries = ExternalSystemApiUtil.getChildren(projectDataNode, ProjectKeys.LIBRARY);
- myLibraryNamesMixer.mixNames(libraries);
-
- return projectDataNode;
- }
-
- @Nullable
- private static BuildEnvironment getBuildEnvironment(@Nonnull ProjectResolverContext resolverCtx)
- {
- try
- {
- return resolverCtx.getConnection().getModel(BuildEnvironment.class);
- }
- catch(Exception e)
- {
- return null;
- }
- }
-
- private void handleBuildSrcProject(@Nonnull final DataNode resultProjectDataNode, @Nonnull final ProjectConnectionDataNodeFunction
- projectConnectionDataNodeFunction)
- {
-
- if(projectConnectionDataNodeFunction.myIsPreviewMode || GradleEnvironment.DISABLE_ENHANCED_TOOLING_API || !new File
- (projectConnectionDataNodeFunction.myProjectPath).isDirectory())
- {
- return;
- }
-
- final DataNode buildSrcModuleDataNode = ExternalSystemApiUtil.find(resultProjectDataNode, ProjectKeys.MODULE,
- new BooleanFunction>()
- {
- @Override
- public boolean fun(DataNode node)
- {
- return projectConnectionDataNodeFunction.myProjectPath.equals(node.getData().getLinkedExternalProjectPath());
- }
- });
-
- // check if buildSrc project was already exposed in settings.gradle file
- if(buildSrcModuleDataNode != null)
- {
- return;
- }
-
- final DataNode buildSrcProjectDataDataNode = myHelper.execute(projectConnectionDataNodeFunction.myProjectPath,
- projectConnectionDataNodeFunction.mySettings, projectConnectionDataNodeFunction);
-
- if(buildSrcProjectDataDataNode != null)
- {
- final DataNode moduleDataNode = ExternalSystemApiUtil.find(buildSrcProjectDataDataNode, ProjectKeys.MODULE);
- if(moduleDataNode != null)
- {
- for(DataNode libraryDataNode : ExternalSystemApiUtil.findAll(buildSrcProjectDataDataNode, ProjectKeys.LIBRARY))
- {
- resultProjectDataNode.createChild(libraryDataNode.getKey(), libraryDataNode.getData());
- }
-
- final DataNode newModuleDataNode = resultProjectDataNode.createChild(ProjectKeys.MODULE, moduleDataNode.getData());
- for(DataNode node : moduleDataNode.getChildren())
- {
- newModuleDataNode.createChild(node.getKey(), node.getData());
- }
- }
- }
- }
-
- private class ProjectConnectionDataNodeFunction implements Function>
- {
- @Nonnull
- private final ExternalSystemTaskId myId;
- @Nonnull
- private final String myProjectPath;
- @Nullable
- private final GradleExecutionSettings mySettings;
- @Nonnull
- private final ExternalSystemTaskNotificationListener myListener;
- private final boolean myIsPreviewMode;
- @Nonnull
- private final GradleProjectResolverExtension myProjectResolverChain;
- private final boolean myIsBuildSrcProject;
-
- public ProjectConnectionDataNodeFunction(@Nonnull ExternalSystemTaskId id, @Nonnull String projectPath,
- @Nullable GradleExecutionSettings settings, @Nonnull ExternalSystemTaskNotificationListener listener, boolean isPreviewMode,
- @Nonnull GradleProjectResolverExtension projectResolverChain, boolean isBuildSrcProject)
- {
- myId = id;
- myProjectPath = projectPath;
- mySettings = settings;
- myListener = listener;
- myIsPreviewMode = isPreviewMode;
- myProjectResolverChain = projectResolverChain;
- myIsBuildSrcProject = isBuildSrcProject;
- }
-
- @Override
- public DataNode apply(ProjectConnection connection)
- {
- try
- {
- return doResolveProjectInfo(new ProjectResolverContext(myId, myProjectPath, mySettings, connection, myListener, myIsPreviewMode),
- myProjectResolverChain, myIsBuildSrcProject);
- }
- catch(RuntimeException e)
- {
- LOG.info("Gradle project resolve error", e);
- throw myProjectResolverChain.getUserFriendlyError(e, myProjectPath, null);
- }
- }
- }
-
-
- @Nonnull
- public static GradleProjectResolverExtension createProjectResolverChain(@Nullable final GradleExecutionSettings settings)
- {
- GradleProjectResolverExtension projectResolverChain;
- if(settings != null)
- {
- List> extensionClasses = settings.getResolverExtensions();
-
- Deque extensions = new ArrayDeque();
- for(ClassHolder extends GradleProjectResolverExtension> holder : extensionClasses)
- {
- final GradleProjectResolverExtension extension;
- try
- {
- extension = holder.getTargetClass().newInstance();
- }
- catch(Throwable e)
- {
- throw new IllegalArgumentException(String.format("Can't instantiate project resolve extension for class '%s'",
- holder.getTargetClassName()), e);
- }
- final GradleProjectResolverExtension previous = extensions.peekLast();
- if(previous != null)
- {
- previous.setNext(extension);
- if(previous.getNext() != extension)
- {
- throw new AssertionError("Illegal next resolver got, current resolver class is " + previous.getClass().getName());
- }
- }
- extensions.add(extension);
- }
- projectResolverChain = extensions.peekFirst();
-
- GradleProjectResolverExtension resolverExtension = projectResolverChain;
- assert resolverExtension != null;
- while(resolverExtension.getNext() != null)
- {
- resolverExtension = resolverExtension.getNext();
- }
- if(!(resolverExtension instanceof BaseGradleProjectResolverExtension))
- {
- throw new AssertionError("Illegal last resolver got of class " + resolverExtension.getClass().getName());
- }
- }
- else
- {
- projectResolverChain = new BaseGradleProjectResolverExtension();
- }
-
- return projectResolverChain;
- }
+public class GradleProjectResolver implements ExternalSystemProjectResolver {
+ private static final Logger LOG = Logger.getInstance(GradleProjectResolver.class);
+
+ @Nonnull
+ private final GradleExecutionHelper myHelper;
+ private final GradleLibraryNamesMixer myLibraryNamesMixer = new GradleLibraryNamesMixer();
+
+ // This constructor is called by external system API, see AbstractExternalSystemFacadeImpl class constructor.
+ @SuppressWarnings("UnusedDeclaration")
+ public GradleProjectResolver() {
+ this(new GradleExecutionHelper());
+ }
+
+ public GradleProjectResolver(@Nonnull GradleExecutionHelper helper) {
+ myHelper = helper;
+ }
+
+ @Nullable
+ @Override
+ public DataNode resolveProjectInfo(
+ @Nonnull final ExternalSystemTaskId id,
+ @Nonnull final String projectPath,
+ final boolean isPreviewMode,
+ @Nullable final GradleExecutionSettings settings,
+ @Nonnull final ExternalSystemTaskNotificationListener listener
+ ) throws ExternalSystemException, IllegalArgumentException, IllegalStateException {
+ if (settings != null) {
+ myHelper.ensureInstalledWrapper(id, projectPath, settings, listener);
+ }
+
+ final GradleProjectResolverExtension projectResolverChain = createProjectResolverChain(settings);
+ final DataNode resultProjectDataNode =
+ myHelper.execute(
+ projectPath,
+ settings,
+ new ProjectConnectionDataNodeFunction(
+ id,
+ projectPath,
+ settings,
+ listener,
+ isPreviewMode,
+ projectResolverChain,
+ false
+ )
+ );
+
+ // auto-discover buildSrc project if needed
+ final String buildSrcProjectPath = projectPath + "/buildSrc";
+ handleBuildSrcProject(
+ resultProjectDataNode,
+ new ProjectConnectionDataNodeFunction(
+ id,
+ buildSrcProjectPath,
+ settings,
+ listener,
+ isPreviewMode,
+ projectResolverChain,
+ true
+ )
+ );
+ return resultProjectDataNode;
+ }
+
+ @Override
+ public boolean cancelTask(@Nonnull ExternalSystemTaskId id, @Nonnull ExternalSystemTaskNotificationListener listener) {
+ // TODO implement cancellation using gradle API invocation when it will be ready, see http://issues.gradle.org/browse/GRADLE-1539
+ return false;
+ }
+
+ @Nonnull
+ private DataNode doResolveProjectInfo(
+ @Nonnull final ProjectResolverContext resolverCtx,
+ @Nonnull final GradleProjectResolverExtension projectResolverChain,
+ boolean isBuildSrcProject
+ ) throws IllegalArgumentException, IllegalStateException {
+ final ProjectImportAction projectImportAction = new ProjectImportAction(resolverCtx.isPreviewMode());
+
+ final List> extraJvmArgs = new ArrayList<>();
+ final List commandLineArgs = ContainerUtil.newArrayList();
+ final Set toolingExtensionClasses = ContainerUtil.newHashSet();
+
+ for (GradleProjectResolverExtension resolverExtension = projectResolverChain; resolverExtension != null; resolverExtension =
+ resolverExtension.getNext()) {
+ // inject ProjectResolverContext into gradle project resolver extensions
+ resolverExtension.setProjectResolverContext(resolverCtx);
+ // pre-import checks
+ resolverExtension.preImportCheck();
+ // register classes of extra gradle project models required for extensions (e.g. com.android.builder.model.AndroidProject)
+ projectImportAction.addExtraProjectModelClasses(resolverExtension.getExtraProjectModelClasses());
+ // collect extra JVM arguments provided by gradle project resolver extensions
+ extraJvmArgs.addAll(resolverExtension.getExtraJvmArgs());
+ // collect extra command-line arguments
+ commandLineArgs.addAll(resolverExtension.getExtraCommandLineArgs());
+ // collect tooling extensions classes
+ toolingExtensionClasses.addAll(resolverExtension.getToolingExtensionsClasses());
+ }
+
+ final ParametersList parametersList = new ParametersList();
+ for (Pair jvmArg : extraJvmArgs) {
+ parametersList.addProperty(jvmArg.getFirst(), jvmArg.getSecond());
+ }
+
+ BuildActionExecuter buildActionExecutor = resolverCtx.getConnection().action(projectImportAction);
+
+ // TODO [vlad] remove the check
+ if (!GradleEnvironment.DISABLE_ENHANCED_TOOLING_API) {
+ File initScript = GradleExecutionHelper.generateInitScript(isBuildSrcProject, toolingExtensionClasses);
+ if (initScript != null) {
+ ContainerUtil.addAll(commandLineArgs, GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
+ }
+ }
+
+ GradleExecutionHelper.prepare(buildActionExecutor, resolverCtx.getExternalSystemTaskId(), resolverCtx.getSettings(),
+ resolverCtx.getListener(), parametersList.getParameters(), commandLineArgs, resolverCtx.getConnection()
+ );
+
+ ProjectImportAction.AllModels allModels;
+ try {
+ allModels = buildActionExecutor.run();
+ if (allModels == null) {
+ throw new IllegalStateException("Unable to get project model for the project: " + resolverCtx.getProjectPath());
+ }
+ }
+ catch (UnsupportedVersionException unsupportedVersionException) {
+ // Old gradle distribution version used (before ver. 1.8)
+ // fallback to use ModelBuilder gradle tooling API
+ Class extends IdeaProject> aClass = resolverCtx.isPreviewMode() ? BasicIdeaProject.class : IdeaProject.class;
+ ModelBuilder extends IdeaProject> modelBuilder = myHelper.getModelBuilder(
+ aClass,
+ resolverCtx.getExternalSystemTaskId(),
+ resolverCtx.getSettings(),
+ resolverCtx.getConnection(),
+ resolverCtx.getListener(),
+ parametersList.getParameters()
+ );
+
+ final IdeaProject ideaProject = modelBuilder.get();
+ allModels = new ProjectImportAction.AllModels(ideaProject);
+ }
+
+ final BuildEnvironment buildEnvironment = getBuildEnvironment(resolverCtx);
+ allModels.setBuildEnvironment(buildEnvironment);
+ resolverCtx.setModels(allModels);
+
+ // import project data
+ ProjectData projectData = projectResolverChain.createProject();
+ DataNode projectDataNode = new DataNode(ProjectKeys.PROJECT, projectData, null);
+
+ // import java project data
+ JavaProjectData javaProjectData = projectResolverChain.createJavaProjectData();
+ projectDataNode.createChild(JavaProjectData.KEY, javaProjectData);
+
+ IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
+
+ projectResolverChain.populateProjectExtraModels(ideaProject, projectDataNode);
+
+ DomainObjectSet extends IdeaModule> gradleModules = ideaProject.getModules();
+ if (gradleModules == null || gradleModules.isEmpty()) {
+ throw new IllegalStateException("No modules found for the target project: " + ideaProject);
+ }
+ final Map, IdeaModule>> moduleMap = new HashMap<>();
+
+ // import modules data
+ for (IdeaModule gradleModule : gradleModules) {
+ if (gradleModule == null) {
+ continue;
+ }
+
+ if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
+ LOG.info(String.format("Importing module data: %s", gradleModule));
+ }
+
+ final String moduleName = gradleModule.getName();
+ if (moduleName == null) {
+ throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
+ }
+
+ ModuleData moduleData = projectResolverChain.createModule(gradleModule, projectData);
+
+ Pair, IdeaModule> previouslyParsedModule = moduleMap.get(moduleName);
+ if (previouslyParsedModule != null) {
+ throw new IllegalStateException(String.format(
+ "Modules with duplicate name (%s) detected: '%s' and '%s'",
+ moduleName,
+ moduleData,
+ previouslyParsedModule
+ ));
+ }
+ DataNode moduleDataNode = projectDataNode.createChild(ProjectKeys.MODULE, moduleData);
+ moduleMap.put(moduleName, Pair.create(moduleDataNode, gradleModule));
+ }
+
+ // populate modules nodes
+ final List allTasks = ContainerUtil.newArrayList();
+ for (final Pair, IdeaModule> pair : moduleMap.values()) {
+ final DataNode moduleDataNode = pair.first;
+ final IdeaModule ideaModule = pair.second;
+ projectResolverChain.populateModuleExtraModels(ideaModule, moduleDataNode);
+ projectResolverChain.populateModuleContentRoots(ideaModule, moduleDataNode);
+ projectResolverChain.populateModuleCompileOutputSettings(ideaModule, moduleDataNode);
+ projectResolverChain.populateModuleDependencies(ideaModule, moduleDataNode, projectDataNode);
+ if (!isBuildSrcProject) {
+ final Collection moduleTasks =
+ projectResolverChain.populateModuleTasks(ideaModule, moduleDataNode, projectDataNode);
+ allTasks.addAll(moduleTasks);
+ }
+ }
+
+ // populate root project tasks
+ final Collection rootProjectTaskCandidates = projectResolverChain.filterRootProjectTasks(allTasks);
+
+ Set> rootProjectTaskCandidatesMap = new HashSet<>();
+ for (final TaskData taskData : rootProjectTaskCandidates) {
+ rootProjectTaskCandidatesMap.add(Couple.of(taskData.getName(), taskData.getDescription()));
+ }
+ for (final Couple p : rootProjectTaskCandidatesMap) {
+ projectDataNode.createChild(
+ ProjectKeys.TASK,
+ new TaskData(GradleConstants.SYSTEM_ID, p.first, projectData.getLinkedExternalProjectPath(), p.second)
+ );
+ }
+
+ // ensure unique library names
+ Collection> libraries = ExternalSystemApiUtil.getChildren(projectDataNode, ProjectKeys.LIBRARY);
+ myLibraryNamesMixer.mixNames(libraries);
+
+ return projectDataNode;
+ }
+
+ @Nullable
+ private static BuildEnvironment getBuildEnvironment(@Nonnull ProjectResolverContext resolverCtx) {
+ try {
+ return resolverCtx.getConnection().getModel(BuildEnvironment.class);
+ }
+ catch (Exception e) {
+ return null;
+ }
+ }
+
+ private void handleBuildSrcProject(
+ @Nonnull final DataNode resultProjectDataNode,
+ @Nonnull final ProjectConnectionDataNodeFunction projectConnectionDataNodeFunction
+ ) {
+
+ if (projectConnectionDataNodeFunction.myIsPreviewMode || GradleEnvironment.DISABLE_ENHANCED_TOOLING_API || !new File
+ (projectConnectionDataNodeFunction.myProjectPath).isDirectory()) {
+ return;
+ }
+
+ final DataNode buildSrcModuleDataNode = ExternalSystemApiUtil.find(
+ resultProjectDataNode,
+ ProjectKeys.MODULE,
+ node -> projectConnectionDataNodeFunction.myProjectPath.equals(node.getData().getLinkedExternalProjectPath())
+ );
+
+ // check if buildSrc project was already exposed in settings.gradle file
+ if (buildSrcModuleDataNode != null) {
+ return;
+ }
+
+ final DataNode buildSrcProjectDataDataNode = myHelper.execute(projectConnectionDataNodeFunction.myProjectPath,
+ projectConnectionDataNodeFunction.mySettings, projectConnectionDataNodeFunction
+ );
+
+ if (buildSrcProjectDataDataNode != null) {
+ final DataNode moduleDataNode = ExternalSystemApiUtil.find(buildSrcProjectDataDataNode, ProjectKeys.MODULE);
+ if (moduleDataNode != null) {
+ Collection> libraryDataNodes =
+ ExternalSystemApiUtil.findAll(buildSrcProjectDataDataNode, ProjectKeys.LIBRARY);
+ for (DataNode libraryDataNode : libraryDataNodes) {
+ resultProjectDataNode.createChild(libraryDataNode.getKey(), libraryDataNode.getData());
+ }
+
+ final DataNode newModuleDataNode =
+ resultProjectDataNode.createChild(ProjectKeys.MODULE, moduleDataNode.getData());
+ for (DataNode node : moduleDataNode.getChildren()) {
+ newModuleDataNode.createChild(node.getKey(), node.getData());
+ }
+ }
+ }
+ }
+
+ private class ProjectConnectionDataNodeFunction implements Function> {
+ @Nonnull
+ private final ExternalSystemTaskId myId;
+ @Nonnull
+ private final String myProjectPath;
+ @Nullable
+ private final GradleExecutionSettings mySettings;
+ @Nonnull
+ private final ExternalSystemTaskNotificationListener myListener;
+ private final boolean myIsPreviewMode;
+ @Nonnull
+ private final GradleProjectResolverExtension myProjectResolverChain;
+ private final boolean myIsBuildSrcProject;
+
+ public ProjectConnectionDataNodeFunction(
+ @Nonnull ExternalSystemTaskId id,
+ @Nonnull String projectPath,
+ @Nullable GradleExecutionSettings settings,
+ @Nonnull ExternalSystemTaskNotificationListener listener,
+ boolean isPreviewMode,
+ @Nonnull GradleProjectResolverExtension projectResolverChain,
+ boolean isBuildSrcProject
+ ) {
+ myId = id;
+ myProjectPath = projectPath;
+ mySettings = settings;
+ myListener = listener;
+ myIsPreviewMode = isPreviewMode;
+ myProjectResolverChain = projectResolverChain;
+ myIsBuildSrcProject = isBuildSrcProject;
+ }
+
+ @Override
+ public DataNode apply(ProjectConnection connection) {
+ try {
+ return doResolveProjectInfo(
+ new ProjectResolverContext(
+ myId,
+ myProjectPath,
+ mySettings,
+ connection,
+ myListener,
+ myIsPreviewMode
+ ),
+ myProjectResolverChain,
+ myIsBuildSrcProject
+ );
+ }
+ catch (RuntimeException e) {
+ LOG.info("Gradle project resolve error", e);
+ throw myProjectResolverChain.getUserFriendlyError(e, myProjectPath, null);
+ }
+ }
+ }
+
+ @Nonnull
+ public static GradleProjectResolverExtension createProjectResolverChain(@Nullable final GradleExecutionSettings settings) {
+ GradleProjectResolverExtension projectResolverChain;
+ if (settings != null) {
+ List> extensionClasses = settings.getResolverExtensions();
+
+ Deque extensions = new ArrayDeque<>();
+ for (ClassHolder extends GradleProjectResolverExtension> holder : extensionClasses) {
+ final GradleProjectResolverExtension extension;
+ try {
+ extension = holder.getTargetClass().newInstance();
+ }
+ catch (Throwable e) {
+ throw new IllegalArgumentException(
+ String.format(
+ "Can't instantiate project resolve extension for class '%s'",
+ holder.getTargetClassName()
+ ),
+ e
+ );
+ }
+ final GradleProjectResolverExtension previous = extensions.peekLast();
+ if (previous != null) {
+ previous.setNext(extension);
+ if (previous.getNext() != extension) {
+ throw new AssertionError(
+ "Illegal next resolver got, current resolver class is " + previous.getClass().getName()
+ );
+ }
+ }
+ extensions.add(extension);
+ }
+ projectResolverChain = extensions.peekFirst();
+
+ GradleProjectResolverExtension resolverExtension = projectResolverChain;
+ assert resolverExtension != null;
+ while (resolverExtension.getNext() != null) {
+ resolverExtension = resolverExtension.getNext();
+ }
+ if (!(resolverExtension instanceof BaseGradleProjectResolverExtension)) {
+ throw new AssertionError("Illegal last resolver got of class " + resolverExtension.getClass().getName());
+ }
+ }
+ else {
+ projectResolverChain = new BaseGradleProjectResolverExtension();
+ }
+
+ return projectResolverChain;
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolverUtil.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolverUtil.java
index 301fd31..7b28aed 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolverUtil.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleProjectResolverUtil.java
@@ -9,23 +9,22 @@
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
-public class GradleProjectResolverUtil
-{
- public static boolean linkProjectLibrary(@Nullable DataNode ideProject, @Nonnull final LibraryData library)
- {
- if(ideProject == null)
- {
- return false;
- }
+public class GradleProjectResolverUtil {
+ public static boolean linkProjectLibrary(@Nullable DataNode ideProject, @Nonnull final LibraryData library) {
+ if (ideProject == null) {
+ return false;
+ }
- String libraryName = library.getExternalName();
- DataNode libraryData = ExternalSystemApiUtil.find(ideProject, ProjectKeys.LIBRARY, node -> libraryName.equals(node.getData()
- .getExternalName()));
- if(libraryData == null)
- {
- ideProject.createChild(ProjectKeys.LIBRARY, library);
- return true;
- }
- return libraryData.getData().equals(library);
- }
+ String libraryName = library.getExternalName();
+ DataNode libraryData = ExternalSystemApiUtil.find(
+ ideProject,
+ ProjectKeys.LIBRARY,
+ node -> libraryName.equals(node.getData().getExternalName())
+ );
+ if (libraryData == null) {
+ ideProject.createChild(ProjectKeys.LIBRARY, library);
+ return true;
+ }
+ return libraryData.getData().equals(library);
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java
index f9bc56e..bdae184 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java
@@ -55,73 +55,74 @@
*/
@ExtensionImpl
public class GradleStartupActivity implements PostStartupActivity {
- private static final String SHOW_UNLINKED_GRADLE_POPUP = "show.inlinked.gradle.project.popup";
- private static final String IMPORT_EVENT_DESCRIPTION = "import";
- private static final String DO_NOT_SHOW_EVENT_DESCRIPTION = "do.not.show";
+ private static final String SHOW_UNLINKED_GRADLE_POPUP = "show.inlinked.gradle.project.popup";
+ private static final String IMPORT_EVENT_DESCRIPTION = "import";
+ private static final String DO_NOT_SHOW_EVENT_DESCRIPTION = "do.not.show";
- @Override
- public void runActivity(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
- configureBuildClasspath(project);
+ @Override
+ public void runActivity(@Nonnull Project project, @Nonnull UIAccess uiAccess) {
+ configureBuildClasspath(project);
- showNotificationForUnlinkedGradleProject(project);
- }
-
- private static void configureBuildClasspath(@Nonnull final Project project) {
- GradleBuildClasspathManager.getInstance(project).reload();
- }
+ showNotificationForUnlinkedGradleProject(project);
+ }
- private static void showNotificationForUnlinkedGradleProject(@Nonnull final Project project) {
- if (!PropertiesComponent.getInstance(project).getBoolean(SHOW_UNLINKED_GRADLE_POPUP, true)
- || !GradleSettings.getInstance(project).getLinkedProjectsSettings().isEmpty()
- || project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) == Boolean.TRUE
- || project.getBaseDir() == null) {
- return;
+ private static void configureBuildClasspath(@Nonnull final Project project) {
+ GradleBuildClasspathManager.getInstance(project).reload();
}
- File baseDir = VfsUtilCore.virtualToIoFile(project.getBaseDir());
- final File[] files = baseDir.listFiles(new FilenameFilter() {
- @Override
- public boolean accept(File dir, String name) {
- return FileUtil.namesEqual(GradleConstants.DEFAULT_SCRIPT_NAME, name);
- }
- });
+ private static void showNotificationForUnlinkedGradleProject(@Nonnull final Project project) {
+ if (!PropertiesComponent.getInstance(project).getBoolean(SHOW_UNLINKED_GRADLE_POPUP, true)
+ || !GradleSettings.getInstance(project).getLinkedProjectsSettings().isEmpty()
+ || project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) == Boolean.TRUE
+ || project.getBaseDir() == null) {
+ return;
+ }
+
+ File baseDir = VfsUtilCore.virtualToIoFile(project.getBaseDir());
+ final File[] files = baseDir.listFiles((dir, name) -> FileUtil.namesEqual(GradleConstants.DEFAULT_SCRIPT_NAME, name));
- if (files != null && files.length != 0) {
- String message = String.format("%s \n%s",
- GradleBundle.message("gradle.notifications.unlinked.project.found.msg", IMPORT_EVENT_DESCRIPTION),
- GradleBundle.message("gradle.notifications.do.not.show", DO_NOT_SHOW_EVENT_DESCRIPTION));
+ if (files != null && files.length != 0) {
+ String message = String.format(
+ "%s \n%s",
+ GradleBundle.message("gradle.notifications.unlinked.project.found.msg", IMPORT_EVENT_DESCRIPTION),
+ GradleBundle.message("gradle.notifications.do.not.show", DO_NOT_SHOW_EVENT_DESCRIPTION)
+ );
- GradleNotification.getInstance(project).showBalloon(
- GradleBundle.message("gradle.notifications.unlinked.project.found.title"),
- message, NotificationType.INFORMATION, new NotificationListener.Adapter() {
- @Override
- @RequiredUIAccess
- protected void hyperlinkActivated(@Nonnull Notification notification, @Nonnull HyperlinkEvent e) {
- if (IMPORT_EVENT_DESCRIPTION.equals(e.getDescription())) {
- VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(files[0]);
- assert vFile != null;
- AsyncResult>> result = AsyncResult.undefined();
- ModuleImportProcessor.showImportChooser(project,
- vFile,
- Collections.singletonList(GradleModuleImportProvider.getInstance()),
- result);
+ GradleNotification.getInstance(project).showBalloon(
+ GradleBundle.message("gradle.notifications.unlinked.project.found.title"),
+ message,
+ NotificationType.INFORMATION,
+ new NotificationListener.Adapter() {
+ @Override
+ @RequiredUIAccess
+ protected void hyperlinkActivated(@Nonnull Notification notification, @Nonnull HyperlinkEvent e) {
+ if (IMPORT_EVENT_DESCRIPTION.equals(e.getDescription())) {
+ VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(files[0]);
+ assert vFile != null;
+ AsyncResult>> result =
+ AsyncResult.undefined();
+ ModuleImportProcessor.showImportChooser(
+ project,
+ vFile,
+ Collections.singletonList(GradleModuleImportProvider.getInstance()),
+ result
+ );
- result.doWhenDone(pair -> {
- ModuleImportContext context = pair.getFirst();
- ModuleImportProvider provider = pair.getSecond();
+ result.doWhenDone(pair -> {
+ ModuleImportContext context = pair.getFirst();
+ ModuleImportProvider provider = pair.getSecond();
- ModifiableModuleModel modifiableModel = ModuleManager.getInstance(project).getModifiableModel();
- provider.process(context, project, modifiableModel, module -> {
- });
- WriteAction.runAndWait(modifiableModel::commit);
- });
- }
- else if (DO_NOT_SHOW_EVENT_DESCRIPTION.equals(e.getDescription())) {
- PropertiesComponent.getInstance(project).setValue(SHOW_UNLINKED_GRADLE_POPUP, Boolean.FALSE.toString());
- }
- }
+ ModifiableModuleModel modifiableModel = ModuleManager.getInstance(project).getModifiableModel();
+ provider.process(context, project, modifiableModel, module -> {});
+ WriteAction.runAndWait(modifiableModel::commit);
+ });
+ }
+ else if (DO_NOT_SHOW_EVENT_DESCRIPTION.equals(e.getDescription())) {
+ PropertiesComponent.getInstance(project).setValue(SHOW_UNLINKED_GRADLE_POPUP, Boolean.FALSE.toString());
+ }
+ }
+ }
+ );
}
- );
}
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/OutputWrapper.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/OutputWrapper.java
index 7749dec..4978860 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/OutputWrapper.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/OutputWrapper.java
@@ -13,62 +13,62 @@
* @since 23.05.13 15:50
*/
public class OutputWrapper extends OutputStream {
+ @Nonnull
+ private final ExternalSystemTaskNotificationListener myListener;
+ @Nonnull
+ private final ExternalSystemTaskId myTaskId;
- @Nonnull
- private final ExternalSystemTaskNotificationListener myListener;
- @Nonnull
- private final ExternalSystemTaskId myTaskId;
+ @Nullable
+ private StringBuilder myBuffer;
- @Nullable private StringBuilder myBuffer;
+ private final boolean myStdOut;
- private final boolean myStdOut;
-
- public OutputWrapper(@Nonnull ExternalSystemTaskNotificationListener listener, @Nonnull ExternalSystemTaskId taskId, boolean stdOut) {
- myListener = listener;
- myTaskId = taskId;
- myStdOut = stdOut;
- }
-
- @Override
- public void write(int b) throws IOException {
- if (myBuffer == null) {
- myBuffer = new StringBuilder();
- }
- char c = (char)b;
- myBuffer.append(Character.toString(c));
- if (c == '\n') {
- doFlush();
+ public OutputWrapper(@Nonnull ExternalSystemTaskNotificationListener listener, @Nonnull ExternalSystemTaskId taskId, boolean stdOut) {
+ myListener = listener;
+ myTaskId = taskId;
+ myStdOut = stdOut;
}
- }
- @Override
- public void write(byte[] b, int off, int len) throws IOException {
- int start = off;
- int maxOffset = off + len;
- for (int i = off; i < maxOffset; i++) {
- if (b[i] == '\n') {
+ @Override
+ public void write(int b) throws IOException {
if (myBuffer == null) {
- myBuffer = new StringBuilder();
+ myBuffer = new StringBuilder();
+ }
+ char c = (char)b;
+ myBuffer.append(Character.toString(c));
+ if (c == '\n') {
+ doFlush();
}
- myBuffer.append(new String(b, start, i - start + 1));
- doFlush();
- start = i + 1;
- }
}
- if (start < maxOffset) {
- if (myBuffer == null) {
- myBuffer = new StringBuilder();
- }
- myBuffer.append(new String(b, start, maxOffset - start));
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException {
+ int start = off;
+ int maxOffset = off + len;
+ for (int i = off; i < maxOffset; i++) {
+ if (b[i] == '\n') {
+ if (myBuffer == null) {
+ myBuffer = new StringBuilder();
+ }
+ myBuffer.append(new String(b, start, i - start + 1));
+ doFlush();
+ start = i + 1;
+ }
+ }
+
+ if (start < maxOffset) {
+ if (myBuffer == null) {
+ myBuffer = new StringBuilder();
+ }
+ myBuffer.append(new String(b, start, maxOffset - start));
+ }
}
- }
- private void doFlush() {
- if (myBuffer == null) {
- return;
+ private void doFlush() {
+ if (myBuffer == null) {
+ return;
+ }
+ myListener.onTaskOutput(myTaskId, myBuffer.toString(), myStdOut);
+ myBuffer.setLength(0);
}
- myListener.onTaskOutput(myTaskId, myBuffer.toString(), myStdOut);
- myBuffer.setLength(0);
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java
index 76eb0ab..fac319d 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java
@@ -52,120 +52,114 @@
@ExtensionImpl
@Order(ExternalSystemConstants.UNORDERED)
public class BuildClasspathModuleGradleDataService implements ProjectDataService {
- @Nonnull
- @Override
- public Key getTargetDataKey() {
- return BuildScriptClasspathData.KEY;
- }
-
- @Override
- public void importData(@Nonnull final Collection> toImport, @Nonnull final Project project,
- boolean synchronous) {
- if (toImport.isEmpty()) {
- return;
+ @Nonnull
+ @Override
+ public Key getTargetDataKey() {
+ return BuildScriptClasspathData.KEY;
}
- if (!project.isInitialized()) {
- return;
- }
-
- final GradleInstallationManager gradleInstallationManager = ServiceManager.getService(GradleInstallationManager.class);
-
- ExternalSystemManager, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
- assert manager != null;
- AbstractExternalSystemLocalSettings localSettings = manager.getLocalSettingsProvider().apply(project);
-
- Map> externalProjectGradleSdkLibs = FactoryMap.create(externalProjectPath ->
- {
- GradleProjectSettings settings =
- GradleSettings.getInstance(
- project)
- .getLinkedProjectSettings(
- externalProjectPath);
- if (settings == null || settings.getDistributionType() == null) {
- return null;
- }
-
- final Set
- gradleSdkLibraries =
- new LinkedHashSet<>();
- File gradleHome =
- gradleInstallationManager.getGradleHome(
- settings.getDistributionType(),
- externalProjectPath,
- settings.getGradleHome());
- if (gradleHome != null && gradleHome
- .isDirectory()) {
-
- final Collection
- libraries =
- gradleInstallationManager.getClassRoots(
- project,
- externalProjectPath);
- if (libraries != null) {
- for (File library : libraries) {
- gradleSdkLibraries.add(
- FileUtil.toCanonicalPath(
- library.getPath()));
- }
- }
- }
- return gradleSdkLibraries;
- });
-
- for (final DataNode node : toImport) {
- if (GradleConstants.SYSTEM_ID.equals(node.getData().getOwner())) {
- DataNode projectDataNode = ExternalSystemApiUtil.findParent(node, ProjectKeys.PROJECT);
- assert projectDataNode != null;
-
- String linkedExternalProjectPath = projectDataNode.getData().getLinkedExternalProjectPath();
- DataNode moduleDataNode = ExternalSystemApiUtil.findParent(node, ProjectKeys.MODULE);
- if (moduleDataNode == null) {
- continue;
- }
- String externalModulePath = moduleDataNode.getData().getLinkedExternalProjectPath();
- GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedExternalProjectPath);
- if (settings == null || settings.getDistributionType() == null) {
- continue;
+ @Override
+ public void importData(
+ @Nonnull final Collection> toImport,
+ @Nonnull final Project project,
+ boolean synchronous
+ ) {
+ if (toImport.isEmpty()) {
+ return;
}
-
- final Set buildClasspath = ContainerUtil.newLinkedHashSet();
- BuildScriptClasspathData buildScriptClasspathData = node.getData();
- for (BuildScriptClasspathData.ClasspathEntry classpathEntry : buildScriptClasspathData.getClasspathEntries()) {
- for (String path : classpathEntry.getSourcesFile()) {
- buildClasspath.add(FileUtil.toCanonicalPath(path));
- }
-
- for (String path : classpathEntry.getClassesFile()) {
- buildClasspath.add(FileUtil.toCanonicalPath(path));
- }
+ if (!project.isInitialized()) {
+ return;
}
- ExternalProjectBuildClasspathPojo projectBuildClasspathPojo = localSettings.getProjectBuildClasspath().get
- (linkedExternalProjectPath);
- if (projectBuildClasspathPojo == null) {
- projectBuildClasspathPojo = new ExternalProjectBuildClasspathPojo(moduleDataNode.getData().getExternalName(),
- ContainerUtil.newArrayList(),
- ContainerUtil.newHashMap());
- localSettings.getProjectBuildClasspath().put(linkedExternalProjectPath, projectBuildClasspathPojo);
+ final GradleInstallationManager gradleInstallationManager = ServiceManager.getService(GradleInstallationManager.class);
+
+ ExternalSystemManager, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID);
+ assert manager != null;
+ AbstractExternalSystemLocalSettings localSettings = manager.getLocalSettingsProvider().apply(project);
+
+ Map> externalProjectGradleSdkLibs = FactoryMap.create(externalProjectPath ->
+ {
+ GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(externalProjectPath);
+ if (settings == null || settings.getDistributionType() == null) {
+ return null;
+ }
+
+ final Set gradleSdkLibraries = new LinkedHashSet<>();
+ File gradleHome = gradleInstallationManager.getGradleHome(
+ settings.getDistributionType(),
+ externalProjectPath,
+ settings.getGradleHome()
+ );
+ if (gradleHome != null && gradleHome.isDirectory()) {
+ final Collection libraries = gradleInstallationManager.getClassRoots(project, externalProjectPath);
+ if (libraries != null) {
+ for (File library : libraries) {
+ gradleSdkLibraries.add(FileUtil.toCanonicalPath(library.getPath()));
+ }
+ }
+ }
+ return gradleSdkLibraries;
+ });
+
+ for (final DataNode node : toImport) {
+ if (GradleConstants.SYSTEM_ID.equals(node.getData().getOwner())) {
+ DataNode projectDataNode = ExternalSystemApiUtil.findParent(node, ProjectKeys.PROJECT);
+ assert projectDataNode != null;
+
+ String linkedExternalProjectPath = projectDataNode.getData().getLinkedExternalProjectPath();
+ DataNode moduleDataNode = ExternalSystemApiUtil.findParent(node, ProjectKeys.MODULE);
+ if (moduleDataNode == null) {
+ continue;
+ }
+
+ String externalModulePath = moduleDataNode.getData().getLinkedExternalProjectPath();
+ GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedExternalProjectPath);
+ if (settings == null || settings.getDistributionType() == null) {
+ continue;
+ }
+
+ final Set buildClasspath = ContainerUtil.newLinkedHashSet();
+ BuildScriptClasspathData buildScriptClasspathData = node.getData();
+ for (BuildScriptClasspathData.ClasspathEntry classpathEntry : buildScriptClasspathData.getClasspathEntries()) {
+ for (String path : classpathEntry.getSourcesFile()) {
+ buildClasspath.add(FileUtil.toCanonicalPath(path));
+ }
+
+ for (String path : classpathEntry.getClassesFile()) {
+ buildClasspath.add(FileUtil.toCanonicalPath(path));
+ }
+ }
+
+ ExternalProjectBuildClasspathPojo projectBuildClasspathPojo =
+ localSettings.getProjectBuildClasspath().get(linkedExternalProjectPath);
+ if (projectBuildClasspathPojo == null) {
+ projectBuildClasspathPojo = new ExternalProjectBuildClasspathPojo(
+ moduleDataNode.getData().getExternalName(),
+ ContainerUtil.newArrayList(),
+ ContainerUtil.newHashMap()
+ );
+ localSettings.getProjectBuildClasspath().put(linkedExternalProjectPath, projectBuildClasspathPojo);
+ }
+
+ List projectBuildClasspath =
+ ContainerUtil.newArrayList(externalProjectGradleSdkLibs.get(linkedExternalProjectPath));
+ // add main java root of buildSrc project
+ projectBuildClasspath.add(linkedExternalProjectPath + "/buildSrc/src/main/java");
+ // add main groovy root of buildSrc project
+ projectBuildClasspath.add(linkedExternalProjectPath + "/buildSrc/src/main/groovy");
+
+ projectBuildClasspathPojo.setProjectBuildClasspath(projectBuildClasspath);
+ projectBuildClasspathPojo.getModulesBuildClasspath().put(
+ externalModulePath,
+ new ExternalModuleBuildClasspathPojo(externalModulePath, ContainerUtil.newArrayList(buildClasspath))
+ );
+ }
}
- List projectBuildClasspath = ContainerUtil.newArrayList(externalProjectGradleSdkLibs.get(linkedExternalProjectPath));
- // add main java root of buildSrc project
- projectBuildClasspath.add(linkedExternalProjectPath + "/buildSrc/src/main/java");
- // add main groovy root of buildSrc project
- projectBuildClasspath.add(linkedExternalProjectPath + "/buildSrc/src/main/groovy");
-
- projectBuildClasspathPojo.setProjectBuildClasspath(projectBuildClasspath);
- projectBuildClasspathPojo.getModulesBuildClasspath().put(externalModulePath, new ExternalModuleBuildClasspathPojo
- (externalModulePath, ContainerUtil.newArrayList(buildClasspath)));
- }
+ GradleBuildClasspathManager.getInstance(project).reload();
}
- GradleBuildClasspathManager.getInstance(project).reload();
- }
-
- @Override
- public void removeData(@Nonnull Collection extends Module> toRemove, @Nonnull Project project, boolean synchronous) {
- }
+ @Override
+ public void removeData(@Nonnull Collection extends Module> toRemove, @Nonnull Project project, boolean synchronous) {
+ }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectDataService.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectDataService.java
index 7ee250c..416a1c0 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectDataService.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectDataService.java
@@ -62,178 +62,201 @@
*/
@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
public class ExternalProjectDataService implements ProjectDataService {
- private static final Logger LOG = Logger.getInstance(ExternalProjectDataService.class);
-
- @Nonnull
- public static final Key KEY = Key.create(ExternalProject.class, ProjectKeys.TASK.getProcessingWeight() + 1);
-
- @Nonnull
- private final Map, ExternalProject> myExternalRootProjects;
-
- @Nonnull
- private ProjectDataManager myProjectDataManager;
-
- public ExternalProjectDataService(@Nonnull ProjectDataManager projectDataManager) {
- myProjectDataManager = projectDataManager;
- myExternalRootProjects = ConcurrentFactoryMap.createMap(key -> new ExternalProjectSerializer().load(key.first, key.second));
- }
-
- @Nonnull
- @Override
- public Key getTargetDataKey() {
- return KEY;
- }
-
- public void importData(@Nonnull final Collection> toImport,
- @Nonnull final Project project,
- final boolean synchronous) {
- if (toImport.size() != 1) {
- throw new IllegalArgumentException(String.format("Expected to get a single external project but got %d: %s",
- toImport.size(),
- toImport));
+ private static final Logger LOG = Logger.getInstance(ExternalProjectDataService.class);
+
+ @Nonnull
+ public static final Key KEY =
+ Key.create(ExternalProject.class, ProjectKeys.TASK.getProcessingWeight() + 1);
+
+ @Nonnull
+ private final Map, ExternalProject> myExternalRootProjects;
+
+ @Nonnull
+ private ProjectDataManager myProjectDataManager;
+
+ public ExternalProjectDataService(@Nonnull ProjectDataManager projectDataManager) {
+ myProjectDataManager = projectDataManager;
+ myExternalRootProjects = ConcurrentFactoryMap.createMap(key -> new ExternalProjectSerializer().load(key.first, key.second));
}
- saveExternalProject(toImport.iterator().next().getData());
- }
-
- @Override
- public void removeData(@Nonnull final Collection extends Project> modules, @Nonnull Project project, boolean synchronous) {
- }
-
- @Nullable
- public ExternalProject getOrImportRootExternalProject(@Nonnull Project project,
- @Nonnull ProjectSystemId systemId,
- @Nonnull File projectRootDir) {
- final ExternalProject externalProject = getRootExternalProject(systemId, projectRootDir);
- return externalProject != null ? externalProject : importExternalProject(project, systemId, projectRootDir);
- }
-
- @Nullable
- private ExternalProject importExternalProject(@Nonnull final Project project, @Nonnull final ProjectSystemId projectSystemId,
- @Nonnull final File projectRootDir) {
- final Boolean result = UIUtil.invokeAndWaitIfNeeded(new Computable() {
- @Override
- public Boolean compute() {
- final Ref result = new Ref(false);
- if (project.isDisposed()) {
- return false;
- }
- final String linkedProjectPath = FileUtil.toCanonicalPath(projectRootDir.getPath());
- final ExternalProjectSettings projectSettings = ExternalSystemApiUtil.getSettings(project, projectSystemId).getLinkedProjectSettings
- (linkedProjectPath);
- if (projectSettings == null) {
- LOG.warn("Unable to get project settings for project path: " + linkedProjectPath);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Available projects paths: " + ContainerUtil.map(ExternalSystemApiUtil.getSettings(project,
- projectSystemId)
- .getLinkedProjectsSettings(),
- (Function)settings -> settings.getExternalProjectPath()));
- }
- return false;
- }
+ @Nonnull
+ @Override
+ public Key getTargetDataKey() {
+ return KEY;
+ }
- final File projectFile = new File(linkedProjectPath);
- final String projectName;
- if (projectFile.isFile()) {
- projectName = projectFile.getParentFile().getName();
- }
- else {
- projectName = projectFile.getName();
+ public void importData(
+ @Nonnull final Collection> toImport,
+ @Nonnull final Project project,
+ final boolean synchronous
+ ) {
+ if (toImport.size() != 1) {
+ throw new IllegalArgumentException(String.format(
+ "Expected to get a single external project but got %d: %s",
+ toImport.size(),
+ toImport
+ ));
}
+ saveExternalProject(toImport.iterator().next().getData());
+ }
- // ask a user for the project import if auto-import is disabled
- if (!projectSettings.isUseAutoImport()) {
- String message = String.format("Project '%s' require synchronization with %s configuration. \nImport the project?", projectName,
- projectSystemId.getReadableName());
- int returnValue = Messages.showOkCancelDialog(message, "Import Project", CommonBundle.getOkButtonText(),
- CommonBundle.getCancelButtonText(), Messages.getQuestionIcon());
- if (returnValue != Messages.OK) {
- return false;
- }
- }
+ @Override
+ public void removeData(@Nonnull final Collection extends Project> modules, @Nonnull Project project, boolean synchronous) {
+ }
+
+ @Nullable
+ public ExternalProject getOrImportRootExternalProject(
+ @Nonnull Project project,
+ @Nonnull ProjectSystemId systemId,
+ @Nonnull File projectRootDir
+ ) {
+ final ExternalProject externalProject = getRootExternalProject(systemId, projectRootDir);
+ return externalProject != null ? externalProject : importExternalProject(project, systemId, projectRootDir);
+ }
- final String title = ExternalSystemBundle.message("progress.import.text", linkedProjectPath, projectSystemId.getReadableName());
- new Task.Modal(project, title, false) {
- @Override
- public void run(@Nonnull ProgressIndicator indicator) {
+ @Nullable
+ private ExternalProject importExternalProject(
+ @Nonnull final Project project,
+ @Nonnull final ProjectSystemId projectSystemId,
+ @Nonnull final File projectRootDir
+ ) {
+ final Boolean result = UIUtil.invokeAndWaitIfNeeded(() -> {
+ final Ref result1 = new Ref<>(false);
if (project.isDisposed()) {
- return;
+ return false;
}
- ExternalSystemNotificationManager.getInstance(project).clearNotifications(null, NotificationSource.PROJECT_SYNC,
- projectSystemId);
- ExternalSystemResolveProjectTask task = new ExternalSystemResolveProjectTask(projectSystemId, project, linkedProjectPath,
- false);
- task.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
- if (project.isDisposed()) {
- return;
+ final String linkedProjectPath = FileUtil.toCanonicalPath(projectRootDir.getPath());
+ final ExternalProjectSettings projectSettings =
+ ExternalSystemApiUtil.getSettings(project, projectSystemId).getLinkedProjectSettings(linkedProjectPath);
+ if (projectSettings == null) {
+ LOG.warn("Unable to get project settings for project path: " + linkedProjectPath);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Available projects paths: " + ContainerUtil.map(
+ ExternalSystemApiUtil.getSettings(project, projectSystemId).getLinkedProjectsSettings(),
+ (Function)settings -> settings.getExternalProjectPath()
+ ));
+ }
+ return false;
}
- final Throwable error = task.getError();
- if (error != null) {
- ExternalSystemNotificationManager.getInstance(project).processExternalProjectRefreshError(error, projectName,
- projectSystemId);
- return;
+ final File projectFile = new File(linkedProjectPath);
+ final String projectName;
+ if (projectFile.isFile()) {
+ projectName = projectFile.getParentFile().getName();
}
- final DataNode projectDataDataNode = task.getExternalProject();
- if (projectDataDataNode == null) {
- return;
+ else {
+ projectName = projectFile.getName();
}
- final Collection> nodes = ExternalSystemApiUtil.findAll(projectDataDataNode, KEY);
- if (nodes.size() != 1) {
- throw new IllegalArgumentException(String.format("Expected to get a single external project but got %d: %s",
- nodes.size(), nodes));
+ // ask a user for the project import if auto-import is disabled
+ if (!projectSettings.isUseAutoImport()) {
+ String message = String.format(
+ "Project '%s' require synchronization with %s configuration. \nImport the project?", projectName,
+ projectSystemId.getReadableName()
+ );
+ int returnValue = Messages.showOkCancelDialog(
+ message,
+ "Import Project",
+ CommonBundle.getOkButtonText(),
+ CommonBundle.getCancelButtonText(),
+ Messages.getQuestionIcon()
+ );
+ if (returnValue != Messages.OK) {
+ return false;
+ }
}
- ProjectRootManager.getInstance((Project)myProject)
- .mergeRootsChangesDuring(() -> myProjectDataManager.importData(KEY, nodes, project, true));
+ final String title =
+ ExternalSystemBundle.message("progress.import.text", linkedProjectPath, projectSystemId.getReadableName());
+ new Task.Modal(project, title, false) {
+ @Override
+ public void run(@Nonnull ProgressIndicator indicator) {
+ if (project.isDisposed()) {
+ return;
+ }
+
+ ExternalSystemNotificationManager.getInstance(project).clearNotifications(
+ null,
+ NotificationSource.PROJECT_SYNC,
+ projectSystemId
+ );
+ ExternalSystemResolveProjectTask task =
+ new ExternalSystemResolveProjectTask(projectSystemId, project, linkedProjectPath, false);
+ task.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
+ if (project.isDisposed()) {
+ return;
+ }
- result.set(true);
- }
- }.queue();
+ final Throwable error = task.getError();
+ if (error != null) {
+ ExternalSystemNotificationManager.getInstance(project)
+ .processExternalProjectRefreshError(error, projectName, projectSystemId);
+ return;
+ }
+ final DataNode projectDataDataNode = task.getExternalProject();
+ if (projectDataDataNode == null) {
+ return;
+ }
- return result.get();
- }
- });
+ final Collection> nodes = ExternalSystemApiUtil.findAll(projectDataDataNode, KEY);
+ if (nodes.size() != 1) {
+ throw new IllegalArgumentException(String.format(
+ "Expected to get a single external project but got %d: %s",
+ nodes.size(),
+ nodes
+ ));
+ }
- return result ? getRootExternalProject(projectSystemId, projectRootDir) : null;
- }
+ ProjectRootManager.getInstance((Project)myProject)
+ .mergeRootsChangesDuring(() -> myProjectDataManager.importData(KEY, nodes, project, true));
- @Nullable
- public ExternalProject getRootExternalProject(@Nonnull ProjectSystemId systemId, @Nonnull File projectRootDir) {
- return myExternalRootProjects.get(Pair.create(systemId, projectRootDir));
- }
+ result1.set(true);
+ }
+ }.queue();
- public void saveExternalProject(@Nonnull ExternalProject externalProject) {
- DefaultExternalProject value = new DefaultExternalProject(externalProject);
+ return result1.get();
+ });
- myExternalRootProjects.put(Pair.create(new ProjectSystemId(externalProject.getExternalSystemId()), externalProject.getProjectDir()),
- value);
+ return result ? getRootExternalProject(projectSystemId, projectRootDir) : null;
+ }
+
+ @Nullable
+ public ExternalProject getRootExternalProject(@Nonnull ProjectSystemId systemId, @Nonnull File projectRootDir) {
+ return myExternalRootProjects.get(Pair.create(systemId, projectRootDir));
+ }
- new ExternalProjectSerializer().save(value);
- }
+ public void saveExternalProject(@Nonnull ExternalProject externalProject) {
+ DefaultExternalProject value = new DefaultExternalProject(externalProject);
- @Nullable
- public ExternalProject findExternalProject(@Nonnull ExternalProject parentProject, @Nonnull Module module) {
- String externalProjectId = ExternalSystemApiUtil.getExternalProjectId(module);
- return externalProjectId != null ? findExternalProject(parentProject, externalProjectId) : null;
- }
+ myExternalRootProjects.put(
+ Pair.create(new ProjectSystemId(externalProject.getExternalSystemId()), externalProject.getProjectDir()),
+ value
+ );
- @Nullable
- private static ExternalProject findExternalProject(@Nonnull ExternalProject parentProject, @Nonnull String externalProjectId) {
- if (parentProject.getQName().equals(externalProjectId)) {
- return parentProject;
+ new ExternalProjectSerializer().save(value);
}
- if (parentProject.getChildProjects().containsKey(externalProjectId)) {
- return parentProject.getChildProjects().get(externalProjectId);
+
+ @Nullable
+ public ExternalProject findExternalProject(@Nonnull ExternalProject parentProject, @Nonnull Module module) {
+ String externalProjectId = ExternalSystemApiUtil.getExternalProjectId(module);
+ return externalProjectId != null ? findExternalProject(parentProject, externalProjectId) : null;
}
- for (ExternalProject externalProject : parentProject.getChildProjects().values()) {
- final ExternalProject project = findExternalProject(externalProject, externalProjectId);
- if (project != null) {
- return project;
- }
+
+ @Nullable
+ private static ExternalProject findExternalProject(@Nonnull ExternalProject parentProject, @Nonnull String externalProjectId) {
+ if (parentProject.getQName().equals(externalProjectId)) {
+ return parentProject;
+ }
+ if (parentProject.getChildProjects().containsKey(externalProjectId)) {
+ return parentProject.getChildProjects().get(externalProjectId);
+ }
+ for (ExternalProject externalProject : parentProject.getChildProjects().values()) {
+ final ExternalProject project = findExternalProject(externalProject, externalProjectId);
+ if (project != null) {
+ return project;
+ }
+ }
+ return null;
}
- return null;
- }
}
diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectSerializer.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectSerializer.java
index 521812c..bfac51e 100644
--- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectSerializer.java
+++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/project/data/ExternalProjectSerializer.java
@@ -45,186 +45,199 @@
* @since 7/15/2014
*/
public class ExternalProjectSerializer {
- private static final Logger LOG = Logger.getInstance(ExternalProjectSerializer.class);
-
- private final Kryo myKryo;
-
- public ExternalProjectSerializer() {
- myKryo = new Kryo() {
- @Override
- public T newInstance(Class type) {
- LOG.error("Serializing default type: " + type);
- return super.newInstance(type);
- }
- };
- configureKryo();
- }
-
- private void configureKryo() {
- myKryo.setAutoReset(true);
-
- myKryo.setRegistrationRequired(true);
- Log.set(Log.LEVEL_WARN);
-
- myKryo.register(ArrayList.class, new CollectionSerializer() {
- @Override
- protected Collection create(Kryo kryo, Input input, Class type) {
- return new ArrayList();
- }
- });
- myKryo.register(HashMap.class, new MapSerializer() {
- @Override
- protected Map create(Kryo kryo, Input input, Class type) {
- return new HashMap();
- }
- });
- myKryo.register(HashSet.class, new CollectionSerializer() {
- @Override
- protected Collection create(Kryo kryo, Input input, Class type) {
- return new HashSet();
- }
- });
-
- myKryo.register(File.class, new FileSerializer());
- myKryo.register(DefaultExternalProject.class, new FieldSerializer(myKryo, DefaultExternalProject.class) {
- @Override
- protected DefaultExternalProject create(Kryo kryo, Input input, Class type) {
- return new DefaultExternalProject();
- }
- });
-
- myKryo.register(DefaultExternalTask.class, new FieldSerializer(myKryo, DefaultExternalTask.class) {
- @Override
- protected DefaultExternalTask create(Kryo kryo, Input input, Class type) {
- return new DefaultExternalTask();
- }
- });
-
- myKryo.register(DefaultExternalPlugin.class, new FieldSerializer(myKryo, DefaultExternalPlugin.class) {
- @Override
- protected DefaultExternalPlugin create(Kryo kryo, Input input, Class type) {
- return new DefaultExternalPlugin();
- }
- });
-
- myKryo.register(DefaultExternalSourceSet.class, new FieldSerializer(myKryo, DefaultExternalSourceSet.class) {
- @Override
- protected DefaultExternalSourceSet create(Kryo kryo, Input input, Class type) {
- return new DefaultExternalSourceSet();
- }
- });
-
- myKryo.register(
- DefaultExternalSourceDirectorySet.class,
- new FieldSerializer(myKryo, DefaultExternalSourceDirectorySet.class) {
- @Override
- protected DefaultExternalSourceDirectorySet create(Kryo kryo, Input input, Class type) {
- return new DefaultExternalSourceDirectorySet();
- }
- }
- );
-
- myKryo.register(DefaultExternalFilter.class, new FieldSerializer(myKryo, DefaultExternalFilter.class) {
- @Override
- protected DefaultExternalFilter create(Kryo kryo, Input input, Class type) {
- return new DefaultExternalFilter();
- }
- });
-
- myKryo.register(ExternalSystemSourceType.class, new DefaultSerializers.EnumSerializer(ExternalSystemSourceType.class));
-
- myKryo.register(LinkedHashSet.class, new CollectionSerializer() {
- @Override
- protected Collection create(Kryo kryo, Input input, Class type) {
- return new LinkedHashSet();
- }
- });
- myKryo.register(HashSet.class, new CollectionSerializer() {
- @Override
- protected Collection create(Kryo kryo, Input input, Class type) {
- return new HashSet();
- }
- });
- myKryo.register(Set.class, new CollectionSerializer() {
- @Override
- protected Collection create(Kryo kryo, Input input, Class type) {
- return new HashSet();
- }
- });
- }
-
-
- public void save(@Nonnull ExternalProject externalProject) {
- Output output = null;
- try {
- final String externalProjectPath = externalProject.getProjectDir().getPath();
- final File configurationFile =
- getProjectConfigurationFile(new ProjectSystemId(externalProject.getExternalSystemId()), externalProjectPath);
- if (!FileUtil.createParentDirs(configurationFile)) return;
-
- output = new Output(new FileOutputStream(configurationFile));
- myKryo.writeObject(output, externalProject);
- }
- catch (FileNotFoundException e) {
- LOG.error(e);
- }
- finally {
- StreamUtil.closeStream(output);
- }
- }
+ private static final Logger LOG = Logger.getInstance(ExternalProjectSerializer.class);
- @Nullable
- public ExternalProject load(@Nonnull ProjectSystemId externalSystemId, File externalProjectPath) {
- Input input = null;
- try {
- final File configurationFile = getProjectConfigurationFile(externalSystemId, externalProjectPath.getPath());
- if (!configurationFile.isFile()) return null;
+ private final Kryo myKryo;
- input = new Input(new FileInputStream(configurationFile));
- return myKryo.readObject(input, DefaultExternalProject.class);
+ public ExternalProjectSerializer() {
+ myKryo = new Kryo() {
+ @Override
+ public T newInstance(Class type) {
+ LOG.error("Serializing default type: " + type);
+ return super.newInstance(type);
+ }
+ };
+ configureKryo();
}
- catch (Exception e) {
- LOG.error(e);
- }
- finally {
- StreamUtil.closeStream(input);
+
+ private void configureKryo() {
+ myKryo.setAutoReset(true);
+
+ myKryo.setRegistrationRequired(true);
+ Log.set(Log.LEVEL_WARN);
+
+ myKryo.register(ArrayList.class, new CollectionSerializer() {
+ @Override
+ protected Collection create(Kryo kryo, Input input, Class type) {
+ return new ArrayList();
+ }
+ });
+ myKryo.register(HashMap.class, new MapSerializer() {
+ @Override
+ protected Map create(Kryo kryo, Input input, Class type) {
+ return new HashMap();
+ }
+ });
+ myKryo.register(HashSet.class, new CollectionSerializer() {
+ @Override
+ protected Collection create(Kryo kryo, Input input, Class type) {
+ return new HashSet();
+ }
+ });
+
+ myKryo.register(File.class, new FileSerializer());
+ myKryo.register(DefaultExternalProject.class, new FieldSerializer(myKryo, DefaultExternalProject.class) {
+ @Override
+ protected DefaultExternalProject create(Kryo kryo, Input input, Class type) {
+ return new DefaultExternalProject();
+ }
+ });
+
+ myKryo.register(DefaultExternalTask.class, new FieldSerializer(myKryo, DefaultExternalTask.class) {
+ @Override
+ protected DefaultExternalTask create(Kryo kryo, Input input, Class type) {
+ return new DefaultExternalTask();
+ }
+ });
+
+ myKryo.register(DefaultExternalPlugin.class, new FieldSerializer(myKryo, DefaultExternalPlugin.class) {
+ @Override
+ protected DefaultExternalPlugin create(Kryo kryo, Input input, Class